Thursday, 27 August 2015

Shutdown Hooks


It is one of the concurrency concept.JVM(Java Virtual Machine) can shutdown in an orderly or abruptly manner. An orderly shutdown is nothing but when all normal threads terminates successfully,or by calling System.exit(),or by closing it from special keys like Ctrl+C.
JVM can also be shutdown abrubtly by killing the JVM process or by some OS related issues.

What is Shutdown Hooks ?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().
JVM does not give any guarantee on the order in which shutdown hooks are started.In orderly shutdown JVM starts all registered shutdown hooks.

When all shutdown hooks have completed their task,JVM may choose to run finalizers if runFinalizersOnExit is true.JVM does not stop any of the application thread that are still running at shutdown time.they automatically terminated when JVM halts.Also JVM allows to run application threads concurrently with shutdown hooks.In an abrupt shutdown,shutdown hooks will not run.


Example of Shutdown Hook:-

/**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class TestShutdownHook {  
      // shutdown hook thread can be used to perform cleaning of resources.  
      private static class ShutDownHook extends Thread {  
           public void run() {  
                System.out.println("shutdown hook thread started");  
           }  
      }  
      public static void main(String[] args) {  
           ShutDownHook jvmShutdownHook = new ShutDownHook();  
           Runtime.getRuntime().addShutdownHook(jvmShutdownHook);  
           System.out.println("Register Shutdown Hook");  
           System.out.println("calling System.exit() to close the program");  
           System.exit(0);  
           System.out.println("Program Finished");  
      }  
 }  

Output:-  
 Register Shutdown Hook  
 calling System.exit() to close the program  
 shutdown hook thread started  

Advantage of Shutdown Hooks:-

It can be used for service or application cleanup,such as deleting unwanted file, releasing resources like db related resources,file operation resources etc.

 Note:-Shutdown hooks must be thread safe and they should use synchronization when   
 accessing shared data.They should not assume the state of the application(such as all worker   
 thread have completed) at any point of time.They should complete their task as quickly as   
 possible because their existence delays the JVM termination at a time when user may be   
 expecting the JVM to shutdown quickly.  




Wednesday, 19 August 2015

Java program to check if Array contains duplicate elements or not



                         Java program to check if Array contains duplicate elements or not


Arrays are important concept in Java.Everyone should be comfortable with arrays as they are quite often used in programming.

To check if declared array contains unique element or it has duplicates ,below is the sample program

 /**  
  * @author Dixit  
  *   
  */  
 public class DuplicateElement {  
      public static void main(String a[]) {  
           int arr[] = { 1, 2, 3, 4, 1 };  
           System.out.println("Result:-" + hasNoDuplicates(arr));  
           int newArr[] = { 1, 2, 3, 4 };  
           System.out.println("Result:-" + hasNoDuplicates(newArr));  
      }  
      public static boolean hasNoDuplicates(final int[] intArray) {  
           for (int i = 0; i < intArray.length; i++) {  
                if (!isIntUniqueInArray(intArray[i], intArray))  
                     return false;  
           }  
           return true;  
      }  
      private static boolean isIntUniqueInArray(final int value,  
                final int[] intArray) {  
           int occurs = 0;  
           for (int i = 0; i < intArray.length && occurs < 2; i++) {  
                if (intArray[i] == value) {  
                     occurs++;  
                }  
           }  
           return occurs == 1;  
      }  
 }  


Enjoy Programming :)

Java program to find out available free memory and memory used by the application


               Java program to find out available free memory and memory used by the application



Suppose you want to know the memory used by your application and available system memory in order to check the performance of your application.

Here is the implementation to know free memory and memory used by your application:-


/**  
  * @author Dixit  
  *   
  */  
 public class MemoryUtils {  
      public static void main(String a[]) {  
           System.out.println("Percentage of Memory Used:"  
                     + getPercentageMemoryUsed());  
           System.out.println("Free memory in KBs:" + getFreeMemoryInKBs());  
      }  
      public static float getPercentageMemoryUsed() {  
           Runtime runtime = Runtime.getRuntime();  
           long memoryUsedByApplication = runtime.totalMemory()  
                     - runtime.freeMemory();  
           long maximumMemory = runtime.maxMemory();  
           float percentageMemoryUsed = ((memoryUsedByApplication / (float) maximumMemory) * 100);  
           return percentageMemoryUsed;  
      }  
      public static int getFreeMemoryInKBs() {  
           Runtime runtime = Runtime.getRuntime();  
           long memoryUsedByApplication = runtime.totalMemory()  
                     - runtime.freeMemory();  
           long maximumMemory = runtime.maxMemory();  
           long freeMemory = maximumMemory - memoryUsedByApplication;  
           int freeMemoryInKBs = (int) freeMemory / 1024;  
           return freeMemoryInKBs;  
      }  
 }  



Enjoy programming :)

Java program to check if String is Null or Empty



                                    Java program to check if String is Null or Empty


While programming many times we come across the scenario where we have to validate the String object i.e. we need to check whether String is null or empty.

Here is the simple implementation to check whether String is null or empty.

 /**  
  * @author Dixit  
  *  
  */  
 public class EmptyOrNullStringCheck {  
      public static void main(String a[])  
      {  
           String firstString=null;  
           String secondString="abc";  
           String thirdString="";  
           System.out.println("Result of firstString:-"+isNullOrEmpty(firstString));  
           System.out.println("Result of secondString:-"+isNullOrEmpty(secondString));  
           System.out.println("Result of thirdString:-"+isNullOrEmpty(thirdString));  
      }  
      /**  
        * Checks for null or empty.  
        * @author dixit  
        * @param data true/ false  
        */  
        public static boolean isNullOrEmpty(String data) {  
         boolean retStatus = true;  
         if (data != null && !"".equals(data.trim())) retStatus = false;  
         return retStatus;  
        }  
 }  



Enjoy programming:)

Execute Linux commands from Java


                                          Execute Linux commands from Java



Sometime you may get an requirement where you need to run Linux commands inside java program.
For ex: suppose you have to run some script file,so you need to run using sh command of Linux.


 /**  
  * @author Dixit  
  *  
  */  
 public class ExecuteLinuxCommands {  
      public static void main(String a[])  
      {  
           int commandExitCode=executeCmd("ls");  
      }  
      public static int executeCmd( final String command )  
        {  
            int exitCode=-1;  
         Process p = null;  
         InputStream inputstream = null;  
         InputStreamReader inputstreamreader = null;  
         BufferedReader bufferedreader = null;  
         StringBuilder sb = new StringBuilder();  
         try  
         {  
           System.out.println( "Executing : " + command );  
           p = Runtime.getRuntime().exec( command );  
           inputstream = p.getInputStream();  
           inputstreamreader = new InputStreamReader( inputstream );  
           bufferedreader = new BufferedReader( inputstreamreader );  
           String line;  
           while ( ( line = bufferedreader.readLine() ) != null )  
           {  
            sb.append( line );  
            sb.append( "\n" );  
           }  
           System.out.println( sb.toString() );  
           exitCode = p.waitFor();  
         }  
         catch ( Exception e )  
         {  
           // Swallow all exceptions  
           System.out.println( "Command execution failed"+e);  
         }  
         finally  
         {  
           try  
           {  
            if ( p != null ) p.destroy();  
            if ( inputstream != null ) inputstream.close();  
            if ( inputstreamreader != null ) inputstreamreader.close();  
            if ( bufferedreader != null ) bufferedreader.close();  
           }  
           catch ( IOException e )  
           {  
           }  
         }  
         return exitCode;  
        }  
 }  


Note:This program is suitable for Linux environment.You can run any Linux command and view the output.

Enjoy programming :)



Tuesday, 18 August 2015

Java program to find duplicate element between two arrayList




You can find common element between two arrays by two ways i.e. either you can use for loop and compare both the array elements or you can convert array into list and can use retainAll() method.

1) Using For Loop:-

/**  
  * @author Dixit  
  *  
  */  
 public class DuplicateElements {  
      public static void main(String a[]){  
     int[] arr1 = {1,2,3,4,5};  
     int[] arr2 = {4,8,9,7,2};  
     for(int i=0;i<arr1.length;i++){  
       for(int j=0;j<arr2.length;j++){  
         if(arr1[i]==arr2[j]){  
           System.out.println(arr1[i]);  
         }  
       }  
     }  
   }  
 }  

2) Using retainAll() method of List:-

 import java.util.ArrayList;  
 import java.util.Arrays;  
 import java.util.Collections;  
 import java.util.HashSet;  
 import java.util.List;  
 import java.util.Set;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class DuplicateElements {  
      public static void main(String a[]) {  
           int[] arr1 = { 1, 2, 3, 4, 5 };  
           int[] arr2 = { 4, 8, 9, 7, 2 };  
           List<Integer> list1 = new ArrayList<Integer>();  
           for (int index = 0; index < arr1.length; index++) {  
                list1.add(arr1[index]);  
           }  
           List<Integer> list2 = new ArrayList<Integer>();  
           for (int index = 0; index < arr2.length; index++) {  
                list2.add(arr2[index]);  
           }  
           list1.retainAll(list2);  
           System.out.println("CommonElements : " + list1);  
      }  
 }  




Enjoy programming :)


Generate Jasper report into different formats(xls,pdf,csv,odt,rtf,html)


                                Generate Jasper reports into different formats 


You can generate jasper report into different formats like excel sheets(xls),portable document format (pdf) ,comma separated values(csv),rich text format(rtf),hyper text mark up language(html),extensible markup language(xml), open document text(odt) etc.


In order to generate jasper report into specific format,you need to have JasperPrint object.You can make use of jasper report classes for each formats. for ex: to generate csv file ,you can make use of JRCsvExporter class.

1) Generate report in CSV format:-

 private static byte[] generateCsv(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRCsvExporter rtfExporter = new JRCsvExporter();  
    rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    rtfExporter.exportReport();  
    return baos.toByteArray();  
   }  

2) Generate report in PDF format:-

private static byte[] generatePDF(JasperPrint jasperPrint) throws JRException {  
    return JasperExportManager.exportReportToPdf(jasperPrint);  
   }  

3) Generate report in XLS format:-

private static byte[] generateXls(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRExporter xlsExporter = new JExcelApiExporter();  
    xlsExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    xlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    xlsExporter.exportReport();  
    return baos.toByteArray();  
   }  

4) Generate report in RTF format:-

private static byte[] generateRtf(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRRtfExporter rtfExporter = new JRRtfExporter();  
    rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    rtfExporter.exportReport();  
    return baos.toByteArray();  
   }  

5) Generate report in HTML format:-

private static byte[] generateHtml(JasperPrint jasperPrint, String reportName) throws JRException {  
  String HTML_REPOT_LOC = "/var/data/sched-ops/kpireports/htmlreport/";  
    JasperExportManager.exportReportToHtmlFile(jasperPrint, HTML_REPOT_LOC + reportName + ".html");  
    return null;  
   }  

6) Generate report in XML format:-

 private static byte[] generateXml(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRExporter xmlExporter = new JRXmlExporter();  
    xmlExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    xmlExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    xmlExporter.setParameter(JRXmlExporterParameter.IS_EMBEDDING_IMAGES, Boolean.TRUE);  
    xmlExporter.exportReport();  
    return baos.toByteArray();  
   }  

7) Generate report in ODT format:-

private static byte[] generateOdt(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRExporter odtExporter = new JROdtExporter();  
    odtExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    odtExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    odtExporter.exportReport();  
    return baos.toByteArray();  
   }  



Make sure you have imported Jasper Report jar into your workspace.

Enjoy programming. :)