Thursday, April 6, 2017

How to Shade a JAR and Relocate Classes in Maven

The example below shows how to shade org.fredy.myjar and guava JARS and rename the Guava classes that contain to
                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>

Friday, March 3, 2017

How to Cancel a Goroutine in Go

The example below shows how to cancel a goroutine while is in the middle of executing a long-running task.
package main

import (

func main() {
    busyChan := make(chan bool)

    ctx, cancel := context.WithCancel(context.Background())
    go func(ctx context.Context) {
        for {
            select {
            case <-busyChan:
                fmt.Println("Pretending to be very busy")
                time.Sleep(5000 * time.Second)
            case <-ctx.Done():
    busyChan <- true
    fmt.Println("Doing some other things")
    time.Sleep(3 * time.Second)
    fmt.Println("Stopping the goroutine")
Prentending to be very busy
Doing some other things
Stopping the goroutine

Wednesday, February 22, 2017

How to Embed JavaScript in Java

Java 8 came with a JavaScript engine called Nashorn. This makes it easy to call some JavaScript code from Java. In this example, I'm going to show how to pass some Java object into JavaScript and vice-versa as well as calling creating a Java object from JavaScript.
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import java.util.Map;

public class JsExample {
    public static class JavaClass {
        public String greet() {
            return "Hello from Java";

    public static void main(String[] args) throws Exception {
        final String script =
            "var File = Java.type(\"\");" +
            "print(new File(\".\").exists());" +
            "var map = {\"msg\": \"Hello from JS\"};" +
            "print(javaClass.greet());" +

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        Bindings bindings = new SimpleBindings();
        bindings.put("javaClass", new JavaClass());

        Map<String, String> retVal = (Map<String, String>) engine.eval(script, bindings);
Hello from Java
Hello from JS