Saturday, 24 December 2016

Binary Search Java Program


public class BinarySearch {
    int binarySearchRecursive(int arr[], int l, int r, int x)
    {
        if (r>=l)
        {
            int mid = l + (r - l)/2;
             if (arr[mid] == x)
               return mid;
              if (arr[mid] > x)
               return binarySearchRecursive(arr, l, mid-1, x);
              return binarySearchRecursive(arr, mid+1, r, x);
        }
         return -1;
    }

    int binarySearchIterative(int arr[], int l, int r, int x)
    {
        while(r>=l)
        {
            int mid = l + (r - l)/2;
              if (arr[mid] == x)
               return mid;
            if (arr[mid] > x)
               {
            r = mid -1;
               }
            else
            {
            l = mid + 1;
            }
        }
        return -1;
    }

public static void main(String[] args) {
BinarySearch ob = new BinarySearch();
        int arr[] = {2,3,4,10,40};
        int n = arr.length;
        int x = 10;
        int result = ob.binarySearchRecursive(arr,0,n-1,x);
        if (result == -1)
            System.out.println(" not present");
        else
            System.out.println(" found at index "+result);
       
        int result1 = ob.binarySearchIterative(arr,0,n-1,x);
        if (result1 == -1)
            System.out.println("not present");
        else
            System.out.println("found at index "+result1);      
}
}

Running .sql file from Java code

Demo on running .sql file from Java Code. Here postgres database is used but commands can be modified for other databases.

 public void createCleanUpProcedure()
  {
 
  Runtime rv = Runtime.getRuntime();
       Process pRestore = null;
       ProcessBuilder pb;
       rv = Runtime.getRuntime();
       pb = new ProcessBuilder(
           "C:\\Program Files\\PostgreSQL\\9.4\\bin\\psql.exe",
           "--host", "localhost",
           "--port", "5432",
           "--username", "postgres",
           "--dbname", "databaseName",            
           "--no-password",            
          "--file","E:\\pgBackup\\Test.sql");

       pb.redirectErrorStream(true);
       try {
pRestore = pb.start();
} catch (IOException e)
                             {
e.printStackTrace();
      }
     
       InputStreamReader isr = new InputStreamReader(pRestore.getInputStream());
       BufferedReader br = new BufferedReader(isr);
       String ll;
                try {
while ((ll = br.readLine()) != null) {
System.out.println(ll);
}

     } catch (IOException e) {
e.printStackTrace();
 }
  }



Restoring Database backup file using java code

This program restores the data from backup file to specified database. Here database used is postgres but the commands can be modified for other databases as well.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.InputStream;

public class dataBaseMigration {
public static void main(String[] args) throws Exception {

Runtime rv = Runtime.getRuntime();
        Process pRestore = null;
        ProcessBuilder pb;
        rv = Runtime.getRuntime();
        pb = new ProcessBuilder( 
            "C:\\Program Files\\PostgreSQL\\9.4\\bin\\pg_restore.exe", //modify this for other databases
            "--host", "localhost",
            "--port", "5432",
            "--username", "postgres",
            "--dbname", "test_database",
            "--role", "postgres",
            "--no-password",
            "--verbose",
           "E:\\pgBackup\\db_name.backup");

        pb.redirectErrorStream(true);
        pRestore = pb.start();
        //BufferedReader rRestore = new BufferedReader(new InputStreamReader(pRestore.getInputStream()));
       // InputStream is = pRestore.getInputStream();
        InputStreamReader isr = new InputStreamReader(pRestore.getInputStream());
        BufferedReader br = new BufferedReader(isr);
        String ll;
        while ((ll = br.readLine()) != null) {
         System.out.println(ll);
        }  
      }
}  

Taking backup of a DataBase through Java Code

This program takes the backup of a relational database PostGres using java code. It can be easily modified for other databases. Just need to supply the respective commands.

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.omg.CORBA.portable.InputStream;

public class dataBaseMigration {

public static void main(String[] args) throws Exception {
   
System.out.println("*********** Main Function *********** ");

      ProcessBuilder builder = new ProcessBuilder(
 "cmd.exe", "/c", "cd \"C:\\Program Files\\PostgreSQL\\9.4\\bin\" && pg_dump  --format=c
 --username \"postgres\" DataBase_name> \"E:\\pgBackup\\db_name.backup\"");
     //passing the location for pg_dump, database to be backed and file name for backup

         builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }

}

Note :
1. You need to get the windows command line and then run the command for taking the back. This command can be changed for other databases.

Another Way to call pg_dump from Java Program :
PropertiesUtil propeties = new PropertiesUtil("myPropertyfile.properties");
String db_backup_file = propeties.getPropertyValue("dbbackup_file");
String password = propeties.getPropertyValue("password");

ProcessBuilder builder = new ProcessBuilder("C:\\Program Files\\PostgreSQL\\9.4\\bin\\pg_dump.exe",
         "-v","-h", "localhost","-f",db_backup_file, "-U","postgres","DataBaseName");
       

builder.environment().put("PGPASSWORD",password);
builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }
     

Tuesday, 15 March 2016

SQL Join with 3 tables?

SQL JOIN With 3 Tables Example :
Example#1
SELECT  t1.column1, t2.column2, t3.column3
FROM table1 t1 INNER JOIN
table2 t2 ON t1.column1 = t2.column2  AND t1.column2 = t2.column3
LEFT OUTER JOIN  table3 t3 ON t2.column2= t3.column2 AND t2.column3 = t3.column3
WHERE  t1.column1=45;

Example#2
SELECT  t1.column1, t2.column2, t3.column3
FROM table1 t1 INNER JOIN
table2 t2 ON t1.column1 = t2.column2  AND t1.column2 = t2.column3
INNER JOIN  table3 t3 ON t2.column2= t3.column2 AND t2.column3 = t3.column3
WHERE  t1.column1=45;
Note: SQL join works from left to right. In this case, it will first join table1 with table2 and then result of this will get joined with table3



Thursday, 3 March 2016

Java Properties File: Reading config.properties Values in JAVA

Reading config.properties Values in JAVA :
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Monday, 29 February 2016

Calling RestApi Web Services From Java Program

A JAVA Program to call RestApi Services :

package RestApiClientTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class NetClientGet {
public static void main(String[] args) {
 try {
 URL url = new URL("http:/localhost:8983/rest/calculatesum"); // rest api url
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
 } catch (MalformedURLException e) {
e.printStackTrace();
 } catch (IOException e) {
e.printStackTrace();
 }
}

You need to include below jars in your class path:
1. jackson-databind
2. jackson-annotations
3. jackson-core

Maven details for the jars :
  <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1.1</version>
</dependency>

Thursday, 11 February 2016

Date Formatting in Java Example

Date Formatting in Java Example :
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatting {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        Date date=new Date();
        String str_date=df.format(date);
        System.out.println("dd-MM-yyyy: "+str_date);
        df.applyPattern("yyyy-MM-dd");
        System.out.println("yyyy-MM-dd: "+df.format(date));      
     
        System.out.println("*****************");        
        SimpleDateFormat df2 = new SimpleDateFormat("dd-MM-yyyy");
        String str="10-02-2016";
        //Date date=new Date();
        Date date1=null;
try {
date1 = df2.parse(str);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        df2.applyPattern("yyyy-MM-dd");
        System.out.println("yyyy-MM-dd: "+df2.format(date1));
}

}



String to Date :
private Date convertStringToDate(String inputString) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(inputString);

return date;
}

PGSQL date column :

@Temporal(TemporalType.DATE) @Column(name="patient_dob", nullable=false) private Date patientDob;
 

Wednesday, 27 January 2016

Java - Convert String containing decimal values to BigDecimal


Java Program to convert String containing decimal values into BigDecimal :
Sometime, we try to convert the String containing the decimal values into the Long. But since, int and long are Integer type so they can't have the decimal values to Long.valueOf(StringValue) gives the error.
The correct approach is to convert the string decimal into the BigDecimal or Double and use them as decimal values.

Example :
        String double_as_string = "23.23";
        BigDecimal price = new BigDecimal(double_as_string);

Tuesday, 26 January 2016

Java - Removing the trailing zeroes from a long number

Java Program to remove the trailing zeroes from the long digit :
Trailing zeroes can be removed from the long digit by using the DecimalFormat class. Below is one such example.

import java.text.DecimalFormat;
public class removeTrailingZero {
public static void main(String[] args) {
double answer = 5.0;
double answer1 = 4.50;
double answer2 = 5.25;
  DecimalFormat df = new DecimalFormat("###.##");
 System.out.println(df.format(answer));  
 System.out.println(df.format(answer1));
 System.out.println(df.format(answer2));
String x = df.format(answer);
System.out.println(x);
}
}

Monday, 11 January 2016

SQL - Adding a column in table from another table based on common column data in both table

We need to update values in table1 with data from table2 where common_column is the present in both tables and data should be updated based on this :

update table1 tl set table1_column=(select v.table2_column from table2 v where v.common_column= tl.common_column) where tl.table2_column is not null;  -- here condition can be any other condition 

Friday, 8 January 2016

Program to remove white spaces and special character from String in JAVA

JAVA Program to remove white spaces and special characters from String:

public class testRegular {
public static void main(String[] args) {
String text = "This - word ! has \\ /allot # of % special % characters ? this12340   _ ASGHJKK \t";
text = text.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(text);
}}


Here it will remove everything except alphabets [ small and capital ] and digits [ 0 - 9].

Similarly, we can make our permutation and combination of  arrangements in replaceAll method.