Loading...

September 26, 2016

Awesome Asciidoctor: Trick To Use Caption Labels And Numbers In References

In Asciidoctor we can add an anchor with an ID to a section or title and then reference it in a link. The title of the section is used as link text. We can alter that when we define the link, but if we rely on the default behaviour we create a title for our section including the caption label and number. This way the created link points to the correct section and the text contains the caption text and number for that section.

In the following example markup we can see how we can use the caption label and section counter as attributes in the title. We do this with the title attribute of a section. By using the single quotes we tell Asciidoctor to interpret the attributes. We must also make sure we set the caption attribute to an empty string value. This disables the default caption creation of Asciidoctor for our section. Finally we need to provide an ID for the section using the #ID syntax:

= Code examples
// Enable the captions for listing blocks.
:listing-caption: Listing

== Creating an application

To create a simple Ratpack application we write
the following code:

// Our listing block has an id of SimpleJavaApp,
// so we can reference it as a link.
// The link text is the title of this listing block.
// We use the listing caption support of Asciidoctor
// in our title with the attributes listing-caption
// and counter:refnum. The value of listing-caption
// is defined with a document attribute (Listing)
// and counter:refnum contains the counter value
// for listing blocks.
// Finally we empty the caption attribute, otherwise
// the default caption rule is used to show Level {counter}.
[#SimpleJavaApp,source,java,caption='',title='{listing-caption} {counter:refnum}. Simple Java Ratpack application']
----
package com.mrhaki;

import ratpack.server.RatpackServer;

public class Main {
    public static void main(String... args) throws Exception {
        RatpackServer.start(server ->
            server
                .handlers(chain ->
                    chain
                        .get(ctx -> ctx.render("Hello World!"))));
    }
}
----

// A second section also with an ID 
// and custom caption and title attributes.
[#SimpleGroovyApp,source,groovy,caption='',title='{listing-caption} {counter:refnum}. Simple Groovy Ratpack application']
----
package com.mrhaki

import static ratpack.groovy.Groovy.ratpack

ratpack {
    handlers {
        get {
            render "Hello World!"
        }
    }
}
----

// In these paragraphs we create a link to the sections with
// id's SimpleJavaApp and SimpleGroovyApp. The text of the links
// will be Listing 1. Simple Java Ratpack application and
// Listing 2. Simple Groovy Ratpack application.
As we can see in <<SimpleJavaApp>> the code is simple. The configuration
of the Ratpack application is done using a series of methods.

With the Groovy code in <<SimpleGroovyApp>> we can use a DSL to define
the application. This results in even better readable code.

When we generate a HTML version of this markup we get the following result:

Written with Asciidoctor 1.5.4.

Awesome Asciidoctor: Use Captions For Listing Blocks

Asciidoctor has some built-in attributes to work with captions for certain content blocks. For example the table-section attribute defines the caption label (by default Table) that is prefixed to a counter for all tables in the document. When we transform our markup Asciidoctor will insert the text Table followed by the table number. By default the caption for listing blocks is disabled, but we can easily enable it with the listing-caption attribute.

In the following markup we enable the caption for listing blocks and set the value to Listing. This will add the text Listing followed by the listing section counter to the output.

= Code examples
// Enable numbered captions
// for listing blocks.
// We define the constant Listing
// as a caption value. This will be
// followed by a counter.
:listing-caption: Listing

== Creating an application

To create a simple Ratpack application we write
the following code:

.Simple Java Ratpack application
[source,java]
----
package com.mrhaki;

import ratpack.server.RatpackServer;

public class Main {
    public static void main(String... args) throws Exception {
        RatpackServer.start(server ->
            server
                .handlers(chain ->
                    chain
                        .get(ctx -> ctx.render("Hello World!"))));
    }
}
----

.Simple Groovy Ratpack application
[source,groovy]
----
package com.mrhaki

import static ratpack.groovy.Groovy.ratpack

ratpack {
    handlers {
        get {
            render "Hello World!"
        }
    }
}
----

When we generate the HTML for this markup we see the caption for the two listing blocks:

To disable the listing captions we must negate the document attribute: :!listing-caption:.

Written with Asciidoctor 1.5.4.

Awesome Asciidoctor: Customize the Figure Captions

With Asciidoctor we can use images in our documents with the image directive. When the document is converted each image gets a caption. By default the caption label is Figure followed a number for the position of the image in the document. So the first image has a caption Figure 1.. If we add a block title (text prefixed with a .) to the image then that text is used in the caption as well. We can customize the caption label, figure counter, caption text or disable the figure caption using a combination of document and image attributes.

We have the following Asciidoctor markup. We include several images and customize the figure caption settings. To change the caption label (Figure) we set a different value for the document attribute figure-caption. In our example we use the value Logo. Any captions following this definition will have the label Logo.

To use a separate counter we can use a counter attribute inside the caption attribute for our image. In our example we use this for the Gradle logo. If we want to use another caption text instead of the block title we can use the title attribute for an image.

Finally to disable all figure captions we negate the figure-caption document attribute.

= Figure caption

// Default the figure caption
// label is Figure.
.SDKMAN!
image::./sdkman-logo.png[]

// Set caption for figures
// for the rest of the document
// to the value Logo.
:figure-caption: Logo

// The figure caption label is Logo.
.Groovy
image::./groovy-logo.png[]

// Custom caption label for this image
// where we can still use a counter.
.Gradle
image::./gradle-logo.png[caption="Logo 1-{counter:logo}"]

// Instead of using the image block
// title in the caption we define
// our own caption text with the title
// attribute.
.Ratpack
image::./ratpack-logo.png[title="Ratpack library"]

// Disable all captions for figures.
:!figure-caption:

.Grails
image::./grails-logo.png[]

When we transform this markup to HTML we get the following output:


Written with Asciidoctor 1.5.4.

September 20, 2016

Awesome Asciidoctor: Change Level Offset For Included Documents

When we use the include directive to include another document we can must make sure the included document fits the levels of our main document. For example the included document shouldn't have level 0 headings if the main document already contains a level 0 heading. We can change the level offset in the main document before including another document. This will change the heading levels for the included document so all heading rules are okay.

To change the level offset we use the document attribute leveloffset. It is best to use a relative value, so if the included document also contains included document the output will still be okay and the heading rules still apply. Alternatively we can use the leveloffset attribute for the include directive. In the following sample document we include other files with a level 0 heading:

// File: book.adoc
= Include other files
// Include section numbers.
:sectnums:

// The file `chapter1.adoc` has a level 0 heading.
// To make sure it can be included we
// increase the level offset.
:leveloffset: +1

include::chapter1.adoc[]

// Reset level offset.
:leveloffset: -1
// Or use :leveloffset: 0

// We can also use the `leveloffset` attribute
// of the `include` directive. The level offset
// is then automatically reset.
include::chapter2.adoc[leveloffset=+2]

Here is the source for the included files:

// File: chapter1.adoc
= First chapter

Sample document to be included.
// File: chapter2.adoc
= First chapter

Sample document to be included.

When we transform book.adoc to HTML with Asciidoctor we get the following result:


Written with Asciidoctor 1.5.4.

Gradle Goodness: Use Command Line Options With Custom Tasks

Suppose we have a custom task with some properties that can be configured. Normally we would add the configuration in the build script. But we can also use command line options to configure a task. So when we run the task from the command line we can provide a configuration value for the task on the command line. To see which command line options are available for a task we can use the Gradle built-in task help followed by the option --task and the task name. To indicate a property as command line option we use a @Option annotation. We can specify the name of the command line option, a short description and also the order that is used to display the options with the help task.

Let's create a sample custom task and use the @Option annotation. In the following build file we create a custom task GenerateVersionFile. This task generates a file with a default name of version.txt in the build/ directory. The file contains the project version value. We make the property that defines the output filename as a command line option. This way the name can be defined when we run Gradle (and still of course using the default configuration in a build file).

// Import Option annotation
import org.gradle.api.internal.tasks.options.Option

version = 'demo'

// Create a task of the custom task type GenerateVersionFile.
task generateVersionFile(type: GenerateVersionFile)

/**
 * Custom task to generate a version value in a file.
 */
class GenerateVersionFile extends DefaultTask {
    
    String version

    // Specify outputFile property as
    // command line option.
    // Use as --outputFile filename.
    @Option(option = "outputFile", 
            description = "File to store the project version in",
            order = 1)
    Object outputFile
    
    GenerateVersionFile() {
        // Set default value for outputFile as version.txt.
        outputFile = 'version.txt'
        
        // Description for the task.
        description = 'Generate a file with the project version'
    }

    @TaskAction
    void generate() {
        // Create directory for the output file if 
        // it doesn't exist.
        final File versionFileDestination = getOutputFile()
        project.mkdir(versionFileDestination.parentFile)
        
        // Save version in file.
        versionFileDestination.text = getVersion()
    }

    @Input
    String getVersion() {
        return project.version
    }
    
    @OutputFile
    File getOutputFile() {
        return new File(project.buildDir, outputFile)
    }
    
}

If we run the help task for the generateVersionFile task we can see that our command line option is shown in the list of available options:

$ gradle help --task generationVersionFile
:help
Detailed task information for generateVersionFile

Path
     :generateVersionFile

Type
     GenerateVersionFile (GenerateVersionFile)

Options
     --outputFile     File where the project version is stored

Description
     Generate a file with the project version

Group
     -

BUILD SUCCESSFUL

Total time: 2.933 secs
$

Now we invoke the generateVersionFile task with a value for the command line option:

$ gradle generateVersionFile --outputFile version.saved
:generateVersionFile

BUILD SUCCESSFUL

Total time: 0.826 secs
$ more build/version.saved
demo
$

Written with Gradle 3.1.

September 19, 2016

Gradle Goodness: Change Gradle Wrapper Script Name

With the Gradle Wrapper task we can specify the name of the generated script files. By default the names are gradlew and gradlew.bat. The Wrapper task has the property scriptFile. We can set a different value for this property to let Gradle generate the script files with a different name.

In the following example we use the value mvnw (they will be surprised the build is so fast... ;-)) as the value:

task gradleWrapper(type: Wrapper) {
    scriptFile = 'mvnw'
}

Let's run the gradleWrapper task:

$ gradle gradleWrapper
:gradleWrapper

BUILD SUCCESSFUL

Total time: 8.597 secs
$ ls mvnw*
mvnw     mvnw.bat
$

Written with Gradle 3.1.

Gradle Goodness: Specify Wrapper Version and Distribution Type From Command Line

Gradle has the built-in task wrapper to create a Gradle wrapper. The Gradle wrapper can be part of our project so other people can build our project with Gradle, without the need for them to install Gradle. Also if we specify the Gradle wrapper we can make sure the correct Gradle version is used. To specify the version we must use the option --gradle-version. This version can be different than the Gradle version we use to create the Gradle wrapper. Since Gradle 3.1 we can also specify the distribution type of the Gradle wrapper. We choose between a binary distribution or the all distribution, which contains documentation and source code. Especially IDEs like to have the all distribution type, so they can provide better help in their editors.

With the following wrapper command we create a wrapper for Gradle 3.1 and the all distribution type. For a binary distribution we either use the value bin or we don't specify the option, so Gradle falls back to the default value bin.

$ gradle wrapper --gradle-version 3.1 --distribution-type all
:wrapper

BUILD SUCCESSFUL

Total time: 1.012 secs

$

We can check the file gradle/wrapper/gradle-wrapper.properties and look for the key distributionUrl. We see the value points to the correct Gradle version and distribution type:

$ more gradle/wrapper/gradle-wrapper.properties
#Mon Sep 19 15:26:27 CEST 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.1-all.zip
$

Written with Gradle 3.1

September 16, 2016

Awesome Asciidoctor: Use Counters in Markup

In Asciidoctor we can create a document attribute as a counter attribute. The attribute is automatically incremented each time we use it in our markup. We can choose to use numbers or characters. Only latin characters from 'a' to 'z' or 'A' to 'Z' are allowed. By default the counter will start at 1, but we can define another start value when we use the counter attribute for the first time.

To define a counter attribute we must prefix the attribute name with counter:. Each time we use this syntax with the counter: prefix the value is incremented and displayed. To only display the current value, without incrementing, we simply refer to the document attribute without the counter: prefix. For example if we want to add a counter attribute with the name steps we would use the following markup in Asciidoctor: {counter:steps}.

To increment the counter without display it we must replace counter: with counter2:. The value of the attribute is incremented but not displayed. So to increment our steps attribute we would use the syntax: {counter2:steps}. To get the current value without incrementing we simply use {steps}.

To start with a different value than 1 we can suffix the attribute name with :<:start-value>. Let's look at how we would create the steps counter attribute starting from 100: {counter:steps:100}. To have a counter with letters we define the start value as a letter from which we want to count: {counter:steps:A}.

In the following example markup we see different usages of the counter support in Asciidoctor:

== Counters

In Asciidoctor we can use counters. To use them
we ({counter:usage}) use a document attribute
prefixed with `counter:` and ({counter:usage}) use it again
to increment the counter.

Instead of numbers we can use characters. To use them
we ({counter:usageChar:A}) use a document attribute
prefixed with `counter:` and suffix `:A` and ({counter:usageChar}) use it again
to increment the counter.

=== Current value

Current value for a counter can be obtained by just referring to document attribute name. 
Value counter is *{usage}*.

=== Increment

{counter2:usage} We can also increment the counter without displaying the value. 
On the next increment the value is *{counter:usage}*.

=== Start at

To start at another number than 1 we can specify the starting counter value as 
a suffix to the counter attribute as `:<start>`.

{counter:sample:10}. do something followed by {counter:sample}. something else.

When we transform this to HTML with Asciidoctor we get the following result:


Written with Asciidoctor 1.5.4.

Spocklight: Custom Default Responses for Stubs

Although I couldn't make it to Gr8Conf EU this year, I am glad a lot of the presentations are available as slide decks and videos. The slide deck for the talk Interesting nooks and crannies of Spock you (may) have never seen before by Marcin ZajÄ…czkowski is very interesting. This is really a must read if you use Spock (and why shouldn't you) in your projects. One of the interesting things is the ability to change the response for methods in a class that is stubbed using Spock's Stub method, but have no explicit stubbed method definition.

So normally when we create a stub we would add code that implements the methods from the stubbed class. In our specification the methods we have written are invoked instead of the original methods from the stubbed class. By default if we don't override a method definition, but it is used in the specification, Spock will try to create a response using a default response strategy. The default response strategy for a stub is implemented by the class EmptyOrDummyResponse. For example if a method has a return type Message then Spock will create a new instance of Message and return it to be used in the specification. Spock also has a ZeroOrNullResponse response strategy. With this strategy null is returned for our method that returns the Message type.

Both response strategies implement the IDefaultResponse interface. We can write our own response strategy by implementing this interface. When we use the Stub method we can pass an instance of our response strategy with the defaultResponse named argument of the method. For example: MessageProvider stub = Stub(defaultResponse: new CustomResponse()). We implement the respond
method of IDefaultResponse to write a custom response strategy. The method gets a IMockInvocation instance. We can use this instance to check for example the method name, return type, arguments and more. Based on this we can write code to return the response we want.

In the following example we have a Spock specification where we create a stub using the default response strategy, the ZeroOrNullResponse strategy and a custom written response strategy:

package com.mrhaki.spock

@Grab('org.spockframework:spock-core:1.0-groovy-2.4')
import spock.lang.Specification
import spock.lang.Subject
import org.spockframework.mock.ZeroOrNullResponse
import org.spockframework.mock.IDefaultResponse
import org.spockframework.mock.IMockInvocation

class SampleSpec extends Specification {

    def """stub default response returns
           instance of Message created with default constructor"""() {
        given: 'Use default response strategy EmptyOrDummyResponse'
        final MessageProvider messageProvider = Stub()
        final Sample sample = new Sample(messageProvider)

        expect:
        sample.sampleMessage == 'Sample says: default'
    }

    def "stub default reponse returns null with ZeroOrNullResponse"() {
        given: 'Use default response strategy of ZeroOrNullResponse'
        final MessageProvider messageProvider =
                Stub(defaultResponse: ZeroOrNullResponse.INSTANCE)
        final Sample sample = new Sample(messageProvider)

        when:
        sample.sampleMessage

        then: 'messageProvider.message returns null'
        thrown(NullPointerException)
    }

    def """stub default response returns
           Message object with initialized text property
           from StubMessageResponse"""() {
        given: 'Use custom default response strategy'
        final MessageProvider messageProvider =
                Stub(defaultResponse: new StubMessageResponse())
        final Sample sample = new Sample(messageProvider)

        expect:
        sample.sampleMessage == 'Sample says: *STUB MESSAGE TEXT*'
    }

}

/**
 * Class to test with a dependency on MessageProvider
 * that is stubbed in the specification.
 */
class Sample {
    private final MessageProvider messageProvider

    Sample(final MessageProvider messageProvider) {
        this.messageProvider = messageProvider
    }

    String getSampleMessage() {
        "Sample says: ${messageProvider.message.text}"
    }

    String sampleMessage(String prefix) {
        "Sample says: ${messageProvider.getMessageWithPrefix(prefix).text}"
    }
}

/**
 * Work with messages. This interface is stubbed
 * in the specification.
 */
interface MessageProvider {
    Message getMessage()
    Message getMessageWithPrefix(String prefix)
}

/**
 * Supporting class for MessageProvider.
 */
class Message {
    String text = 'default'
}

/**
 * Custom default response strategy.
 * When a method has a Message return type then we
 * create an instance of Message with a custom text
 * property value.
 * Otherwise rely on default behaviour.
 */
class StubMessageResponse implements IDefaultResponse {
    @Override
    Object respond(IMockInvocation invocation) {
        // If return type of method is Message we create
        // a new Message object with a filled text property.
        if (invocation.method.returnType == Message) {
            return new Message(text: '*STUB MESSAGE TEXT*')
        }

        // Otherwise use default response handler for Stubs.
        return ZeroOrNullResponse.INSTANCE.respond(invocation)
    }
}

Written with Spock 1.0-groovy-2.4.

September 15, 2016

Awesome Asciidoctor: Replacements For Text To Symbols

With Asciidoctor we can use text to describe a symbol in our markup. The text is automatically transformed to a Unicode replacement. For example if we use the text (C) it is converted to &#169; which is the copyright symbol: ©.

In the following sample we see all the symbol replacements:

Written with Asciidoctor 1.5.2.