Tuesday, April 14, 2015

Java Server Side Templating using Mustache.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;

/**
 * Simple java server side templating
 * @author Samar Aarkotti
 *
 */
public class Sample {

public static void main(String[] args) {
String template = "{\"products\": \"iPhone\"}";
String text = "How do I get my {{products}} serviced?";
Template tmpl = Mustache.compiler().compile(text);
try {
JSONObject jsonObj = new JSONObject(template);
Map<String,Object> map = getTemplateFromJson(jsonObj);
System.out.println(tmpl.execute(map));
} catch (JSONException e) {
e.printStackTrace();
}
}
private static Map<String, Object> getTemplateFromJson(JSONObject json) throws JSONException {
    Map<String,Object> out = new HashMap<String,Object>();
    Iterator<?> it = json.keys(); 
    while (it.hasNext()) {
        String key = (String)it.next();

        if (json.get(key) instanceof JSONArray) {

            // Copy an array
            JSONArray arrayIn = json.getJSONArray(key);
            List<Object> arrayOut = new ArrayList<Object>();
            for (int i = 0; i < arrayIn.length(); i++) {
                JSONObject item = (JSONObject)arrayIn.get(i);
                Map<String, Object> items = getTemplateFromJson(item);
                arrayOut.add(items);
            }
            out.put(key, arrayOut);
        }
        else {

            // Copy a primitive string
            out.put(key, json.getString(key));
        }
    }
    return out;
}

}

Expected Output : How do I get my iPhone serviced?

Create ElasticSearch cluster on single machine

I wanted to figure out how to create a multi-node ElasticSearch cluster on single machine. So i followed these instructions First i did...