Monday, 30 January 2017

Yesterday's Date using Java code

Java code snipet for Yesterday's Date :

We can use Calendar class to do this job.

                                Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = cal.getTime();
System.out.println(df2.format(date));
String dateForConsultation = df2.format(date);

Sunday, 29 January 2017

MD5 Hash Code Encription

Java Code Snipet for MD5 Encription :

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public  String md5(final String s) {
        final String MD5 = "MD5";
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest
                    .getInstance(MD5);
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

           // Create Hex String
            StringBuilder hexString = new StringBuilder();
            for (byte aMessageDigest : messageDigest) {
                String h = Integer.toHexString(0xFF & aMessageDigest);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();

       } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

Base64 Decode and Encode

Java Code snipet for Base64 Encode and Decode

import org.apache.commons.codec.binary.Base64;

// Encode data on your side using BASE64
byte[]   bytesEncoded = Base64.encodeBase64(str .getBytes());
System.out.println("ecncoded value is " + new String(bytesEncoded ));

// Decode data on other side, by processing encoded data
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
System.out.println("Decoded value is " + new String(valueDecoded));


Maven Dependencies :
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>

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);
        }