Monday, 14 May 2018

Producer-Consumer Problem solved using Blocking Queue

The problem can be approached using various techniques
  • Using wait() and notifyAll()
  • Using BlockingQueue
  • Using sempahores

How to use BlockingQueue in code
public class ProducerConsumerBlockingQueue {

  static int MAX_SIZE = 5;
  static BlockingQueue queue = new LinkedBlockingQueue(MAX_SIZE);

  public static void main(String[] args) {

    Producer producer = new Producer();
    Consumer consumer = new Consumer();
    producer.start();
    consumer.start();
  }

  static class Producer extends Thread {
    Random random = new Random();

    public void run() {
      while (true) {
        int element = random.nextInt(MAX_SIZE);
        try {
          queue.put(element);
        } catch (InterruptedException e) {
        }
      }
    }
  }

  static class Consumer extends Thread {
    public void run() {
      while (true) {
        try {
          System.out.println("Consumed " + queue.take());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}

//Output
Producer 2
Producer 3
Consumed 2
Consumed 3
Producer 0
Producer 4
Consumed 0



Tuesday, 17 April 2018

How to use Google Translate API in Java application ?

You can do the language translation using Google Translate API. Below is the Java code for integration.

import java.util.Arrays;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;

public class GoogleTranslationAPISample {
public static void main(String[] arguments) throws GeneralSecurityException, IOException 
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
// Set your application name
                .setApplicationName("sample-Example")
                .build();
        Translate.Translations.List list = t.new Translations().list(
                Arrays.asList(
// Pass in list of strings to be translated
                "Hello World",
                "How to use Google Translate from Java"),
// Target language
                "es"); // es for spanish

// TODO: Set your API-Key from https://console.developers.google.com/
// list.setKey("your-api-key");
        
//list.setKey("AIdwaSyCAKK7htoeT8i8ArmITELoDMyuiorooe5wk-cKs5g"); // my test credentials

        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Maven Dependencies :

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-translate</artifactId>
  <version>1.24.1</version>
</dependency>
<dependency>

  <groupId>com.google.api-client</groupId>
  <artifactId>google-api-client-gson</artifactId>
  <version>1.23.0</version>
</dependency>

References :
https://cloud.google.com/vision/docs/libraries
https://github.com/GoogleCloudPlatform/java-docs-samples

Tuesday, 27 February 2018

How to Create a Cron Job or Scheduling Function in Tomcat

Scheduling Function or Repeating Job in Tomcat 

Repeating jobs in tomcat can be created by creating a listener which will get started when tomcat is started or new war is deployed and destroyed when tomcat is shutdown.
We can take advantage of thread and infinite loop in which we can do our repetitive work and then wait for specified time and loop again.
This example have been tested in tomcat 8.5.23 and will be applicable for other application server as well.

web.xml 
<listener>
<listener-class>com.test.api.util.NotificationListener</listener-class>
</listener> 

Java class
package com.test.api.util;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class NotificationListener implements ServletContextListener {
    private Thread t = null;
    private ServletContext context;
    public void contextInitialized(ServletContextEvent contextEvent) {
        t =  new Thread(){
            //repeating task
            public void run(){               
                try {
                    while(true){
                        // do all you repeating jobs here.
                       // Example 1. sending reports every 5 mins. 2. sending notifications 3. db cleanup etc.
                       
                        Thread.sleep(1000*60*5); // thread waits for 5 mins.
                    }
                } catch (InterruptedException e) {}
            }           
        };
        t.start(); // starting the thread
        context = contextEvent.getServletContext();
        // context values can be set as well as shown below
        context.setAttribute("TEST_VARIABLE", "VALUE");
    }
    public void contextDestroyed(ServletContextEvent contextEvent) {
        // context is destroyed interrupts the thread
        t.interrupt();
    }           
}

NOTE
1. you can use producer and consume problem approach as well and start them in constructor.



Tuesday, 9 January 2018

Configuration and Command to Directoy Deploy to Remote Server through maven

configuration and command to directoy deploy to remote server through maven :
-----------------------------------------------------------------------------
pom.xml configuration :

<build>
<finalName>MYWAR</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://XX.XX.XX.XX:8080/manager/text</url>
<username>admin</username>
<password>admin</password>
<path>/MYWAR </path>
</configuration>
</plugin>
</plugins>
</build>

------------------------------------------------------------------------------
maven command :

mvn compile tomcat7:redeploy

------------------------------------------------------------------------------

Tuesday, 18 April 2017

JAVA ---> Generating unique IDs

To generate UUID in Java we can use the java.util.UUID class. This class was introduced in JDK 1.5. The UUID.randomUUID() method return a UUID object.

A Sample Java Program for Generating Unique IDs :
import java.util.UUID;
public class GeneratingUniqId {
public static void main(String[] args) {
            UUID testId1 = UUID.randomUUID();
   UUID testId2 = UUID.randomUUID();
   System.out.println("UUID One: " + testId1);
   System.out.println("UUID Two: " + testId2);

}
}

Sunday, 26 February 2017

java - How to make an executable jar using maven with all dependencies added ?


Creating an executable jar file through maven with all dependecies added :
Requirement :
To pack a little app with all dependencies [external jars ] through maven and run it from the console.

maven-assembly-plugin can be used to assemble all the dependent jar into the same executable jar so that we do not need to pass the classpath of dependent jars while running the executable jar.

To do it just add the following to pom.xml and make sure we write the correct path to our main class.

 <build>
     <plugins>
       <plugin>
         <artifactId>maven-assembly-plugin</artifactId>
         <configuration>
           <archive>
             <manifest>
               <mainClass>com.test.MavenBuildTest</mainClass>
             </manifest>
           </archive>
           <descriptorRefs>
             <descriptorRef>jar-with-dependencies</descriptorRef>
           </descriptorRefs>
         </configuration>
         <executions>
           <execution>
             <id>make-assembly</id>
             <phase>package</phase>
             <goals>
               <goal>single</goal>
             </goals>
           </execution>
         </executions>
       </plugin>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>2.5.1</version>
         <inherited>true</inherited>
         <configuration>
           <source>1.7</source>
           <target>1.7</target>
         </configuration>
       </plugin>
     </plugins>
   </build>
 

When the maven package gets executed, two .jar files will be created.
The one with the text jar-with-dependencies on its name,
will contain is the one we should run. To do it, just go to the terminal,
navigate to it(inside the target folder) and type the command:
 java -jar myapp-jar-with-dependencies.jar

Here is complete pom Example:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>MavenBuildTest</groupId>
  <artifactId>MavenBuildTest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
     <plugin>
       <artifactId>maven-compiler-plugin</artifactId>
       <version>3.1</version>
       <configuration>
         <source>1.7</source>
         <target>1.7</target>
       </configuration>
     </plugin>
    <plugin>
         <artifactId>maven-assembly-plugin</artifactId>
         <configuration>
           <archive>
             <manifest>
               <mainClass>MavenBuildTest</mainClass>
             </manifest>
           </archive>
           <descriptorRefs>
             <descriptorRef>jar-with-dependencies</descriptorRef>
           </descriptorRefs>
         </configuration>
         <executions>
           <execution>
             <id>make-assembly</id>
             <phase>package</phase>
             <goals>
               <goal>single</goal>
             </goals>
           </execution>
         </executions>
       </plugin>
        </plugins>
<finalName>MavenBuildTest</finalName>
  </build>
  <dependencies>
       <dependency>
          <groupId>org.postgresql</groupId>
           <artifactId>postgresql</artifactId>
           <version>9.4-1201-jdbc4</version>
            </dependency>
     <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.1.3</version>
  <!-- <scope>system</scope>
  <systemPath>${basedir}\src\lib\jackson-databind-2.4.1.3.jar</systemPath> -->
 </dependency>
 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.4.1</version>
  <!-- <scope>system</scope>
  <systemPath>${basedir}\src\lib\jackson-annotations-2.4.1.jar</systemPath> -->
 </dependency>
 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.4.1.1</version>
  <!-- <scope>system</scope>
  <systemPath>${basedir}\src\lib\jackson-core-2.4.1.1.jar</systemPath> -->
 </dependency>
 <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
   <!--  <scope>system</scope>
    <systemPath>${basedir}\src\lib\json-simple-1.1.1.jar</systemPath> -->
</dependency>

    </dependencies>
<packaging>jar</packaging>
</project>

Tuesday, 31 January 2017

Calling Https url from Java Code

Java code snipet for hitting Https url from Java code ::

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestHitSSL {

    public static void main(String[] args) throws Exception {
        // Need to create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Installing the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Installing the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        URL url = new URL("https://www.google.com"); // test https url
        URLConnection con = url.openConnection();  //opening the url connection to test url
     
        final Reader reader = new InputStreamReader(con.getInputStream());
        final BufferedReader br = new BufferedReader(reader);      
        String message = "";
        while ((message = br.readLine()) != null) // reading the line from InputStream
    {
            System.out.println(message );
        }      
        br.close(); //closing the BufferedReader
    }
}

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

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