Monday 16 December 2013

How to read the array data in mongoDB, modify the array data and update the same in mongoDB.



How to read the arrat data in mongoDB, modify the array data and update the same in mongoDB.

public static void mongoArrayExample(){
DBCursor cursor = null;
MongoClient mongoClient = null;
try {

mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("school");
DBCollection students = db.getCollection("students");

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id" , 0);

cursor = students.find(whereQuery);
Map<String, Double> map = new HashMap<String, Double>();
while (cursor.hasNext()){
BasicDBObject result = (BasicDBObject) cursor.next();
BasicDBList  scores = (BasicDBList) result.get("scores");
// Reading the data from Array.
        for(int j = 0; j< scores.size(); j++)
        {
        // Reading the individual records
            String type = (String) ((BSONObject) scores.get(j)).get("type");
            Double score = (Double) ((BSONObject) scores.get(j)).get("score");
            if(map.containsKey("homework")){
            map.put(type, score);
            }
        }
}

List<BasicDBObject> scores = new ArrayList<BasicDBObject>();
  Set<String> str = map.keySet();
  for (String string : str) {
  BasicDBObject obje = new BasicDBObject();
  obje.put("type", string);
  obje.put("score", map.get(string));
  scores.add(obje);
}

  // Modifying the array
  BasicDBObject updateQuery = new BasicDBObject();
  updateQuery.append("$set", new BasicDBObject().append("scores", scores));
  students.update(whereQuery, updateQuery);

}catch (Exception e) {
}
}

Friday 29 November 2013

connect remote mongoDB through JAVA


When you try to connect mongoDB locally through java, its easy as below

MongoClient mongoClient = null ;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");


but when you try to connect remote mongoDB, It wont connect for the below code.

MongoClient mongoClient = null ;
try {
mongoClient = new MongoClient( "10.55.36.74" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");

To make th above code work, you need to do some changes in mongod.conf file.
Go to the location /usr/local/etc/mongod.conf .
You will find below option of bind_ip.
bind_ip is 127.0.0.1, which forces the server to only listen for requests on the localhost IP.

# Only accept local connections
bind_ip = 127.0.0.1

Chnage the same option to
bind_ip = 0.0.0.0

Once you change the same remote connection through JAVA as mentioned in above code will work.

Thursday 28 November 2013

Example of Data retrivel from MondoDB using JAVA.


Data retrivel from MondoDB using JAVA.

public static void getData(){
DBCursor cursor = null;
MongoClient mongoClient= null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");


// Get all documents of a collections.
cursor = documents.find();
while(cursor.hasNext()) {
System.out.println(" Get all documents of a collections. \n");
   System.out.println(cursor.next());
}

// Get documents of a collections where age = 25.
//      key is case sensitive so it wont retrieve any documents.
// Key has to "Age" and not "age"
BasicDBObject caseSenQuery = new BasicDBObject();
caseSenQuery.put("age", 25);
cursor = documents.find(caseSenQuery);
System.out.println("\n Get documents of a collections where age = 25 as  key is case sensitive so it wont retrieve any documents. \n");
while(cursor.hasNext()) {
System.out.println(cursor.next());
}

// Get documents of a collections where age = 25.
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("Age", 25);
cursor = documents.find(whereQuery);
while(cursor.hasNext()) {
System.out.println("\n Get documents of a collections where age = 25. \n");
   System.out.println(cursor.next());
}


//   Get documents of a collection by adding mutliple clauses like name and age.
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("Age", 25));
obj.add(new BasicDBObject("Name" , "abcdefxyz"));
andQuery.put("$and", obj);

cursor = documents.find(andQuery);
while (cursor.hasNext()) {
System.out.println("\n Get documents of a collection by adding mutliple clauses like name and age. \n");
System.out.println(cursor.next());
}


//       Get documents where name like pattern for "name"
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("Name", new BasicDBObject("$regex", "abcd") .append("$options", "i"));
cursor = documents.find(regexQuery);
while (cursor.hasNext()) {
System.out.println("\n Get documents where name like pattern for name. \n");
System.out.println(cursor.next());
}


//      Get documents where name like pattern for "BooksRead.name"
BasicDBObject regexQuery1 = new BasicDBObject();
regexQuery.put("BooksRead.name", new BasicDBObject("$regex", "Krishna") .append("$options", "i"));
cursor = documents.find(regexQuery1);
while (cursor.hasNext()) {
System.out.println("\n Get documents where name like pattern for BooksRead.name. \n");
System.out.println(cursor.next());
}

//     Get documents by quering the embedded/sub document address.area = Aundh.
BasicDBObject embeddedQuery = new BasicDBObject();
embeddedQuery.put("address.area", "Aundh");
cursor = documents.find(embeddedQuery);
while(cursor.hasNext()) {
System.out.println("\n Get documents by quering the embedded/sub docuement address.area = Aundh. \n");
   System.out.println(cursor.next());
}


//   Get documents by quering the embedded/sub document BooksRead.publishedBy = Mehata Publishing Ltd.
BasicDBObject embeddedQuery1 = new BasicDBObject();
embeddedQuery1.put("BooksRead.publishedBy", "Mehata Publishing Ltd");
cursor = documents.find(embeddedQuery1);
while(cursor.hasNext()) {
System.out.println("\n Get documents by quering the embedded/sub docuement BooksRead.publishedBy = Mehata Publishing Ltd. \n");
   System.out.println(cursor.next());
}


// Find documents by date of birth
Date gtDate = null;
try {
gtDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("1984-05-010T8:30:00.000Z");
} catch (ParseException e) {
e.printStackTrace();
}
BasicDBObject dateQueryObj = new BasicDBObject("DateOfBirth",  new BasicDBObject("$lt", gtDate));
cursor = documents.find(dateQueryObj);
while(cursor.hasNext()) {
System.out.println("\n Find documents by date of birth. \n");
   System.out.println(cursor.next());
}


//    Get selective fields from matched document.
BasicDBObject selectiveFields = new BasicDBObject();
selectiveFields.put("Age", 25);
BasicDBObject fields = new BasicDBObject();
fields.put("Name", 1);
fields.put("Age", 2);
fields.put("DateOfBirth", 3);
fields.put("address.area", 3);

cursor = documents.find(selectiveFields, fields);
while (cursor.hasNext()) {
System.out.println("\n Get selective fields from matched document. \n");
System.out.println(cursor.next());
}


//    Get selective fields along with embedded fields from matched document.
BasicDBObject clauseField = new BasicDBObject();
selectiveFields.put("Age", 25);
BasicDBObject embeddedfields = new BasicDBObject();
embeddedfields.put("Name", 1);
embeddedfields.put("Age", 2);
embeddedfields.put("DateOfBirth", 3);
embeddedfields.put("address.area", 4);
embeddedfields.put("BooksRead.name", 5);

cursor = documents.find(clauseField, embeddedfields);
while (cursor.hasNext()) {
System.out.println("\n Get selective fields along with embedded fields from matched document. \n");
System.out.println(cursor.next());
}
}



the output on the console is ::

 Get all documents of a collections.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Get documents of a collections where age = 25 as  key is case sensitive so it wont retrieve any documents.


 Get documents of a collections where age = 25.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Get documents of a collection by adding mutliple clauses like name and age.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Get documents where name like pattern for name.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Get documents where name like pattern for BooksRead.name.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Get documents by quering the embedded/sub docuement address.area = Aundh.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Get documents by quering the embedded/sub docuement BooksRead.publishedBy = Mehata Publishing Ltd.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Find documents by date of birth.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Id" : 12345 , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "Interests" : [ "Reading" , "Politics" , "Basketball"] , "address" : { "addressDetail" : "flat no 333, Q Wing, Sita Nagar" , "area" : "Aundh" , "city" : "Pune" , "pincode" : 411017 , "state" : "MAHARASHTRA" , "country" : "INDIA"} , "BooksRead" : [ { "name" : "The Immortals of Meluha" , "authorName" : "Amish Tripathi" , "publishedBy" : "Westland Press"} , { "name" : "The Krishna Key" , "authorName" : "Ashwin Sanghi" , "publishedBy" : "Westland Ltd"} , { "name" : "Sita: An Illustrated Retelling of Ramayana" , "authorName" : "Devdutt Pattanaik" , "publishedBy" : "Mehata Publishing Ltd"}]}

 Get selective fields from matched document.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "address" : { "area" : "Aundh"}}

 Get selective fields along with embedded fields from matched document.

{ "_id" : { "$oid" : "5296e987910919e6768c9391"} , "Name" : "abcdefxyz" , "Age" : 25 , "DateOfBirth" : { "$date" : "1984-05-08T03:00:00.000Z"} , "address" : { "area" : "Aundh"} , "BooksRead" : [ { "name" : "The Immortals of Meluha"} , { "name" : "The Krishna Key"} , { "name" : "Sita: An Illustrated Retelling of Ramayana"}]}


Wednesday 27 November 2013

Embedded/sub document example of MongoDB with JAVA.


Creating a complex JSON for in MongoDB.
Embedded/sub document example of MongoDB with JAVA.
Lets aim to add a JSON as shown below in mongoDB.
{
"Id" : 12345,
"Name" : "opqrst",
"Age" : 25,
"DateOfBirth" :  ("1984-05-08"),
"Interests" : [ "Reading", "Politics", "Basketball" ],

"Address" : {
"addressDetail" : "flat no 103, A Wing, Ram Nagar",
"area" : "Rahatani",
"city" : "Pune",
"pincode" : 411027,
"state" : "MAHARASHTRA",
"country" : "INDIA"
}
}


public static void create(){
MongoClient mongoClient = null ;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");
BasicDBObject document = new BasicDBObject();
document.put("Id", 12345);
document.put("Name", "opqrst");
document.put("Age", 25);
try {
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("1984-05-08T8:30:00.000Z");
document.put("DateOfBirth", date);
} catch (ParseException e) {
e.printStackTrace();
}

String [] interests = {"Reading", "Politics", "Basketball"};
document.put("Interests", interests);

BasicDBObject address = new BasicDBObject();
address.put("addressDetail", "flat no 103, A Wing, Ram Nagar" );
address.put("area", "Rahatani");
address.put("city", "Pune");
address.put("pincode", 411027);
address.put("state", "MAHARASHTRA");
address.put("country", "INDIA");

document.put("Address", address);

documents.insert(document);

}

The output on the mongo shell is like :

> db.Documents.find().pretty();
{
"_id" : ObjectId("5296e4fe91093f95cc8b84e7"),
"Id" : 12345,
"Name" : "opqrst",
"Age" : 25,
"DateOfBirth" : ISODate("1984-05-08T03:00:00Z"),
"Interests" : [ "Reading", "Politics", "Basketball" ],
"Address" : {
"addressDetail" : "flat no 103, A Wing, Ram Nagar",
"area" : "Rahatani",
"city" : "Pune",
"pincode" : 411027,
"state" : "MAHARASHTRA",
"country" : "INDIA"
}
}


Creating more complex Structure using MongoDB and JAVA

Example of creating array of embedded/sub document.
The JSON structure is :

{
"Id" : 12345,
"Name" : "abcdefxyz",
"Age" : 25,
"DateOfBirth" : ("1984-05-08"),
"Interests" : [ "Reading", "Politics", "Basketball"],

"address" : {
"addressDetail" : "flat no 333, Q Wing, Sita Nagar",
"area" : "Aundh",
"city" : "Pune",
"pincode" : 411017,
"state" : "MAHARASHTRA",
"country" : "INDIA"
},

"BooksRead" : [
{
"name" : "The Immortals of Meluha",
"authorName" : "Amish Tripathi",
"publishedBy" : "Westland Press"
},
{
"name" : "The Krishna Key",
"authorName" : "Ashwin Sanghi",
"publishedBy" : "Westland Ltd"
},
{
"name" : "Sita: An Illustrated Retelling of Ramayana",
"authorName" : "Devdutt Pattanaik",
"publishedBy" : "Mehata Publishing Ltd"
}
]
}


public static void create(){
MongoClient mongoClient = null ;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");
BasicDBObject document = new BasicDBObject();
document.put("Id", 12345);
document.put("Name", "abcdefxyz");
document.put("Age", 25);
document.put("DateOfBirth", new Date());

try {
  Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("1984-05-                             08T8:30:00.000Z");
  document.put("DateOfBirth", date);
} catch (ParseException e) {
  e.printStackTrace();
}

   String [] interests = {"Reading", "Politics", "Basketball"};
   document.put("Interests", interests);

BasicDBObject address = new BasicDBObject();
address.put("addressDetail", "flat no 333, Q Wing, Sita Nagar" );
address.put("area", "Aundh");
address.put("city", "Pune");
address.put("pincode", 411017);
address.put("state", "MAHARASHTRA");
address.put("country", "INDIA");

document.put("address", address);

List<BasicDBObject> booksRead = new ArrayList<BasicDBObject>();
BasicDBObject book1 = new BasicDBObject();
book1.put("name", "The Immortals of Meluha");
book1.put("authorName", "Amish Tripathi");
book1.put("publishedBy", "Westland Press");
booksRead.add(book1);

BasicDBObject book2 = new BasicDBObject();
book2.put("name", "The Krishna Key");
book2.put("authorName", "Ashwin Sanghi");
book2.put("publishedBy", "Westland Ltd");
booksRead.add(book2);

BasicDBObject book3 = new BasicDBObject();
book3.put("name", "Sita: An Illustrated Retelling of Ramayana");
book3.put("authorName", "Devdutt Pattanaik");
book3.put("publishedBy", "Mehata Publishing Ltd");
booksRead.add(book3);

document.put("BooksRead", booksRead);
documents.insert(document);

}

The output on the mongo shell is like :

> db.Documents.find().pretty();

{
"_id" : ObjectId("5296e987910919e6768c9391"),
"Id" : 12345,
"Name" : "abcdefxyz",
"Age" : 25,
"DateOfBirth" : ISODate("1984-05-08T03:00:00Z"),
"Interests" : [ "Reading", "Politics","Basketball"],
"address" : {
"addressDetail" : "flat no 333, Q Wing, Sita Nagar",
"area" : "Aundh",
"city" : "Pune",
"pincode" : 411017,
"state" : "MAHARASHTRA",
"country" : "INDIA"
},
"BooksRead" : [
{
"name" : "The Immortals of Meluha",
"authorName" : "Amish Tripathi",
"publishedBy" : "Westland Press"
},
{
"name" : "The Krishna Key",
"authorName" : "Ashwin Sanghi",
"publishedBy" : "Westland Ltd"
},
{
"name" : "Sita: An Illustrated Retelling of Ramayana",
"authorName" : "Devdutt Pattanaik",
"publishedBy" : "Mehata Publishing Ltd"
}
]
}

Use of Java for Inserting data to MongoDB


Example for MongoDB  : Use of Java for Inserting data to MongoDB.

MongoClient mongoClient = null ;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");
BasicDBObject document = new BasicDBObject();
document.put("Id", 12345);
document.put("Name", "abcdhijk");
document.put("Age", 25);
try {
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("1984-05-08T8:30:00.000Z");
document.put("DateOfBirth", date);
} catch (ParseException e) {
e.printStackTrace();
}

String [] interests = {"Reading", "Politics", "Basketball"};
document.put("Interests", interests);

documents.insert(document);



The output on the mongo shell is like :
connect MongoDB using "mongo" command
> show dbs

local 0.078125GB
mongoDB 0.203125GB

> use mongoDB
switched to db mongoDB

> show collections
Documents
system.indexes

> db.Documents.find();
{ "_id" : ObjectId("5296db7e91098e64f3c4faa8"), "Id" : 12345, "Name" : "abcdhijk", "Age" : 25, "DateOfBirth" : ISODate("1984-05-08T03:00:00Z"), "Interests" : [ "Reading", "Politics", "Basketball" ] }

> db.Documents.find().pretty();
{
"_id" : ObjectId("5296db7e91098e64f3c4faa8"),
"Id" : 12345,
"Name" : "abcdhijk",
"Age" : 25,
"DateOfBirth" : ISODate("1984-05-08T03:00:00Z"),
"Interests" : [
"Reading",
"Politics",
"Basketball"
]
}



Friday 8 November 2013

Solr 4.5.1 set up issues with Tomcat

I tried installing Solr 4.5.1

I faced couple of issues while setting up the environment.

The first issue is I was not able access the as it was throwing an error
SEVERE: Error filterStart....

when I checked for more information I got this ....
SEVERE: Exception starting filter SolrRequestFilter

This is occurring because org.apache.solr.common.SolrException: Could not find necessary SLF4j logging jars. Need to add the jars on the containers.


Add the jars in the tomcat
1. slf4j-log4j12-1.6.6.jar
2. slf4j-api-1.6.6.jar
3. log4j-1.2.16.jar
4. jcl-over-slf4j-1.6.6.jar

The above issue got resolved after adding the jars.

The second issue is "msg=SolrCore 'collection1' is not available due to init failure: Unable to use updateLog: _version_field must exist in schema".

To resolve the above issue ...need to Add below in the <fields> tag in schema.xml

<field name="_version_" type="long" indexed="true" stored="true"/>


Saturday 31 August 2013

Split a large array into smaller arrays...


Split a large array into smaller arrays...

import java.util.Arrays;


public class Test {
public static void main(String[] args) {
int[] original = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int sizeOfNewArray = 5;
int quotient = original.length / sizeOfNewArray;
boolean isRemainder = original.length % sizeOfNewArray == 0;
if(!isRemainder){
quotient ++;
}
int startPoint = 0;
for (int i = 0 ; i < quotient ; i ++ ) {
int arrayLength = ((startPoint + sizeOfNewArray) > original.length) ? original.length : (startPoint + sizeOfNewArray) ;
int[] smallerArray = Arrays.copyOfRange(original, startPoint, arrayLength);
for (int j : smallerArray) {
System.out.println("Array " + i + " ::" + j);
}
startPoint = startPoint + sizeOfNewArray ;
}
}
}

*Here in the example "original" array size is smaller. 

Wednesday 24 April 2013

Panel which dynamically opens and closes in Wicket




Panel which dynamically opens and closes in Wicket

import java.text.MessageFormat;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.value.IValueMap;

public class CustomPanel extends Panel {
  private static final String SHOW_ALL_SCRIPT = "jQuery('a.panel-open').click()";

  private static final String HIDE_ALL_SCRIPT = "jQuery('a.panel-close').click()";

  public CustomPanel(final String id, final Component component) {
    this(id, component, new Model<Boolean>(true));
  }

  public CustomPanel(final String id, final Component component, final IModel<Boolean> open) {
    super(id, open);
    component.setOutputMarkupId(true);

    final WebMarkupContainer link = new WebMarkupContainer("link") {
      private static final String SCRIPT = "var panel = jQuery(''#{0}'');"
          + "var link = jQuery(this); var span = link.children();"
          + "link.toggleClass(''panel-close'').toggleClass(''panel-open'');"
          + "if (panel.css(''display'') == ''none'') "
          + "'{' panel.show(); span.text(''{1}''); link.attr(''title'', ''{3}''); '}'" + "else "
          + "'{' panel.hide(); span.text(''{2}''); link.attr(''title'', ''{4}''); '}'" + "return false;";

      @Override
      protected void onComponentTag(final ComponentTag tag) {
        super.onComponentTag(tag);
        if (!tag.isClose()) {
          final IValueMap attributes = tag.getAttributes();

          final Boolean isPanelOpen = getModel().getObject();
          if (isPanelOpen != null && isPanelOpen) {
            attributes.put("class", "panel-close");
            attributes.put("title", getCloseText());
          } else {
            attributes.put("class", "panel-open");
            attributes.put("title", getOpenText());
          }
          attributes.put("onclick", MessageFormat.format(SCRIPT, component.getMarkupId(), getCloseText(),
              getOpenText(), getClosePanelText(), getOpenPanelText()));
        }
      }

    };
    add(link);
    link.add(new Label("text", new AbstractReadOnlyModel<String>() {
      private static final long serialVersionUID = 1045024635866272771L;

      @Override
      public String getObject() {
        final Boolean isPanelOpen = getModel().getObject();
        if (isPanelOpen != null && isPanelOpen) {
          return getCloseText();
        } else {
          return getOpenText();
        }
      }
    }));
  }

  @Override
  protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
    renderComponentTagBody(markupStream, openTag);
    super.onComponentTagBody(markupStream, openTag);
    // Render the body of the link

  }

  @SuppressWarnings("unchecked")
  protected IModel<Boolean> getModel() {
    return (IModel<Boolean>) getDefaultModel();
  }

  private String getCloseText() {
    return getString("close");
  }

  private String getOpenText() {
    return getString("open");
  }

  private String getClosePanelText() {
    return getString("closePanel");
  }

  private String getOpenPanelText() {
    return getString("openPanel");
  }

  public static AttributeAppender getShowAllBehavior() {
    return new AttributeAppender("onclick", true, new Model<String>(SHOW_ALL_SCRIPT), " ");
  }

  public static AttributeAppender getHideAllBehavior() {
    return new AttributeAppender("onclick", true, new Model<String>(HIDE_ALL_SCRIPT), " ");
  }

}


CustomPanel.html

<wicket:panel xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd">
<a wicket:id="link" href="#">
<span wicket:id="text"></span>
</a>

</wicket:panel>