Wednesday, June 6, 2012

All About MangoDB


NoSql DB is one of the latest trends in the market which most of the big names in the industry are investing in and are getting benefited by its huge spectrum of features. The common feature associated with NoSQL are Storing huge Data & Scaling up Storage, Interconnected Data, Complex Data Structure, High performance and Flexibility with schema less approach.

Major Internet giants like Facebook, Twitter, Digg, Amazon, LinkedIn, craigslist, Foursquare and Google all use NoSQL in one way or another because of the significantly different challenges in dealing with huge quantities of data that the traditional RDBMS solutions could not cope with.


MongoDB (from "humongous") is a scalable, high-performance, open source, document based NoSQL database used by company like craigslist, Foursquare, Disney, MTV and many more.





Tuesday, June 5, 2012

MongoDB Tutorial : Getting Started

MongoDB is no SQL,open source database, written purely in C++, basically store the database in the document form.
based on the JSON approach,can be horizontally scalable,can be index on any attribute

Here are the best practise to use











How to download and Install MongoDB
Download the MongoDB from the MongoDB website as depicted in the picture as per your
plateform,here I am downloading it for the Windows 32 bits.











Download the relevent Driver to work for
The fallowing page shows the link for the driver,Here I am working with the Java Driver.








Review the downloaded bineries
After downloading MongoDB,extract the zip file which contains the fallowing exe files as shown in the image.








Installing the MongoDB server
Intalling the MongoDB server is not a time taking process,just open the command prompt and go the location of bin of the unzipped folder,in the meanwhile create the
database folder as MongoDB does not create the database itself.

execute the fallowing command mongod --dbpath "f://mongodatabase"
and press enter the fallowing screen show the out that your server is up and running on the default port 27017











Test your DB Installation
Open the web browser and type the fallowing addres http://loacalhost:27017/
The webpage displays the welcome page of mongoDB same as the image shown.









Connect to MongoDB
Open the command prompt, open the bin location






run the MongoDB as a Windows Service
open the command prompt and execute the fallowing command
mongod --dbpath "f:\mongodatabase" --logpath "f:\mongodatabase\logs.txt" --install --serviceName "MongoDB"
here shown the output on the console





The Next step is to verify from the service manager





Uninstall
Use the remove command shown in the image.




Create Database in the MongoDB
MongoDB does not provide any command or syntex to create database as provided with the relationship based
database,it creates the database on the fly when you try to insert the values first time in the database.

on the shell use show dbs command which shows the local(empty) database




use databasename command will create your MongoDB,but the database has not been created yet you can
verify the same by using show dbs command.
The database only created when you try to insert some document into the database
Define a collection name as employee and let try to insert some document inside it




New in Java 7

Working with java.nio.file package overcome the difficulties in copying and moving the files and directories which java really lacks of.
Java 7 provide directory tree traversal trough Files.walkFileTree Method which basically traverse the hierarchical folder structure
Path Objects
Path object represent the sequence of Directory structure to find the file resource
How to construct path object

Paths.get(“/BaseDir”);    // return path string “/BaseDir”

Paths.get(“/BaseDir”,”SubDir”);   // return the path string “/BaseDir/SubDir”

path object can be manipulated using the Path.resolve and Path.relativize,lets have a look
Path base =  Paths.get(“/BaseDir”);    //this is the base path

Path filePath = base.resolve(“SubDir/somefile.txt”);    // the filePath is “/BaseDir/SubDir/somefile.txt” while the base path remains “/BaseDir”
The very useful method of the Path class is Path.getFileName which inturn return the farthest element which is eighter a file or directory,lets have an example
suppose we have created the filePath as “/BaseDir/SubDir/somefile.txt”
filePath.getFileName()    // returns the name of the file as somefile.txt

suppose we have created the dirPath as “/BaseDir/SubDir/SomeDir”

dirPath.getFileName()     // return the directory name as SomeDir

How to copy a file

Path srcPath = …......
Path targetPath = …...............
Path basePath = …......
Files.copy(srcPath,targetPath.resolve(basePath.relativize(srcPath)));

Monday, June 4, 2012

Hibernate: Saving Collections

We have a Employee Class in which we have class field as empId,empName and addresses.
suppose an Employee can have multiple address, in our example we have considered that
Employee have office address as well as home address.
for saving these address we have used Set collection in our example.
Here is the Employee Class
//Employee.java

package com.test;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int empid;
 
 @Column(name="EMPLOYEE_NAME")
 private String empName;
 
 @ElementCollection
 private Set
addresses = new HashSet
(); public Set
getAddresses() { return addresses; } public void setAddresses(Set
addresses) { this.addresses = addresses; } public int getEmpid() { return empid; } public void setEmpid(int empid) { this.empid = empid; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } }
Here we have address class which is marked as @Embeddable
package com.test;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Address {
 
 @Column(name="STREET")
 private String street;
 
 @Column(name="CITY")
 private String city;
 
 @Column(name="PINCODE")
 private String pincode;
 
 @Column(name="STATE")
 private String state;
 
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getPincode() {
  return pincode;
 }
 public void setPincode(String pincode) {
  this.pincode = pincode;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 
}

for persisting these classes we need a hibernate configuration to our database here I used MySQL as database
look at Hibernate.cfg.xml
<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDb</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <mapping class="com.test.Address"/>
        <mapping class="com.test.Employee"/>
        
    </session-factory>

</hibernate-configuration>

now we are ready to test our example here we have our main class
package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {

 
 public static void main(String[] args) {
  Employee emp1 = new Employee();
  emp1.setEmpName("Rajkumar Singh");
  
  Employee emp2 = new Employee();
  emp2.setEmpName("Sharad Singh");
  
  Address homeAddress = new Address();
  homeAddress.setCity("Bareilly");
  homeAddress.setStreet("121");
  homeAddress.setPincode("201301");
  homeAddress.setState("UP");
  
  Address officeAddress = new Address();
  officeAddress.setCity("Noida");
  officeAddress.setStreet("131");
  officeAddress.setPincode("201302");
  officeAddress.setState("UP");
  
  emp1.getAddresses().add(homeAddress);
  emp1.getAddresses().add(officeAddress);
  
  SessionFactory sf = new Configuration().configure().buildSessionFactory();
  Session session = sf.openSession();
  session.beginTransaction();
  session.save(emp1);  // saving emp1 
  session.getTransaction().commit();
  session.close();
  

 }

}

we we ran our main class two table have generated in the database with the name of Employee and Employee_addresses.

look at the console output
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: insert into Employee (EMPLOYEE_NAME) values (?)
Hibernate: insert into Employee_addresses (Employee_empid, CITY, PINCODE, STATE, STREET) values (?, ?, ?, ?, ?)
Hibernate: insert into Employee_addresses (Employee_empid, CITY, PINCODE, STATE, STREET) values (?, ?, ?, ?, ?)

Friday, September 23, 2011

How to share and access propeties file using singleton and java properties

In this example I have given a Idea to share properties file(configuration file) using Singleton class and Java Properties

first we have our properties file say for example data.properties

name = Rajkumar Singh
course = java

now create a singleton class as fallows

DataSingleton.java
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

package example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class DataSingleton {
static  private DataSingleton instance = null;
public String name;
public String course;
static public DataSingleton getDataSingleton(){
if(instance == null){
instance = new DataSingleton();
}
return instance;
}

private DataSingleton(){
try{
BufferedReader br = new BufferedReader(new FileReader(new File("data.txt")));
Properties prop = new Properties();
prop.load(br);
name = prop.getProperty("name");
course = prop.getProperty("course");
}catch(IOException e){
e.printStackTrace();
}
}
}

now we have our tester class like this


TesterClass.java
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

public class TesterClass {
public static void main(String[] args) {
DataSingleton ds = DataSingleton.getDataSingleton();
System.out.println(ds.name);
System.out.println(ds.course);
}
}


output:
:::::::::::::::::::::::::::::::::::::::::::::::
Rajumar Singh
java
:::::::::::::::::::::::::::::::::::::::::::::::

the example is self explementory.......hope u enjoy the code segment
looking forward to your reply

Sunday, September 4, 2011

New in Java 7

You'll be able to use String values in switch-case statements! It'll support A COMPLETELY NEW BYTE CODE -- Invoke Dynamic -- which might be used, maybe, by some other languages on the platform, some years from now after Java 7 is widely adopted. You'll be able to put UNDERSCORES in numeric literals -- like 1_345_892!!! Excitement is at an all-time-high!!!!! Java 7 has a known runtime optimization bug that is known to do crazy things, including corrupting files. Use the '-XX:-UseLoopPredicate' command line option to disable that feature/bug. Actually, this bug was present in Java 6. But it's disabled by default in Java 6, so hardly anyone used it. But Java 7 enables it by default, so *everyone* has been testing/using it, and it corrupted lots of files