Sunday, February 4, 2018

Getting Started with Python's Virtualenv

This blog will teach you how to get started with virtualenv in Python. First install virtualenv if you have not installed it.
pip install virtualenv
Create a new virtualenv directory called hello.
virtualenv hello
The above command will a standard Python installation.
hello/
├── bin
├── include
├── lib
└── pip-selfcheck.json

To activate the virtualenv we just created, we need to source the activate script in the bin directory. Once we are in the virtualenv environment, we can install any Python libraries we want and the libraries will be installed in the hello virtualenv we just created, e.g.
cd hello
source bin/activate
pip install requests
To quit the virtualenv, simply type
deactivate
Let's now create a simple script that uses the new request module we just installed.
test.py
import requests

if __name__ == '__main__':
    r = requests.get('http://www.google.com')
    print(r.status_code)
To run the script in a virtualenv.
cd hello
source bin/activate
python test.py
deactivate

Friday, January 12, 2018

Getting Started with Java Module System

In this blog, I'm going to teach you how to get started with Java module system.
build.gradle
apply plugin: "java"

sourceCompatibility = 1.9

Now let's add module-info.java and put it in the root project.
module jigsaw {
}

Your project structure should look like this.
|-- build.gradle
`-- src
    `-- main
        `-- java
            |-- jigsaw
            |   `-- Main.java
            `-- module-info.java
Let's now build the JAR using Gradle.
gradle

Type the following command to run the application.
java --module-path build/libs -m jigsaw/jigsaw.Main

We can still run the JAR with a module system using a standard classpath.
java -cp build/libs/jigsaw.jar jigsaw.Main

In order to make it easy to distribute the application and to reduce the Java runtime size, we can create a custom Java runtime image using jlink.
jlink --module-path "build/libs;$JAVA_HOME/jmods" --add-modules jigsaw --output jigsaw

The command above creates a Java runtime image in the directory called jigsaw.
jigsaw          
|-- bin    
|-- conf   
|-- legal  
|-- lib    
`-- release

By using jlink, the jigsaw module that we just created will be part of the Java runtime image. You will not see the jigsaw JAR gets in the Java runtime image. If you run this command below, you will see the jigsaw module is now part of the image.
$ cd jigsaw
$ bin/java --list-modules
java.base@9.0.1
jigsaw

We can now run the jigsaw module by running the Java executable inside the Java runtime image without having to specify -m option.
$ cd jigsaw
$ bin/java -m jigsaw/jigsaw.Main

Friday, June 30, 2017

How to a Build Standalone REST Application in Java

There are many frameworks that allow you to build REST easily in Java. In this blog, however, I am going tho show you how to build a standalone REST application without any framework. We are going to use the following libraries:
  1. Jetty for web server
  2. Jersey for REST
  3. Jackson for JSON
  4. Swagger for API documentation

First we need the build script. I am going to use Gradle for this.
plugins {
    id "com.github.johnrengelman.shadow" version "2.0.1"
    id "java"
}

apply plugin: "java"
apply plugin: "com.github.johnrengelman.shadow"

defaultTasks = ["clean", "build", "shadowJar"]

repositories {
    jcenter()
}

dependencies {
    // Jetty dependencies
    compile "org.eclipse.jetty:jetty-server:9.4.6.v20170531"
    compile "org.eclipse.jetty:jetty-servlet:9.4.6.v20170531"

    // Jersey dependencies
    compile "org.glassfish.jersey.core:jersey-server:2.25.1"
    compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.25.1"
    compile "org.glassfish.jersey.containers:jersey-container-servlet:2.25.1"

    // Swagger dependencies
    compile "io.swagger:swagger-core:1.5.15"
    compile "io.swagger:swagger-annotations:1.5.15"
    compile "io.swagger:swagger-jersey2-jaxrs:1.5.15"
    // Required by BeanConfig
    runtime "org.codehaus.groovy:groovy:2.4.12"

    // Required by Swagger
    runtime "ch.qos.logback:logback-core:1.2.3"
    runtime "ch.qos.logback:logback-classic:1.2.3"
}

jar {
    manifest {
        attributes "Main-Class": "org.fredy.example.rest.HelloServer"
    }
}

Second, we will write a typical JAX-RS application with JAX-RS, Jackson, and Swagger annotations.
package org.fredy.example.rest;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Api(value = "/hello", description = "API for Hello")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/hello")
public class HelloResource {
    @ApiModel("request")
    public static class HelloRequest {
        @ApiModelProperty(value = "The name", required = true)
        private final String name;

        @JsonCreator
        public HelloRequest(@JsonProperty("name") String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    @ApiModel("response")
    public static class HelloResponse {
        @ApiModelProperty(value = "The message", required = true)
        private final String message;

        @JsonCreator
        public HelloResponse(@JsonProperty("message") String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }
    }

    @ApiOperation(value = "Gets the message", response = HelloResponse.class)
    @ApiResponse(code = 200, message = "Successful operation")
    @Path("/message")
    @POST
    public Response getMessage(HelloRequest request) {
        return Response.ok(new HelloResponse("Hello, " + request.getName())).build();
    }
}

Third, we will need to register our REST resource into Jetty and start the server.
package org.fredy.example.rest;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.servlet.ServletContainer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.util.StringJoiner;

public class HelloServer {
    public static class Bootstrap extends HttpServlet {
        @Override
        public void init(ServletConfig config) throws ServletException {
            super.init(config);

            BeanConfig beanConfig = new BeanConfig();
            beanConfig.setTitle("Hello API");
            beanConfig.setVersion("1.0.0");
            beanConfig.setSchemes(new String[]{"http"});
            beanConfig.setBasePath("/api");
            beanConfig.setResourcePackage("org.fredy.example.rest");
            beanConfig.setScan(true);
        }
    }

    public static void main(String[] args) throws Exception {
        ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        servletHandler.setContextPath("/");

        ServletHolder jerseyServlet = servletHandler.addServlet(ServletContainer.class, "/api/*");
        jerseyServlet.setInitOrder(0);

        jerseyServlet.setInitParameter(
            ServerProperties.PROVIDER_CLASSNAMES,
            new StringJoiner(",")
                .add(HelloResource.class.getCanonicalName())
                .add(JacksonJsonProvider.class.getCanonicalName())
                .add(ApiListingResource.class.getCanonicalName())
                .add(SwaggerSerializers.class.getCanonicalName())
            .toString());

        ResourceHandler staticHandler = new ResourceHandler();
        staticHandler.setWelcomeFiles(new String[]{"index.html"});
        staticHandler.setBaseResource(Resource.newClassPathResource("/webapp"));

        HandlerList handlers = new HandlerList();
        // Add two handlers, one for static content and the other one for dynamic content.
        handlers.setHandlers(new Handler[]{staticHandler, servletHandler});

        // The mapping doesn't really matter here.
        ServletHolder swaggerServlet = servletHandler.addServlet(Bootstrap.class, "/");
        swaggerServlet.setInitOrder(2);

        Server jettyServer = new Server(8080);
        jettyServer.setHandler(handlers);

        try {
            jettyServer.start();
            jettyServer.join();
        } finally {
            jettyServer.destroy();
        }
    }
}

Few important things to note.
  1. Add the Jersey servlet container (org.glassfish.jersey.servlet.ServletContainer). This servlet implementation comes from Jersey library.
  2. Register some providers, such as our own REST provider (org.fredy.example.rest.HelloResource), Jackson provider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider), and Swagger providers (io.swagger.jaxrs.listing.ApiListingResource and io.swagger.jaxrs.listing.SwaggerSerializers). The Swagger providers will create swagger.json specified by the servlet mapping path, which is api/swagger.json in this case.

Lastly, we need to add some Swagger UI so that we can display the API documentation in a nice format. What we need is basically download Swagger UI from https://github.com/swagger-api/swagger-ui and copy the dist directory into src/main/resources. The goal of this is to keep the Swagger UI in the JAR and is available in the classpath. Swagger UI is just a static content and we can tell Jetty to serve static content by using org.eclipse.jetty.server.handler.ResourceHandler. Make sure to modify the URL in Swagger's index.html from http://petstore.swagger.io/v2/swagger.json to http://localhost:8080/api/swagger.json since that's where our swagger.json file lives. To build and run the example, we can type the following command.
./gradlew && java -jar build/libs/java-rest-swagger-example-all.jar
Full source code can be found here.

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 com.google.guava to org.fredy.com.google.guava.
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.fredy</groupId>
  <artifactId>shaded</artifactId>
  <version>0.0.1</version>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.fredy</groupId>
      <artifactId>myjar</artifactId>
      <version>0.0.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <relocations>
            <relocation>
              <pattern>com.google.common</pattern>
              <shadedPattern>org.fredy.com.google.common</shadedPattern>
            </relocation>
          </relocations>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <filters>
                <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                  </excludes>1
                </filter>
              </filters>
              <promoteTransitiveDependencies>true</promoteTransitiveDependencies>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

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 (
    "context"
    "fmt"
    "time"
)

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():
                return
            }
        }
    }(ctx)
    busyChan <- true
    fmt.Println("Doing some other things")
    time.Sleep(3 * time.Second)
    fmt.Println("Stopping the goroutine")
    cancel()
}
Output:
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(\"java.io.File\");" +
            "print(new File(\".\").exists());" +
            "var map = {\"msg\": \"Hello from JS\"};" +
            "print(javaClass.greet());" +
            "map;";

        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);
        System.out.println(retVal.get("msg"));
    }
}
Output:
true
Hello from Java
Hello from JS

Wednesday, December 14, 2016

How to Use Jetty to Serve Static Content

  1. Download Jetty.
  2. Extract it to some location. We will call this JETTY_HOME.
  3. Set JETTY_BASE environment variable. This is a separate directory where your configurations live.
  4. Copy $JETTY_HOME/start.ini into $JETTY_BASE.
  5. Create $JETTY_BASE/webapps directory.
  6. Create $JETTY_BASE/webapps/scratch.xml with the content explained here.
  7. Start Jetty by running $JETTY_HOME/bin/jetty.sh start.
  8. Stop Jetty by running $JETTY_HOME/bin/jetty.sh stop.


Sunday, August 21, 2016

How to Use Vendoring in Go

Vendoring is a way to put dependencies in a Go project without having to mess with the GOPATH. The idea is simple, that is to put the dependencies in a directory called "vendor".
awesomego/
|-- foo (this directory contains a library, i.e. non-main package)
|   `-- foo.go
|-- main.go (this is the main program)
`-- vendor (this is where the third-party libs live)
    `-- goini
        |-- goini.go
        |-- goini_test.go
        |-- LICENSE
        |-- README.md
        `-- testdata
            |-- test_expected.ini
            `-- test.ini

The project structure above has the following benefits.
  1. It can be used to build a library.
  2. It can be used to build an executable.
  3. It is go-gettable.
This is an example of using it in a standard Go workspace.
go-workspace/
`-- src
    `-- awesomego
        |-- foo
        |   `-- foo.go
        |-- main.go
        `-- vendor
            `-- goini
                |-- goini.go
                |-- goini_test.go
                |-- LICENSE
                |-- README.md
                `-- testdata
                    |-- test_expected.ini
                    `-- test.ini
To build it as a library:
GOPATH=`pwd` go install awesomego/foo
To build it as an executable:
GOPATH=`pwd` go install awesomego

Wednesday, August 3, 2016

Compile-Time Enum in Go

Unlike other languages, Go does not support enum. However, it is pretty straightforward to create something that behaves similar to enum. There are a lot of articles on the internet on how to create an enum in Go, which pretty much looks like below.
package main

import (
    "fmt"
)

type myType string

const (
    Foo myType = "foo"
    Bar myType = "bar"
)

func doSomething(t myType) {
    fmt.Println(t)
}

func main() {
    // baz := "baz"
    // This will result in compilation error:
    // "cannot use baz (type string) as type myType in argument to doSomething"
    // doSomething(baz)

    // However, this is allowed.
    doSomething("baz")
}
As you can see in the code above, calling doSomething("baz") does not result in a compilation error. To fix that, we can change the code to look like below.
package main

import (
    "fmt"
)

type myType string

const (
    Foo myType = "foo"
    Bar myType = "bar"
)

func doSomething(t *myType) {
    fmt.Println(*t)
}

func main() {
    // This will now result in a compilation error.
    // doSomething("baz")

    baz := myType("baz")
    doSomething(&baz)
}

Wednesday, July 6, 2016

Compile-time Builder Pattern in Java

Builder pattern is a pattern that is usually used for a language that does not support named parameters. However, the typical builder pattern has a limitation, such at it can't at compile-time check the required parameters. Below are some suggestions how to use a builder pattern that has compile-time check.
  • Option 1
  • public class Foo {
        private String a;
        private String b;
        private String c;
    
        private Foo() {
        }
    
        public static ABuilder newBuilder() {
            return new ABuilder(new Foo());
        }
    
        private static class ABuilder {
            private final Foo foo;
    
            private ABuilder(Foo foo) {
                this.foo = foo;
            }
    
            public BBuilder a(String a) {
                foo.a = a;
                return new BBuilder(foo);
            }
        }
    
        private static class BBuilder {
            private final Foo foo;
    
            private BBuilder(Foo foo) {
                this.foo = foo;
            }
    
            public CBuilder b(String b) {
                foo.b = b;
                return new CBuilder(foo);
            }
        }
    
        private static class CBuilder {
            private final Foo foo;
    
            private CBuilder(Foo foo) {
                this.foo = foo;
            }
    
            public FinalBuilder c(String c) {
                foo.c = c;
                return new FinalBuilder(foo);
            }
        }
    
        private static class FinalBuilder {
            private final Foo foo;
    
            private FinalBuilder(Foo foo) {
                this.foo = foo;
            }
    
            public Foo build() {
                return foo;
            }
        }
    
        public static void main(String[] args) {
            Foo foo = Foo.newBuilder().a("a").b("b").c("c").build();
            System.out.println(foo);
        }
    }
    
  • Option 2
  • public class Bar {
        private final String a;
        private final String b;
        private final String c;
    
        public static class False {}
        public static class True {}
    
        public static class Builder<Has1, Has2, Has3> {
            private String a;
            private String b;
            private String c;
    
            public static Builder<False, False, False> create() {
                return new Builder<>();
            }
    
            public Builder<True, Has2, Has3> a(String a) {
                this.a = a;
                return (Builder<True, Has2, Has3>) this;
            }
    
            public Builder<Has1, True, Has3> b(String b) {
                this.b = b;
                return (Builder<Has1, True, Has3>) this;
            }
    
            public Builder<Has1, Has2, True> c(String c) {
                this.c = c;
                return (Builder<Has1, Has2, True>) this;
            }
        }
    
        public Bar(Builder<True, True, True> builder) {
            a = builder.a;
            b = builder.b;
            c = builder.c;
        }
    
        public static void main(String[] args) {
            Bar bar = new Bar(Builder.create().a("a").b("c").c("a"));
            System.out.println(bar);
        }
    }
    

Thursday, April 21, 2016

How to Create a Command Line Spinner in Go

package main

import "fmt"
import "time"

func main() {
    chars := "|/-\\"
    i := 0
    for {
        i++
        char := chars[i%len(chars)]
        fmt.Printf("\rDownloading: %c", char)
        time.Sleep(100 * time.Millisecond)
    }
}

Monday, August 17, 2015

Parallel Merge Sort using Fork and Join

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

public class MergeSortForkJoin {
    public static class MergeSortTask extends RecursiveAction {
        private static final long serialVersionUID = 1L;
        private final List<Integer> list;
        private final int lo;
        private final int hi;
        
        public MergeSortTask(List<Integer> list, int lo, int hi) {
            this.list = list;
            this.lo = lo;
            this.hi = hi;
        }
        
        @Override
        protected void compute() {
            if (lo >= hi) {
                return;
            } else {
                int mid = (lo + hi) / 2;
                MergeSortTask task1 = new MergeSortTask(list, lo, mid);
                MergeSortTask task2 = new MergeSortTask(list, mid+1, hi);

                invokeAll(task1, task2);

                merge(list, lo, mid, hi);
            }
        }
        
        private void merge(List<Integer> list, int lo, int mid, int hi) {
            List<Integer> tmp = new ArrayList<>();
            for (int i : list) {
                tmp.add(i);
            }
            int left = lo;
            int right = mid + 1;
            int idx = lo;
            while (left <= mid && right <= hi) {
                if (tmp.get(left) <= tmp.get(right)) {
                    Integer element = tmp.get(left);
                    list.set(idx, element);
                    left++;
                    idx++;
                } else {
                    Integer element = tmp.get(right);
                    list.set(idx, element);
                    right++;
                    idx++;
                }
            }
            while (left <= mid) {
                Integer element = tmp.get(left);
                list.set(idx, element);
                idx++;
                left++;
            }
            while (right <= hi) {
                Integer element = tmp.get(right);
                list.set(idx, element);
                idx++;
                right++;
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        ForkJoinPool pool = new ForkJoinPool();
        List<Integer> list = Arrays.asList(4, 9, 1, 5, 8, 0, 7, 6, 3, 2);
        System.out.println("Unsorted: " + list);
        MergeSortTask task = new MergeSortTask(list, 0, list.size()-1);
        try {
            do {
                pool.execute(task);
            } while (!task.isDone());
        } finally {
            pool.shutdown();
        }
        System.out.println("Sorted:   " + list);
    }
}

Monday, August 10, 2015

How to Organize a Go Project

The official has a good information on how to structure your Go code. In this blog, I am going to explain a little bit more about it. Let's say we want to create a Go project containing a command and a package.
workspace1/
|-- build.sh
`-- src
    `-- mylib
        |-- hello
        |   `-- hello.go (package)
        `-- main.go (command)
hello.go
package hello

import "fmt"

func SayHello() {
    fmt.Println("Hello")
}
main.go
package main

import "mylib/hello"

func main() {
    hello.SayHello()
}
build.sh
#!/bin/bash

export GOPATH=`pwd`
go install mylib/hello
go install mylib
Calling build.sh will create this structure.
workspace1/
|-- bin
|   `-- mylib (executable)
|-- build.sh
|-- pkg
|   `-- linux_amd64
|       `-- mylib
|           `-- hello.a (library)
`-- src
    `-- mylib
        |-- hello
        |   `-- hello.go (package)
        `-- main.go (command)
In order to make mylib project go-gettable, let's make it into a Git project. Take a note that we will be creating a Git project in the mylib directory and not in the workspace1 directory.
1. cd workspace1/src/mylib
2. git init
3. git add .
4. git commit -m "Initial commit"
5. Push this repository to the remote URL
Now let's create another project that uses mylib. This new project is a simple project that uses mylib.
workspace2/
|-- build.sh
`-- src
    `-- myapp
        `-- app
            `-- app.go (command)
1. cd workspace2
2. git init
3. git add submodule [mylib_git_url] src/mydomain/user/mylib (the src/mydomain/user is just a convention, you can also set the path to src/mylib)
After the submodule addition, we will have this structure.
workspace2/
|-- build.sh
`-- src
    |-- myapp
    |   `-- app
    |       `-- app.go (command)
    `-- mydomain
        `-- user
            `-- mylib
                |-- hello
                |   `-- hello.go (package)
                `-- main.go (command)
app.go
package main

import (
    "fmt"
    "mydomain/user/mylib/hello"
)

func main() {
    fmt.Println("Do something")
    hello.SayHello()
}
build.sh
#!/bin/bash

export GOPATH=`pwd`
go install mydomain/user/mylib/hello
go install myapp/app
Calling build.sh will create this structure.
workspace2/
|-- bin
|   `-- app (executable)
|-- build.sh
|-- pkg
|   `-- linux_amd64
|       `-- mydomain
|           `-- user
|               `-- mylib
|                   `-- hello.a (library)
`-- src
    |-- myapp
    |   `-- app
    |       `-- app.go (command)
    `-- mydomain
        `-- user
            `-- mylib
                |-- hello
                |   `-- hello.go (package)
                `-- main.go (command - not used)

Saturday, May 23, 2015

How to Create a Simple REST Server in Go

Below is an example on how to create a simple REST server in Go.
package main

import (
    "encoding/json"
    "log"
    "net/http"
    "strconv"
)

type Hello struct {
    Message string `json:"message"`
}

func HelloServer(w http.ResponseWriter, req *http.Request) {
    log.Println("Received a request from ", req.RemoteAddr)
    w.Header().Set("Content-Type", "application/json")
    if req.Method == "GET" {
        encoder := json.NewEncoder(w)
        hello := Hello{"Hello World"}
        encoder.Encode(hello)
    }
}

func main() {
    port := 8080
    // serve static content
    http.Handle("/", http.FileServer(http.Dir("html")))
    http.HandleFunc("/hello/", HelloServer)
    log.Println("Starting HTTP server at", port)
    err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
    if err != nil {
        log.Fatal("Unable to start the server: ", err)
    }
}

Tuesday, May 5, 2015

How to Cross Compile Go Programs

If you download the Go binary for a particular platform, most likely that go binary distribution does not come with support for cross-compiling.
cd myapp
GOOS=windows GOARCH=amd64 go build

go build runtime: windows/amd64 must be bootstrapped using make.bash
In order to add support for cross-compiling in your Go distribution, you need to do the following.
cd $GOROOT/src
GOOS=windows GOARCH=amd64 ./make.bash --no-clean
In this example I am adding cross-compile support to target Windows 64-bit.
cd myapp
GOOS=windows GOARCH=amd64 go build
Now you can easily build Windows 64-bit binaries on a Linux.

Friday, December 5, 2014

How to Edit an Excel File using C# with Excel Office Interop

Below is a simple example how to edit an Excel File using C# with Excel Office Interop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelBlog
{
    class Program
    {
        static void Main(string[] args)
        {
            var xlApp = new Excel.Application();
            var xlWorkbook = xlApp.Workbooks.Open(
                @"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\in.xlsx");
            var xlWorksheet = xlWorkbook.Worksheets["Sheet1"];
            var fullRow = xlWorksheet.Rows.Count;
            var lastRow = xlWorksheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row;
            var dict = new Dictionary<string, IList<string>>();
            for (int i = 1; i <= lastRow; i++)
            {
                var cell = xlWorksheet.Cells[i, "A"].Value;
                xlWorksheet.Cells[i, "A"].Value = cell + "" + i;
            }
            xlWorkbook.SaveAs(@"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\out.xlsx");
            xlWorkbook.Close();
        }
    }
}

Monday, October 6, 2014

How to Implement Policy Classes in C++

Policy-based class design is a powerful technique described in Modern C++: Generic Programming and Design Patterns Applied book. It's similar to a strategy design pattern, but with all the type-safety thanks to the use of C++ templates.

Below is a trivial example how to design a library with policy classes.

#include <iostream>
#include <string>
using namespace std;

template<class T>
struct HelloPolicy {
    static void saySomething(const T& t) {
        cout << "Hello World, " << t.getName() << endl;
    }
};

template<class T>
struct ByePolicy {
    static void saySomething(const T& t) {
        cout << "Bye World, " << t.getName() << endl;
    }
};

struct Foo {
    string getName() const {
        return "Foo";
    }
};

struct Bar {
    string getName() const {
        return "Bar";
    }
};

template<template <class> class Policy>
class FooPolicy : public Policy<Foo> {
public:
    void doSomething() {
        Foo foo;
        Policy<Foo>().saySomething(foo);
    }
};

template<template <class> class Policy>
class BarPolicy : public Policy<Bar> {
public:
    void doSomething() {
        Bar bar;
        Policy<Bar>().saySomething(bar);
    }
};

int main() {
    FooPolicy<HelloPolicy> f1;
    f1.doSomething();

    FooPolicy<ByePolicy> f2;
    f2.doSomething();

    BarPolicy<HelloPolicy> b1;
    b1.doSomething();

    BarPolicy<ByePolicy> b2;
    b2.doSomething();
    
    return 0;
 }
Output:
Hello World, Foo
Bye World, Foo
Hello World, Bar
Bye World, Bar

Tuesday, September 2, 2014

Java 8 Functional Interfaces

Java 8 has many functional interfaces as defined in the Javadoc. In this blog, I'm going to explain few important Java 8 functional interfaces.
  • Consumer<T>
    • Arguments: T
    • Returns: Void
  • Supplier<T>
    • Arguments: None
    • Returns: T
  • Function<T, R>
    • Arguments: T
    • Returns: R
  • Predicate<T>
    • Arguments: T
    • Returns: boolean
  • UnaryOperator<T>
    • Arguments: T
    • Returns: T
  • BinaryOperator<T>
    • Arguments: (T, T)
    • Returns: T
public class Java8 {
    public static void main(String[] args) {
        System.out.print("Consumer: ");
        Consumer<String> consumer = (s) -> {
            System.out.println(s);
        };
        consumer.accept("hello");

        System.out.print("Supplier: ");
        Supplier<String> supplier = () -> {
            return "foo";
        };
        System.out.println(supplier.get());
        
        System.out.print("Function: ");
        Function<Integer, String> function = (i) -> {
            return "func" + i;
        };
        System.out.println(function.apply(1));
        
        System.out.print("Predicate: ");
        Predicate<Integer> predicate = (i) -> {
            return i == 0;
        };
        System.out.println(predicate.test(0));
        
        System.out.print("UnaryOperator: ");
        UnaryOperator<Integer> unaryOperator = (i) -> {
            return i * 100;
        };
        System.out.println(unaryOperator.apply(2));
        
        System.out.print("BinaryOperator: ");
        BinaryOperator<Integer> binaryOperator = (i, j) -> {
            return i + j;
        };
        System.out.println(binaryOperator.apply(3, 5));
    }
}
Output:
Consumer: hello
Supplier: foo
Function: func1
Predicate: true
UnaryOperator: 200
BinaryOperator: 8

Friday, August 29, 2014

Creating Custom Serializer and Deserializer with Gson

Gson is a cool JSON library by Google. It can convert Java objects into their JSON representation and vice versa. In this blog, I'm going to show how to write custom serializer and deserializer with Gson for the following JSON structure.
{
  "root": {
    "node1-a": {
      "node2-a": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
      },
      "node2-b": {
        "key4": "value4",
        "key5": "value5"
      }
    },
    "node1-b": {
      "node2-a": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    "node1-c": {
      "node2-a": {
        "key1": "value1"
      }
    }
  }
}
public class Root {
    public final Map<String, Node1> map = new LinkedHashMap<String, Node1>();

    public Root put(String key, Node1 node) {
        map.put(key, node);
        return this;
    }

    /**
     * This is the next at level 1
     */
    public static class Node1 {
        public final Map<String, Node2> map = new LinkedHashMap<String, Node2>();

        public Node1 put(String key, Node2 node) {
            map.put(key, node);
            return this;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Node1 [map=");
            builder.append(map);
            builder.append("]");
            return builder.toString();
        }
    }

    /**
     * This is the node at level 2
     */
    public static class Node2 {
        public final Map<String, String> map = new LinkedHashMap<String, String>();

        public Node2 put(String key, String value) {
            map.put(key, value);
            return this;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Node2 [map=");
            builder.append(map);
            builder.append("]");
            return builder.toString();
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Root [map=");
        builder.append(map);
        builder.append("]");
        return builder.toString();
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Gson gson = new GsonBuilder().setPrettyPrinting()
            .registerTypeAdapter(Root.class, new RootSerializer())
            .registerTypeAdapter(Root.class, new RootDeserializer())
            .create();
        
        Root root = new Root()
            .put("node1-a", new Node1()
                .put("node2-a", new Node2()
                    .put("key1", "value1")
                    .put("key2", "value2")
                    .put("key3", "value3"))
                .put("node2-b", new Node2()
                    .put("key4", "value4")
                    .put("key5", "value5")))
            .put("node1-b", new Node1()
                .put("node2-a", new Node2()
                    .put("key1", "value1")
                    .put("key2", "value2")))
            .put("node1-c", new Node1()
                .put("node2-a", new Node2()
                    .put("key1", "value1")));
        
        gson.toJson(root, System.out);
        
        System.out.println();
        
        String json = String.join("\n", Files.readAllLines(Paths.get("test.json")));
        root = gson.fromJson(json, Root.class);
        System.out.println(root);
    }
}

public class RootSerializer implements JsonSerializer<Root> {
    @Override
    public JsonElement serialize(Root root, Type typeOfSrc,
        JsonSerializationContext context) {
        JsonObject node1JsonObj = new JsonObject();
        for (Map.Entry<String, Node1> n1Entry : root.map.entrySet()) {
            JsonObject node2JsonObj = new JsonObject();
            for (Map.Entry<String, Node2> n2Entry : n1Entry.getValue().map.entrySet()) {
                JsonObject jsonObj = new JsonObject();
                for (Map.Entry<String, String> e : n2Entry.getValue().map.entrySet()) {
                    jsonObj.addProperty(e.getKey(), e.getValue());
                }
                node2JsonObj.add(n2Entry.getKey(), jsonObj);
            }
            node1JsonObj.add(n1Entry.getKey(), node2JsonObj);
        }
        
        JsonObject rootJsonObject = new JsonObject();
        rootJsonObject.add("root", node1JsonObj);
        return rootJsonObject;
    }
}

public class RootDeserializer implements JsonDeserializer<Root> {
    @Override
    public Root deserialize(JsonElement rootJson, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
        Root root = new Root();
        JsonObject rootJsonObj = rootJson.getAsJsonObject();
        for (Map.Entry<String, JsonElement> rootJsonEntry : rootJsonObj.entrySet()) {
            JsonObject node1JsonObj = rootJsonEntry.getValue().getAsJsonObject();
            Node1 node1 = new Node1();
            for (Map.Entry<String, JsonElement> n1JsonEntry : node1JsonObj.entrySet()) {
                JsonObject node2JsonObj = n1JsonEntry.getValue().getAsJsonObject();
                Node2 node2 = new Node2();
                for (Map.Entry<String, JsonElement> n2JsonEntry : node2JsonObj.entrySet()) {
                    JsonObject jsonObj = n2JsonEntry.getValue().getAsJsonObject();
                    for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) {
                        node2.put(e.getKey(), e.getValue().getAsString());
                    }
                }
                node1.put(n1JsonEntry.getKey(), node2);
            }
            root.put(rootJsonEntry.getKey(), node1);
        }
        return root;
    }
}

Tuesday, July 22, 2014

How to Embed Python in C++

#include <iostream>
#include <string>
#include <Python.h>

using namespace std;

int main() {
    Py_Initialize();

    string statements =
        "a = 8\n"
        "b = 2\n"
        "c = (a * b) / 2";

    int retVal = PyRun_SimpleString(statements.c_str());
    if (retVal == 0) {
        PyObject* m = PyImport_AddModule("__main__");
        PyObject* v = PyObject_GetAttrString(m, "c");

        int c = PyInt_AsLong(v);
        cout << "c: " << c << endl;

        Py_DECREF(v);
    }
    Py_Finalize();
    return 0;
}
Output:
c: 8