3 ธ.ค. 2554

My new blog in wordpress.

http://javadroids.wordpress.com/

19 ต.ค. 2554

TestReadSummary

package ball.summary;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.JOptionPane;

import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;

public class ReadSummary {
 final static String FILENAME = "2.pdf:\5SummaryInformation";

 protected String fileName;

 protected RandomAccessFile seeker;

public static void main(String[] args) throws IOException, NoPropertySetStreamException, MarkUnsupportedException {
// ReadSummary read = new ReadSummary();
// read.RandomRead(FILENAME);
//    System.out.println("Offset is " + read.readOffset());
//    System.out.println("Message is \"" + read.readMessage() + "\".");
BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream("2.pdf:\5SummaryInformation")));

// byte[] getByte = getBytesFromFile(new File("2.pdf:\5SummaryInformation"));
String str = "";
String a = "";
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> resultByte = new ArrayList<String>();
while((a=buf.readLine()) != null){
str+=a;
}
String buffer = str;
String[] splitStringArray = buffer.split("P");

int offset = 0;
for(String s: splitStringArray) {
   offset = buffer.indexOf(s);
   System.out.println(">"+offset);
}
System.out.println(new String(str));
System.exit(0);
char[] ch = null;
if(!str.trim().equals("")){
ch = str.toCharArray();
StringBuffer bufByte = new StringBuffer();
String com = "0/0/30/0/0/0/";
String zero = "0/0/0/0/0/0/0/0/0/";
for (int i = 0; i < ch.length; i++) {
int numb = (byte)ch[i];
//System.out.println(numb+" = "+ch[i]);
bufByte.append(numb+"/");
String strbuf = bufByte.toString();
// if(ch[i]=='A')
// ch[i]='X';
resultByte.add(String.valueOf(ch[i]));
if(strbuf.indexOf(com)>=0){
//System.out.println("BUFFFF "+strbuf);
String allstrbuf = strbuf.substring(4,strbuf.indexOf(com)-1);
String[] splitstrbuf = allstrbuf.split("/");
byte[] byteArray = new byte[splitstrbuf.length];
for (int j = 0; j < splitstrbuf.length; j++) {
if(!splitstrbuf[j].equals(""))
byteArray[j] = (byte) Integer.parseInt(splitstrbuf[j]);
}
String byteresult = new String(byteArray).trim();
if(!byteresult.equals(""))
result.add(byteresult);
bufByte = new StringBuffer();
}
if(strbuf.indexOf(zero)>=0){
//System.out.println(strbuf);
String allstrbuf = strbuf.substring(0,strbuf.indexOf(zero));
//System.out.println(allstrbuf);
String[] splitstrbuf = allstrbuf.split("/");
byte[] byteArray = new byte[splitstrbuf.length];
for (int j = 0; j < splitstrbuf.length; j++) {
if(!splitstrbuf[j].equals(""))
byteArray[j] = (byte) Integer.parseInt(splitstrbuf[j]);
}
String byteresult = new String(byteArray).trim();
if(!byteresult.equals(""))
result.add(byteresult);
bufByte = new StringBuffer();
}
}
}
for (String arr : result) {
// System.out.println("Result "+arr);
}
String allResult = "";
for (String arr : resultByte) {
allResult+=arr;
}
OutputStreamWriter bw = new OutputStreamWriter(new FileOutputStream("ByteResult.txt", true));
bw.write(str);
bw.close();
System.out.println("Done");
}

 /** Constructor: save filename, construct RandomAccessFile */
 public void RandomRead(String fname) throws IOException {
   fileName = fname;
   seeker = new RandomAccessFile(fname, "r");
 }

 /** Read the Offset field, defined to be at location 0 in the file. */
 public int readOffset() throws IOException {
   seeker.seek(0); // move to very beginning
   return seeker.readInt(); // and read the offset
 }

 /** Read the message at the given offset */
 public String readMessage() throws IOException {
   seeker.seek(readOffset()); // move to the offset
   return seeker.readLine(); // and read the String
 }
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);

// Get the size of the file
long length = file.length();

// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}

// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}

// Close the input stream and return bytes
is.close();
return bytes;
}

private static void copyfile(String srFile, String dtFile) {
try {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

// For Append the file.
// OutputStream out = new FileOutputStream(f2,true);

// For Overwrite the file.
OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out
.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}

29 ก.ย. 2554

Java create xml and read

Java create xml and read

package ball.Xml;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class CreateXml {
 private String output;
 public static void main(String[] args ) throws TransformerConfigurationException, IOException{
  new CreateXml();
 }
 public CreateXml() throws TransformerConfigurationException, IOException{
  System.out.println("Create Element");
  output = "output.xml";
  CreateElement();
  ReadXml();
 }
 private void CreateElement() {
  try {
            /////////////////////////////
            //Creating an empty XML Document
            //We need a Document
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            ////////////////////////
            //Creating the XML tree

            //create the root element and add it to the document
            Element root = doc.createElement("root");
            doc.appendChild(root);

            //create a comment and put it in the root element
            Comment comment = doc.createComment("Just a thought");
            root.appendChild(comment);

            //create child element, add an attribute, and add to root
            Element child = doc.createElement("child");
            root = addAttribute(root,child,"a","b");
            root = addAttribute(root,child,"x","a");
            root = addAttribute(root,child,"x","a");

            //add a text element to the child
            Text text = doc.createTextNode("Filler, ... I could have had a foo!");
            child.appendChild(text);
            Element info = doc.createElement("Information");
            root.appendChild(info);
            root = addAttribute(root, info, "Name", "Wongsakorn");
            info.appendChild(doc.createTextNode("Hello"));
            root = addAttribute(root, info, "SureName", "Kongosod");
            /////////////////
            //Output the XML

            //set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult result = new StreamResult(new File(output));
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);

        } catch (Exception e) {
            System.out.println(e);
        }
 }
 private void ReadXml() throws TransformerConfigurationException, IOException {
        //print xml
        System.out.println("Here's the xml:\n");
        InputStream ins = new FileInputStream(new File(output));
        DataInputStream data = new DataInputStream(ins);
        BufferedReader reader = new BufferedReader(new InputStreamReader(data));
        String strLine = "";
        while ((strLine = reader.readLine())!=null) {
   System.out.println(strLine);
  }
 }
 private Element addAttribute(Element root, Element child, String name,String value) {
  child.setAttribute(name, value);
        root.appendChild(child);
  return root;
 }
}

output:

<root>
<!--Just a thought-->
<child a="b" x="a">Filler, ... I could have had a foo!</child>
<Information Name="Wongsakorn" SureName="Kongosod">Hello</Information>
</root>

28 ก.ย. 2554

Anagram

 อนาแกรม (Anagram) คือ การนำตัวอักษรในคำมาสลับหรือจัดเรียงเพื่อให้ได้คำใหม่ โดยความยาวของข้อความและจำนวนตัวอักษรที่ใช้ต้องเท่ากัน อาจจะมีความหมายหรือไม่ก็ได้ครับ ตัวอย่างเช่น


คำว่า Thailand จะได้หลายคำ
Natal Hid
Hand Tali
Hand Alit
Hand Tail
Laid Than
Dial Than
A Had Lint
A Hand Lit
A Lad Thin
A Lad Hint
A Land Hit
A And Hilt
A Halt Din
A Lath Din
A Than Lid
Ad Ha Lint
Ad Ah Lint



ลองดูได้ที่
http://wordsmith.org/anagram/index.html

อันนี้เป็นชื่อผมเอง กลายเป็น Ska Grown On 555+

27 ก.ย. 2554

ReadXml

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLReader {
private String out = "";
private HashMap<Node, String> checkEle;
private HashMap<String, Node> mapRoot;
public static void main(String argv[]) throws ParserConfigurationException,
SAXException, IOException {
new XMLReader();
}

public XMLReader() throws ParserConfigurationException, SAXException,
IOException {
DocumentBuilderFactory docBuild = DocumentBuilderFactory.newInstance();
docBuild.setNamespaceAware(false);
docBuild.setIgnoringComments(true);
docBuild.setIgnoringElementContentWhitespace(true);
DocumentBuilder build = docBuild.newDocumentBuilder();
Document doc = build.parse(new File("input.xml"));
Element root = doc.getDocumentElement();
parser(root);
}

public void parser(Element element) {
System.out.println(element.getNodeName());
NodeList list1 = element.getChildNodes();
checkEle = new HashMap<Node, String>();
mapRoot = new HashMap<String, Node>();
parserChildNode(list1,0);
System.out.println(out);
}
public void parserChildNode(NodeList list,int indexChild) {
String tab = "|  |";
for (int i = 0; i < indexChild; i++) {
tab+="|  |";
}
if (list != null) {
for (int i = 0; i < list.getLength(); i++) {
if (!list.item(i).getNodeName().equals("#text")) {
if(mapRoot.get(list.item(i))!=null){
tab = checkEle.get(mapRoot.get(list.item(i).getNodeName()));
}
NamedNodeMap attribute = list.item(i).getAttributes();
if(attribute!=null && attribute.getLength()>0){
String text = "";
if(list.item(i).hasChildNodes())
text = list.item(i).getFirstChild().getTextContent();
if(checkEle.get(list.item(i)) != null)
out += checkEle.get(list.item(i))+"<"+list.item(i).getNodeName()+"> "+text;
else{
out += tab+"<"+list.item(i).getNodeName()+">";
checkEle.put(list.item(i), tab);
}
}
else{
String text = "";
if(list.item(i).hasChildNodes())
text = list.item(i).getFirstChild().getTextContent();
out += tab+"<"+list.item(i).getNodeName()+"> "+text+"\n";
}
if(attribute!=null && attribute.getLength()>0){
for (int j = 0; j < attribute.getLength(); j++) {
out +=attribute.item(j).getNodeName()+"="+attribute.item(j).getNodeValue();
}
out+="\n";
}
if(list.item(i).getChildNodes()!=null){
if(mapRoot.get(list.item(i).getParentNode())== null){
mapRoot.put(list.item(i).getParentNode().getNodeName(),list.item(1));
parserChildNode(list.item(i).getChildNodes(),indexChild++);
}
}
}

}
}
}
}

Java Reflection get and set Value

package ball.Invoke;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Locale;

import javax.swing.JOptionPane;

import static java.lang.System.out;
import static java.lang.System.err;

public class InvokeSample {
 private String name;
 private String surename;
 private String age;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSurename() {
  return surename;
 }

 public void setSurename(String surename) {
  this.surename = surename;
 }

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

 @Override
 public String toString() {
  return getName() + " " + getSurename() + " " + getAge();
 }

 public static void main(String[] args) throws SecurityException,
   NoSuchFieldException, IllegalArgumentException,
   IllegalAccessException, InvocationTargetException {
  InvokeSample deet = new InvokeSample();
  deet.setAge("20");
  deet.setName("Boner");
  deet.setSurename("Terry");
  deet.parsetObject(deet);
 }
 private void parsetObject(InvokeSample deet)
   throws IllegalArgumentException, IllegalAccessException,
   InvocationTargetException {
  String[] val = { "Data1", "Data2", "Data3" };
  // get Class
  Class<?> c = deet.getClass();
  // get all methods
  Method[] allMethods = c.getDeclaredMethods();

  // get all Fields
  Field[] allF = c.getDeclaredFields();
  for (Field field : allF) {
   System.out.println(field.getName());
  }
  // set value to set method send String
  int i = 0;
  for (Method m : allMethods) {
   String mname = m.getName();
   if (mname.startsWith("set")
     && (m.getGenericReturnType() != boolean.class)) {
    m.setAccessible(true);
    // set value by set method
    m.invoke(deet, new String(val[i++]));
    System.out.println(("invoking " + mname + "()" + m
      .getReturnType()));
   }
  }
  // get value from get method retruned String
  for (Method m : allMethods) {
   String mname = m.getName();
   if (mname.startsWith("get")
     && (m.getGenericReturnType() != boolean.class)
     || mname.startsWith("toString")) {
    Class<?> ret = m.getReturnType();
    if (ret.getSimpleName().trim().equalsIgnoreCase("String")) {
     System.out
       .println(("invoking " + mname + "() return type " + m
         .getReturnType()));
     m.setAccessible(true);
     // get value from get method
     String value = (String) invokeMethod(deet, m);
     out.format("%s() returned %s %n", mname, value);
    }
   }
  }
 }

 private Object invokeMethod(Object obj, Method m) {
  // Invoke Method
  Object value = null;
  try {
   value = m.invoke(obj);
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  }
  return value;
 }
}

26 ก.ย. 2554

Java Abstract

A.java

public abstract class A extends C{
 abstract void me();
 abstract String helloAbs();
 String str;
}

B.java

public class B extends A{
 @Override
 void me() {
  str = "Hello World ";
  System.out.println(getName());
  System.out.println(getSurename());
  System.out.println(getAge());
 }
 @Override
 String helloAbs() {
  return str+toString();
 }
}

C.java

public class C {
 private String name;
 private String surename;
 private int age;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSurename() {
  return surename;
 }
 public void setSurename(String surename) {
  this.surename = surename;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 @Override
 public String toString(){
  return getName()+" "+getSurename()+" "+getAge();
 }
}


UseAbs.java

public class UseAbs {
 public static void main(String[] args) {
  B b = new B();
  b.setName("Terry");
  b.setSurename("Harn");
  b.setAge(22);
  b.me();
  System.out.println(b.helloAbs());
 }
}
Result:
Terry
Harn
22
Hello World Terry Harn 22
 

Java Interface

Interface A.java

public interface A {
 void iamA(); 
 void helloA();
}

B.java

public class B implements A{
 @Override
 public void iamA() {
  System.out.println("I am A use by B");
 }
 @Override
 public void helloA() {
  System.out.println("Hello World A");
 }
}

Use.java

public class Use {
 public static void main(String[] args) {
  B b = new B();
  b.iamA();
  b.helloA();
 }
}

Result:  I am A use by B
         Hello World A

23 ก.ย. 2554

Interface and Abstract


Interface กับ Abstract Class 



Abstract Class คือ Class เป็นเสมือนคลาสนึงที่วางโครงร่างไว้ให้แล้วแค่มา extends ไปใช้


Interface แก้ปัญหาการสืบทอด เพราะเวลา extends Class จะได้ Class เดียวแต่เราสามารถ Implements ได้หลาย Interface

จะยกตัวอย่างในตอนถัดไป

Change Properties Summary of file with java

http://www.4shared.com/file/aAwQ8bst/Summary.html

Program  Properties Summary of file with java

Program and Game Android

Program and Game Android

1. Xexplorer
http://www.4shared.com/file/pL24AU1A/Xexplorer.html

2.GuessNumber
http://www.4shared.com/file/uqQD_g0J/GuessNumber.html

3.FindNumber
http://www.4shared.com/file/QsoW1Wyb/FindNumber.html?

4.TerryNews
http://www.4shared.com/file/GTqR9Lxt/TerryNews.html?

5.Pao Ying Choop by Puchong
http://slideme.org/applications?text=pao%20ying%20choop

ฝากโปรแกรมไปลองใช้หน่อยนะครับยังไม่เสร็จดี

MongoDB Install

mongo DB Install

            1.      Go to download page http://www.mongodb.org/downloads
            download OS  and Source in use 


For java use library jar file download  https://github.com/mongodb/mongo-java-driver/downloads
2. When get all file

Extract OS and Source file
Create floder to store C: my_mongo_dir

Create a data directory
By default MongoDB will store data in \data\db, but it won't automatically create that folder, so we do so here:
C:\> mkdir \data
C:\> mkdir \data\db


       3. Run
Run and connect to the server
The important binaries for a first run are:
·         mongod.exe - the database server. Try mongod --help to see startup options.
·         mongo.exe - the administrative shell
To run the database, click mongod.exe in Explorer, or run it from a CMD window.
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongod
Note: It is also possible to run the server as a Windows Service. But we can do that later.
Now, start the administrative shell, either by double-clicking mongo.exe in Explorer, or from the CMD prompt. By default mongo.exe connects to a mongod server running on localhost and uses the database named test. Run mongo --help to see other options.
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongo
> // the mongo shell is a javascript shell connected to the db
> // by default it connects to database 'test' at localhost
> 3+3
6
> db
test
> // the first write will create the db:
> db.foo.insert( { a : 1 } )
> db.foo.find()
{ _id : ..., a : 1 }
> show dbs
...
> show collections
...
> help



Java Code Example
 
package ball;

/**
* Simple Example that shows creating a people (id:number, name:string,
* gender:string) collection and then adding, finding, updating and deleting.
* You need to download and install MongoDB (www.mongodb.org) and run the
* server. You’ll also need to have the mongo-1.2.jar in your class path.
*/


import java.net.UnknownHostException;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
* @author vsbabu
*/
public class MongoManager {
       public MongoManager(){
              RunCommand();
              Mongo();
       }
       private void Mongo() {
              System.out.println("Start ");
              try {
                     Mongo m = new Mongo("localhost", 27017);
                     DB db = m.getDB("sampledb");
                     DBCollection coll = db.getCollection("people");

                     // clear records if any
                     DBCursor cur = coll.find();
                     while (cur.hasNext())
                           coll.remove(cur.next());

                     // create a unique ascending index on id;
                     //doesn’t seem to work? it works from python and javascript
                     coll.ensureIndex(new BasicDBObject("id", 1).append("unique", true));
                     coll.createIndex(new BasicDBObject("name", 1));
                     coll.insert(makePersonDocument(6655, "James", "male"));
                     coll.insert(makePersonDocument(6797, "Bond", "male"));
                     coll.insert(makePersonDocument(6643, "Cheryl", "female"));
                     coll.insert(makePersonDocument(7200, "Scarlett", "female"));
                     coll.insert(makePersonDocument(6400, "Jacks", "male"));
                     System.out.println("Total Records : " + coll.getCount());

                     cur = coll.find();
                     printResults(cur, "Find All Records");

                     cur = coll.find(new BasicDBObject("id", 6655));
                     printResults(cur, "Find id = 6655");

                     cur = coll.find(new BasicDBObject()
                                  .append("id", new BasicDBObject("$lte", 6700)));
                     printResults(cur, "Find id <= 6700");

                     cur = coll.find(new BasicDBObject()
                                  .append("id", new BasicDBObject("$lte", 6700))
                                  .append("gender", "male"));
                     printResults(cur, "Find id <= 6700 and gender = male");

                     cur = coll.find(new BasicDBObject()
                                  .append("name", Pattern.compile("^ja.*?s$", Pattern.CASE_INSENSITIVE)))
                                  .sort(new BasicDBObject("name", -1));
                     printResults(cur, "Find name like Ja%s and sort reverse by name");
                    
                     cur = coll.find(new BasicDBObject()
                                  .append("gender", "female"))
                                  .sort(new BasicDBObject("id", -1))
                                  .limit(2);
                     printResults(cur, "Get top 2 (by id) ladies");
                    
                     //let us reduce every body’s phone numbers by 10; add Sir to males, Mme to ladies
                     cur  = coll.find();
                     while(cur.hasNext()) {
                           BasicDBObject set = new BasicDBObject("$inc", new BasicDBObject("id", -10));
                           if ("male".equals(cur.next().get("gender")))
                                  set.append("$set", new BasicDBObject("name", "Sir ".concat((String) cur.curr().get("name"))));
                           else
                                  set.append("$set", new BasicDBObject("name", "Mme ".concat((String) cur.curr().get("name"))));
                           coll.update(cur.curr(), set);
                     }
                     cur  = coll.find();
                     printResults(cur, "All, after id and name update");
                    
              }
              catch (UnknownHostException ex) {
                     ex.printStackTrace();
              }
              catch (MongoException ex) {
                     ex.printStackTrace();
              }

       }
       private void RunCommand() {
              System.out.println("Run");
                try {
                                  Process p = Runtime
                                     .getRuntime()
                                     .exec("rundll32 url.dll,FileProtocolHandler C:/mongodb/bin");
                                  p.waitFor();
                                  JOptionPane.showMessageDialog(null, "Open mongod.exe");
                       } catch (Exception ex) {
                           ex.printStackTrace();
                       }
             
       }
       public static void main(String[] args) {
              new MongoManager();
       }

       private static void printResults(DBCursor cur, String message) {
              System.out.println("<<<<<<<<<< " + message + " >>>>>>>>>>>>");
              while (cur.hasNext()) {
                     System.out.println(cur.next().get("id") + "," + cur.curr().get("name") + "," + cur.curr().get("gender"));
              }
       }

       private static BasicDBObject makePersonDocument(int id, String name, String gender) {
              BasicDBObject doc = new BasicDBObject();
              doc.put("id", id);
              doc.put("name", name);
              doc.put("gender", gender);
              return doc;
       }

}

/*
Output will look like below
Total Records : 5
<<<<<<<<<< Find All Records >>>>>>>>>>>>
6655,James,male
6797,Bond,male
6643,Cheryl,female
7200,Scarlett,female
6400,Jacks,male
<<<<<<<<<< Find id = 6655 >>>>>>>>>>>>
6655,James,male
<<<<<<<<<< Find id <= 6700 >>>>>>>>>>>>
6400,Jacks,male
6643,Cheryl,female
6655,James,male
<<<<<<<<<< Find id <= 6700 and gender = male >>>>>>>>>>>>
6400,Jacks,male
6655,James,male
<<<<<<<<<< Find name like Ja%s and sort reverse by name >>>>>>>>>>>>
6655,James,male
6400,Jacks,male
<<<<<<<<<< Get top 2 (by id) ladies >>>>>>>>>>>>
7200,Scarlett,female
6643,Cheryl,female
<<<<<<<<<< All, after id and name update >>>>>>>>>>>>
6645,Sir James,male
6787,Sir Bond,male
6633,Mme Cheryl,female
7190,Mme Scarlett,female
6390,Sir Jacks,male
*/