Thursday, June 30, 2011

Mongo Java QueryBuilder Example

QueryBuilder helps construct complex queries to retrieve data from a collection in mongo db.

Following is an example of a QueryBuilder.

public List<Map<String, Object>> findList() { 
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        BasicDBObject document = new BasicDBObject();
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        QueryBuilder qb = new QueryBuilder();
        qb.or(new QueryBuilder().put("starting_date").is(null).put("ending_date").is(null).get(),
                new QueryBuilder().put("starting_date").lessThanEquals(now).put("ending_date").greaterThanEquals(now).get());
        document.putAll(qb.get());
        document.put("status", "running");
        DBCursor cursor = getDbCollection().find(document).sort(new BasicDBObject("reported_time", 1));
        while(cursor.hasNext()) {
            list.add((Map<String, Object>) cursor.next().toMap().get("message"));
        }
        return list;
    }



  •  QueryBuilder qb = new QueryBuilder(), instantiates a new QueryBuilder.
  • The logic build by the QueryBuilder in the example above is;  (starting date = null and ending date = null) or (starting date >= now and ending date >= now) .  [qb.or(new QueryBuilder().put("starting_date").is(null).put("ending_date").is(null).get(),
                    new QueryBuilder().put("starting_date").lessThanEquals(now).put("ending_date").greaterThanEquals(now).get());]
  • document.putAll(qb.get()) adds the logic constructed to the DBObject.

thanks,
Shyarmal.

    Wednesday, June 15, 2011

    Singleton pattern (Java)

    The objective of the singleton pattern is to restrict the instantiation of a class to one object. Following is a simple example of a singleton class;

    A singleton class should;
    • Hold private static instance of itself;
    • Have it's constructors to be in private access level.
    • A non-private static method to return the above mentioned instance.

    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    package com.basic;

    import java.util.logging.Logger;

    public class Singleton {

        private static Singleton mySingleton = null;
        private static final Logger logger = Logger.getLogger("Singleton");
       
        private Singleton(){
            logger.info("constructor");
        }
       
        public static synchronized Singleton getInstance(){
            logger.info("get instance");
            if(mySingleton == null){
                logger.info("instance null");
                mySingleton = new Singleton();
            }
            return mySingleton;
        }
    }

    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    The above class cannot be instantiated from any other class since it's constructor is private. Furthermore it holds an instance of itself, which is instantiated in the first call to the method getInstance(). The same instance will be returned to all subsequent calls to the getInstance() method.

    thanks,
    Shyarmal.

    Simple DOM example (Java)

    The following is a simple example of the DOM parser, which creates an XML document and outputs the document to the console.

     package src;

    import java.io.PrintWriter;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    public class DomTest {

        public static void main(String[] args){
            DocumentBuilder documentBuilder;
            try {
                documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document document = documentBuilder.newDocument();
                Element root = document.createElement("root");
                Element text1 = document.createElement("text");
                text1.appendChild(document.createTextNode("hi"));
                root.appendChild(text1);
                Element text2 = document.createElement("text");
                text2.appendChild(document.createTextNode("bye"));
                root.appendChild(text2);
                document.appendChild(root);
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer();
                DOMSource source = new DOMSource(document);
                PrintWriter writer = new PrintWriter(System.out);
                StreamResult result = new StreamResult(writer);
                transformer.transform(source , result);
            } catch (Exception e) {
                e.printStackTrace();
            }
           
        }
    }

    Output of the above code:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?><root><text>hi</text><text>bye</text></root>

    Firstly a org.w3c.dom.Document is created,
                documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document document = documentBuilder.newDocument();

    Then two elements, namely 'text' are created and appended to the root element, 'root'. Then the root element is appended to the document as follows;
                Element root = document.createElement("root");
                Element text1 = document.createElement("text");
                text1.appendChild(document.createTextNode("hi"));
                root.appendChild(text1);
                Element text2 = document.createElement("text");
                text2.appendChild(document.createTextNode("bye"));
                root.appendChild(text2);
                document.appendChild(root);

    Finally the document (created XML is output to the console). DomSource is created with the document. StreamResult is created wrapping a PrintWritter, which outputs to the console, System.out.
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer();
                DOMSource source = new DOMSource(document);
                PrintWriter writer = new PrintWriter(System.out);
                StreamResult result = new StreamResult(writer);
                transformer.transform(source , result);

    Thanks,
    Shyarmal.