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