Wednesday, 7 May 2014

Sort Integer array without using sort() method -Java

Hi Viewers


        This post is regarding a small code snippet which helps us to sort an integer array of elements   without using any of the sort() method present in Arrays or Collections in Java API.We used bubble       sort  technique to sort the integer array.This is being asked frequently in written exams of interviewing process.Hope this code snippet helps you 


Code Begins here:


public class SortIntArray {

 public static void main(String[] args) {
  int[] a={12,4,1,7,10,21,21,18,17,15,5,34,30};
  SortIntArray sia=new SortIntArray();
  int[] des=sia.toDescendingOrder(a);
  int[] asc=sia.toAsscendingOrder(a);
  System.out.println(">>>>>>>>>>>descending order>>>");
  for(int i=0;i<des.length;i++){
   System.out.print(des[i]+"\t");
  }
  System.out.println("");
  System.out.println(">>>>>>>asscending order>>>>>>");
  for(int i=0;i<asc.length;i++){
   System.out.print(asc[i]+"\t");
  }
 }
  public int[] toDescendingOrder(int[] a){
   int[] b=toAsscendingOrder(a);
   int c[]=new int[b.length];
   int j=0;
   for(int i=b.length-1;i>=0;i--){
    c[j]=b[i];
    j++;
   }
 return c;
  }
  public int[] toAsscendingOrder(int[] a){
  int swap;
  for(int i=0;i<a.length-1;i++){
   for(int j=0;j<a.length-1-i;j++){
    if(a[j]>a[j+1]){
     swap=a[j];
     a[j]=a[j+1];
     a[j+1]=swap;
    }
   } 
  }
   return a;
  }
}
output: >>>>>>>>>>>descending order>>>
        34 30 21 21 18 17 15 12 10 7 5 4 1 
        >>>>>>>asscending order>>>>>>
        1 4 5 7 10 12 15 17 18 21 21 30 34

Wednesday, 9 April 2014

Mongodb Import and Export database -MONGODB


This post is regarding how to import and export mongodb data dump. 
To export the database we need to run  mongodump.exe.
To import the database dump we need to run mongorestore.exe.
Consider and example Customer database need to be exported and imported


WINDOWS:

Export Dump:
step 1: Make sure that mongodb is running in your machine if its not running
go to mongodb\bin folder in your mongodb installation and run mongod.exe file
step 2: Run mongodump.exe file which will export all schema present in db to data folder
inside bin directory of mongodb installation

Step 3: If you want to export a particular schema of your db to a desired location in your machine
then press windows+r type cmd and thenEnter button your command prompt will be opened Go to mongo installation bin directory

Command : mongodump.exe -d customer --out C:\

This will export database customer to C:\ in your machine

    Restore Dump:
command:mongorestore.exe -d customer C:\\customer
This will import database customer to mongodb

UBUNTU :
Export Dump:
step 1: Make sure that mongodb is running in your machine if its not running
run command sudo service mongodb startand the run the below command to
export the dump
Command :mongodump -d customer --out /home

This will export database customer to /home in your machine

Restore Dump:
command:mongorestore -d customer /home/customer
This will import database customer to mongodb




Thanks and regards

javasimplestuff

Tuesday, 25 March 2014

Write data to Excel using Apache POI -Java

HI

This post is regarding writing data to a xlsx sheet.In java we had many powerful API's to write data to CSV or xlsx or xls files.One such API is apache POI by apache foundation.This API has classes and interfaces which helps us to write data to .csv or .xlsx sheets.

Here I am providing you a sample code snippet which helps you to explore and experiment more on this

ENVIRONMENT: java 1.6 sdk,apche poi  jars

Download location : http://poi.apache.org/download.html

Setup your environment add jars to the build path in eclipse.

Code begins:


 import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class sample {

 public static void main(String[] args) {
   try {
  String sample="test content";
  Workbook wb=new XSSFWorkbook();
  Sheet sheet=wb.createSheet("samplesheet");
  Row row=sheet.createRow(0);
  Cell cell=row.createCell(0);
  row.getCell(0).setCellValue(sample);
  FileOutputStream fop=new FileOutputStream("sample.xlsx",true);
  wb.write(fop);
  fop.flush();
  fop.close();
  } catch (Exception e) {
  
   e.printStackTrace();
  }

 }

}   

Output: This sample created a Excel sheet with first cell filled with the string test content

Friday, 21 March 2014

Grails with Mysql database DataSource.groovy configuration

Hello viewers

In this post i am going to give a sample of code snippet which helps to configure Grails with mysql database. First of all grails is a framework which is developed by integrating hibernate and spring framework by springsouce .In a grails-app to communicate with database we provide all our configuration in DataSource.groovy file present under grails-app/conf folder in a grails project


dataSource {
    pooled = true
    dbCreate = "update"
    url = "jdbc:mysql://localhost:3306/yourDb"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "root"
    password = "xxxx"
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
    development {
        dataSource {
            pooled = true
            dbCreate = "update"
            url = "jdbc:mysql://localhost:3306/yourDb"
            driverClassName = "com.mysql.jdbc.Driver"
            username = "root"
            password = "xxxx"
        }
    }

and in grails we had plugins which will handle many operations.here to connect to mysql we need connector jar which in java we download and include it in our build path.But in grails right click on project in any of your IDE (Here i am using intellij idea) and in options choose grails-->plugins and search for mysql .Now install all mysql dependent plugins

then it get reflected in application.properties in your project as
plugins.mysql-connectorj=5.1.22.1

Here ends the configuration now you access mysql with your grails app


Thanks and regards
venkata naveen

Wednesday, 5 March 2014

Run a Java Thread For Certain period of time java

A sample program on threads to demonstrate how to start a thread and run it for a specified period of time (say 2 minutes in this below example).

Code begins here.........


import java.util.Calendar;
class ThreatRunner extends Thread{
 @Override
 public void run() {
  System.out.println(" in the thread");
  try {
   sleep(10000);
  } catch (InterruptedException e) {

   e.printStackTrace();
  }
 }
}
public class ThreadWithTimer {
 public static void main(String[] args) {
  ThreatRunner tr=new ThreatRunner();
  Thread tt=new Thread(tr);
  Calendar mycal=Calendar.getInstance();
  long currentTimer=System.currentTimeMillis();
  System.out.println(mycal.getTime());
  while ((System.currentTimeMillis()-currentTimer)< 2*60*1000){
   tt.run();

  }
  System.out.println(mycal.getTime());

 }

}
Output: Thu Mar 06 12:17:04 IST 2014
in the thread
in the thread
Thu Mar 06 12:19:04 IST 2014

Thursday, 30 January 2014

Avoid cloning Singleton object -Java

HI Viewers
 Here i'm going to give a short note one how to avoid a singleton object from getting cloned.This is one of the interview questions that are being asked frequently while interviewing .We all know that singleton pattern is which doesn't allow for invoking new keyword while creating new instance to that class.generally we achieve it in many ways that i will explain in Singleton design pattern .Here I'm giving you a small code snippet which doesn't allow Singletons instance from getting cloned.

Create a class Singleton and override the Object class clone method and return CloneNotSupported instance to that method
public class Singleton implements Cloneable{
 private static Singleton ss=new Singleton();
 
 private  Singleton() {

 }

 public static Singleton getInstance(){
  return ss;
 }
  public Object clone(){
   
  return new CloneNotSupportedException();
   
  }

}
Now create a sample class to check the Singleton class clone mechanism
public class Example {
public static void main(String args[]){
 
 Singleton ss=(Singleton) Singleton.getInstance().clone();
}
}
Out put: Exception in thread "main" java.lang.ClassCastException: java.lang.CloneNotSupportedException cannot be cast to Singleton

Tuesday, 21 January 2014

UBUNTU-System Stuck in Login Loop

Hi Ubuntu users,you might some times face these problem like when you try to log in with proper credentials it will get logged in immediately a black screen appears. Weird thing without even you see the content on the black screen your machine again show you log in screen.And the process repeats and make you vexed.Here is the solution which i found and made may machine work .


Step 1: Press ctrl+alt+F3 in your machine .you will get shell screen log in to it .

Step2 : Run ls-lah command in the shell .Check for .Xauthority in the output shown.If the output is like
           -rw------- 1 root root 53 Jan 21 10:19 .Xauthority


Step 3: Do  sudo chown username:username .Xauthority and try logging in .It worked for me and               try  this yourselves if you got stuck in the similar way


Thanks and Regards
JavasimpleStuff

Thursday, 19 December 2013

ArrayList Without Duplicate java

Hi this is a  sample example of java how we can write a ArrayList and eliminate duplicates in it .Below is the code snippet that gives you an idea on how to eliminate duplicates from arraylist

import java.util.ArrayList;
public class ArrayListWithoutDuplicates {
     
 public static void main(String args[]){

  ArrayList<String> original = new ArrayList<String>();
  ArrayList<String> eliminateDuplicate= new ArrayList<String>();

  original.add("Naveen");
  original.add("Rajesh");
  original.add("Pradeep");
  original.add("Rajesh");


  for (String dupWord : original) {
      if (!eliminateDuplicate.contains(dupWord)) {
          eliminateDuplicate.add(dupWord);
      }
  }
  System.out.println(eliminateDuplicate);
 }

}
Output : [Naveen, Rajesh, Pradeep]

Wednesday, 4 December 2013

Collections Sort a HashMap Based On Values Java

Hi Viewers  I'm going to give you an example to sort an unsorted HashMap using Comparator in java.
Comparator can be used to sort the classes that implement sorted maps and sorted sets .As per the java docs we can pass Comparator ,map or sorted map . So here in below code snippet we pass object of class to TreeMap's constructor in which we implemented Comparator . It then creates a new TreeMap which is sorted as per Comparator ans displays the desired result.
Below is the code snippet that gives a clear example of how to sort HashMap based on its value objects
  
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;

public class SortHashMap {
 public SortHashMap() {
  
 }
 public static void main(String args[]){
  HashMap<String,String> mp=new HashMap<String,String>();
  mp.put("1","America");
  mp.put("2", "Florida");
  mp.put("3", "England");
  mp.put("4", "Dallas");
  CheckComparator cc=new CheckComparator(mp);
  TreeMap<String,String> tm=new TreeMap<String,String>(cc);
  tm.putAll(mp);
  System.out.println(tm);
 
 }
}
class CheckComparator implements Comparator{
 private HashMap<String, String> mp;

 public CheckComparator(HashMap<String, String> mp) {
  this.mp=mp;
 }

 @Override
 public int compare(Object o1, Object o2) {
  if(mp.get(o1).toString().compareTo(mp.get(o2).toString())>0){
   return 1;  
  }else if(mp.get(o1).toString().compareTo(mp.get(o2).toString()<0){
  return -1;
  }else{
   return 0;
  }
}
Output:
{1=America, 4=Dallas, 3=England, 2=Florida}

Collections Comparator Interface with example java

Comparator Interface with example:

Comparator Interface belongs to java.utill package. Comparator is also used to compare the two objects by overriding its inherited int compare(Object o1,Object o2) method.Here I'm going to give example to understand well about Comparator Interface in java.
Create an Employee bean class Employee.java :
 public class Employee{
 private int eid;
 private String ename;
 private int age;
 
 public Employee(int eid,String ename,int age) {
this.eid=eid;
this.ename=ename;
this.age=age;
 }
 public int getEid() {
  return eid;
 }
 public void setEid(int eid) {
  this.eid = eid;
 }
 public String getEname() {
  return ename;
 }
 public void setEname(String ename) {
  this.ename = ename;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 
}
Now create a class EmployeeAgeComparator.java to compare and sort based on ages as below
public class EmplyeeAgeComparator implements Comparator<Employee>
{

 @Override
 public int compare(Employee o1, Employee o2) {
  if(o1.getAge()>o2.getAge())
   return 1;
  if(o1.getAge()<o2.getAge())
   return -1;
  if(o1.getAge()==o2.getAge())
   return 0;
  return 0;
 }

}
Create an employee comparator class and call Collections.sort() method to sort values based on age and print values
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.interview.comparatortest.Employee;
public  class EmployeeComparator {
 public static void main(String args[]){
  List<Employee> emp=new ArrayList<Employee>();
  emp.add(new Employee(1,"Alfred", 23));
  emp.add(new Employee(2,"Ion Bell", 21));
  emp.add(new Employee(3,"Clarke",30));
  Collections.sort(emp,new EmplyeeAgeComparator());
  for(Employee test:emp){
   System.out.println("age=="+test.getAge()+"\tname=="+test.getEname()+"\teid=="+test.getEid());
  }

 }

}
Output :
age==21 name==Ion Bell eid==2
age==23 name==Alfred eid==1
age==30 name==Clarke eid==3

Tuesday, 3 December 2013

Comparable Interface with Example Java

Comparable Interface with Example:

Hi in this post i would like to give you an explanation regarding comparable interface example in java.
Comparable is an interface which belong to java.lang package .Comparable interface helps in ordering of the objects for a class which implements this interface.Here I'm giving you a scenario which explains the comaparable


Q): Using ArrayList take the values of an employee like his name,age,eid and i wanted to get the list to be printed in sorted order as per their names.

Solution: First i created a Employee bean class having getters and setters in it as below.
and implement the Employee class with Comparable interface with Employee as generic type .Implementing comparable will insist you to override the int compareTo(Employee o) method in Employee class

Below is the code snippet Employee.java:
  public class Employee implements Comparable<Employee>{
 private int eid;
 private String ename;
 private int age;
 
 public Employee() {
 }
 public int getEid() {
  return eid;
 }
 public void setEid(int eid) {
  this.eid = eid;
 }
 public String getEname() {
  return ename;
 }
 public void setEname(String ename) {
  this.ename = ename;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 @Override
 public int compareTo(Employee o) {
       
  if(this.ename.compareTo(o.ename)>0)
      
   return 1;
  else if(this.ename.compareTo(o.ename)<0)
   return -1;
  else
   return 0;
 }
Now create a SortEmployee class  where we get the final result of sorted employee details with names. Below is the code snippet SortEmployee.java:  
import java.util.ArrayList;

import java.util.Collections;

public class SortEmployee {
 public static void main(String args[]){
 
     Employee naveen=new Employee();
  naveen.setAge(24);
  naveen.setEid(1);
  naveen.setEname("naveen");
  Employee vivek=new Employee();
  vivek.setAge(32);
  vivek.setEid(2);
  vivek.setEname("vivek");
  Employee check=new Employee();
  check.setAge(44);
  check.setEid(3);
  check.setEname("piyush");
 ArrayList<Employee> emps=new ArrayList<Employee>();

 emps.add(naveen);
 emps.add(vivek);
 emps.add(check);

  Collections.sort(emps);
  
  for(Employee emp1:emps){
   System.out.println(emp1.getEname()+">>>>"+emp1.getAge()+">>>>"+emp1.getEid());
  }
 }
}

Now if we run the SortEmployee.java we get the desired output as below:
naveen>>>>24>>>>1
piyush>>>>44>>>>>3
vivek>>>>32>>>>2

To sort the employee details based on age change compareTo method as below and re run the program :
 @Override
 public int compareTo(Employee o) {
  
  if(this.age>o.age)
   return 1;
  else if(this.age<o.age)
   return -1;
  else
   return 0;
 }
output:
naveen>>>>24>>>>1
vivek>>>>32>>>>2
piyush>>>>44>>>>3

Sunday, 1 December 2013

UBUNTU- Errors Encountered While Processing google-chrome-stable

Errors Encountered While Processing google-chrome-stable

Today when i tried installing google-chrome in my ubuntu machine ,i was stuck with this error in my terminal .After searching for some thing to make it work out in i found the below solution for this

Step 1: Do a sudo apt-get install -f in your terminal It will install some dependencies in your machine.

Step2 : now install your chrome .deb file using command 
                  sudo dpkg -i google-chrome-stable_current_amd64.deb

and here their it ends with successful installation of chrome browser in your machine


Thanks and Reagrds
Naveen 

Friday, 29 November 2013

JSP accepting String[] as attribute to custom tag

JSP accepting String[] as attribute to custom tag

Hi viewers  In the below example I'm giving you the code samples that i have done for this task

Step 1: Create a dynamic web project in your eclipse
Step 2: create a package with any of your desired name  say    com.practice.customtags

Step 3: Create a java class with some name say SimpleTag.Java


 
package com.pratice.customtags;
import java.io.IOException;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class SimpleTag extends TagSupport {
 private static final long serialVersionUID = 6997517813033042928L;
 private String[] input;
 
 public int doEndTag(){ 
  JspWriter out =pageContext.getOut();
    try {
     for(int i=0;i<input .length;i++){
          out.println(input[i]);
         }
  
 } catch (IOException e) {
  
  e.printStackTrace();
 }
    return EVAL_PAGE;
 }

 public String[] getInput() {
  return input;
 }

 public void setInput(String[] input) {
  this.input = input;
 }
  
}


Step 4: Create a new file with and save as custom.tld in your eclipse .save it under
               WebContent/WEB-INF/custom.tld
 
   1.0
  2.0
  Example TLD
  
    ObjectArray
    com.pratice.customtags.SimpleTag 
     
      input
      true
      java.lang.String[]
      true  
      false
    
   

Step 5: Create a jsp file index.jsp under WebContent folder of your dynamic web application

<%@ taglib prefix="My" uri="WEB-INF/custom.tld"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   


<%String[] check={"naveen","rajesh","vivek"}; %>
   


Step: And Finally run the web application you will see the output as naveen
rajesh vivek Thanks and Regards Naveen

Monday, 25 November 2013

About Me

      Hi I'm Naveen. I am a Software developer and a beginner.I created this blog to do simple coding exercises. Write some technical stuff in this blog which helps me and other developers in their daily coding tasks .If you like my posts click like and post your feedback in the below comment box.You can contact me at venkatanaveen.iter@gmail.com



                                 Thanks and reagrds
                                  Naveen...........................