Sunday 30 August 2015

Why POST method is non-idempotent and GET is idempotent ?




GET Method:-HTTP GET method is just for getting things from server.It is not supposed to change anything on server.So GET method is idempotent.It can be executed more than once without any side effects.
As you can see in below diagram,User request for a page and servlet sends back a response with a generated HTML page.You can call the same page again and again and server will return the response with no negative consequences that is called idempotent.





POST Method:-HTTP POST method is not idempotent i.e. the data submitted in the body of POST might be destined for transaction that can't be reversed.
As below diagram explains that when you submit your form ,POST method updates the data in database and servlet sends back an response.SO when you perform the submit action again,It will generate different response.





PUT,HEAD,DELETE methods are IDEMPOTENT just like GET method.

Enjoy Learning :)

Saturday 29 August 2015

Finally block and Its Usage



What is finally block ?


finally block is either written after catch block or try block.finally blocks always executes when try block exits.Even if unexpected exception occurs in try block ,finally block is executed.It must be immediately followed by try or catch block.

Example:


/**  
  * @author Dixit  
  *   
  */  
 public class FinallyTest {  
      public static void main(String a[]) {  
           try {  
                System.out.println("Try block");  
           } catch (Exception e) {  
                System.out.println("catch block.");  
           } finally {  
                System.out.println("finally block.");  
           }  
      }  
 }  


Output  
 Try block  
 finally block.

Usage of finally block

finally block is mostly used to execute important code like closing db connection,closing file resources etc.

Also read Important finally interview questions

Enjoy Learning :)

Important finally interview questions


Important finally block questions which are commonly asked in interviews.

1) Find the output of below program ?

try {  
                System.out.println("Try block");  
                System.exit(0);  
           } catch (Exception ex) {  
                ex.printStackTrace();  
           }  
           finally {  
                System.out.println("finally block!!!");  
           }  

Output  
 Try block 

Reason:-the program will not execute finally block in this case because program is terminated using
System.exit(0) statement.

2) Find the output of below program ?

try {  
                System.out.println("Try block");  
                System.out.println(10 / 0);  
                System.exit(1);  
           } catch (Exception ex) {  
                ex.printStackTrace();  
           }  
           finally {  
                System.out.println("Finally block!!!");  
           }  

Output  
 Try block  
 java.lang.ArithmeticException: / by zero  
      at FinallyTest.main(FinallyTest.java:16)  
 Finally block!!!  

Reason:- An arithmetic exception occurred before executing statement System.exit(1).

3) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(tryCatchMethod());  
      }  
      private static int tryCatchMethod() {  
           try {  
                return 1;  
           } finally {  
                System.out.println("finally block");  
           }  
      }  
 }  

 Output  
 finally block  
 1  

Reason:-finally block runs before method returns 1 .

4) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           try {  
                return 1;  
           } finally {  
                return 2;  
           }  
      }  
 }  

Output  
 2  

Reason:- return value in finally block ("2") overrides return value of try block ("1").

5) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           try {  
                throw new NumberFormatException();  
           } finally {  
                return 2;  
           }  
      }  
 }  

 Output  
 2  

Reason:-Exception thrown by try block is overridden by return statement in finally block.That is why no exception is thrown.So Its bad practice to use return statements in finally block.

6)

 public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           int i = 0;  
        try {  
          i = 1;  
          return i;  
        } finally {  
          i = 2;  
          System.out.println("finally block.");  
        }  
      }  
 }  

Output  
 finally block.  
 1  

Reason:- when return i is executed i has a value 1 after that i is assigned new value in finally block to 2 and program prints "finally block.". but here 1 is returned because return statement is not executed again.

Enjoy programming :)

Top 10 Important shortcut keys for Windows


Shortcut keys mainly improve our work efficiency by speeding up the work.

Very basic and important shortcut key that everyone must know are:-

1) ALT + Tab :- It allows you to shuffle around your open application windows.It is very useful key to easily switch to other application windows.

2) CTRL + SHIFT +Del :-It opens the window option screen for Task Manager,locking computer,witiching user etc in latest version of windows.In Windows XP,It is meant for opening task manager.
CTRL + SHIFT + Esc is used to open Windows Task manager in Wndows XP and later.

3) SHIFT + Del :-It will delete the selected files permanently without moving them to recycle bin.

4) F2 :- Instead of right clicking on file and selecting rename option,F2 function key allows you to rename file instantly.

5) WIN + D :-It will display the desktop irrespective of how many opened application .
Similarly WIN + M will minimize all the current opened application and will display desktop. 

6) WIN + L :- Lock the computer and switch users (Windows XP and above only). 

7) WIN + R :-Opens the run command dialog box.

8) CTRL + C :- It will copy the highlighted text or selected file.If you want to cut highlighted text or selected file,press CTRL + X.

9) CTRL + V or SHIFT + Insert :- Both the shortcut keys will paste the highlighted text or selected file.

10) CTRL + Z or CTRL + Y :- CTRL + Z will undo the recent changes which you have done and CTRL + Y will redo the recent undo changes.
Enjoy Learning.


10 useful windows run command every developer must know


To speed up the work in windows, run command are very useful.There are some useful run commands that every developer must know .

First to open run dialog box you can either go to Start- > run or press shortcut key win + R.
Type the following command in the dialog box and press ok button.

1) %temp% :- This command is very useful to delete temporary files which gets created when you work on you PC.This are unnecessary files so in order to speed up your PC or clear your PC memory,you should delete all the temporary files.Keep in habbit that every week you run this command and free your PC memory space.

2) write :-It opens a Microsoft wordpad where you can write your notes and etc.

3) psr:-Its stands for Problem Steps Recorder.You can use this to automatically capture the steps you take on a computer including a text description of where you clicked and a picture of the screen during each click.Once you are done saving the steps,you can help others to troubleshoot their PC problems.

4) cmd:- Its a very important command for developers.this command use to open command prompt.

5) notepad:-this command is used to open notepad.

6) taskmgr:- Its opens a task manager where you can monitor your running process.There is shortcut key for this command also.

7) services.msc:-It provides you with all the running service on your machine. you can enable or disable unnecessary service which will speed your system.Note you should not disable any service for which you don't have knowledge because it may interrupt your PC normal behavior.

8) calc:-It will open a calculator .

9) control:-This command will open control panel on your desktop.

10) mstsc:-Its is used to open Remote Desktop Connection dialog box.With the help of this command ,you can connect to another computer running windows that's connected to the same network or to the internet.For ex: you can access you work computer from you home computer and will be able to perform various tasks.

NOTE:-Try to bring in practice to use this commands while you are working.It will speed up your work activities.

Also read Top 10 Important shortcut keys for Windows

Thursday 27 August 2015

Convert Web browser into Notepad



In order to open temporary notepad into your web browser,you need to type 
data:text/html, <html.contenteditable> in the address bar of your web browser and you have temporary notepad.







Enjoy Learning :)

Daemon Thread


What is Daemon Threads ?

Daemon threads are those threads which perform some helper functions or provide services to non-daemon threads(user threads).When JVM starts up,it creates garbage collector thread or some housekeeping threads except main thread .this threads are called Daemon threads

Daemon threads runs in background to provide services to user threads.Daemon threads are low priority threads.When no user thread is running JVM terminates all the daemon threads .

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class TestDaemonThreads extends Thread {  
      public static void main(String[] args) {  
           TestDaemonThreads daemonThread = new TestDaemonThreads();  
           TestDaemonThreads normalThread = new TestDaemonThreads();  
           daemonThread.setDaemon(true);  
           daemonThread.start();  
           normalThread.start();  
      }  
      public void run() {  
           if (Thread.currentThread().isDaemon()) {  
                System.out.println("Daemon Thread");  
           } else {  
                System.out.println("Normal Thread");  
           }  
      }  
 }  



 Output:-  
 Daemon Thread  
 Normal Thread  

Use of Daemon Threads:-

Daemon threads performs housekeeping tasks such as removing unwanted entries from memory cache,releasing memory of unused objects etc.

Enjoy Learning.


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. :)

Wednesday 12 August 2015

Java Program to check whether open parenthesis is closed properly or not


              Java Program to check whether open parenthesis is closed properly or not

Many times we want to do a validation on some formula or some string where we need to check whether open parenthesis is closed properly or not.

for ex:- String strFormula=(1+2);

We are going to implement this using stack where we will push the '(' open parenthesis character as soon as it encounters and we will pop out as soon as we encounters closed parenthesis.


 import java.util.Stack;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class ValidateParenthesis {  
      public static void main(String args[]) {  
           String strFormulaCondition = "(1+2)";  
           boolean result = checkForparenthesis(strFormulaCondition);  
           System.out.println("Result:-" + result);  
           String strNewFormulaCondition = "((1+2)";  
           System.out.println("Result:-"  
                     + checkForparenthesis(strNewFormulaCondition));  
      }  
      /**  
       * It checks whether open parenthesis is closed properly or not in report  
       * formula notation  
       *   
       * @param strReportFormula  
       */  
      public static boolean checkForparenthesis(String strReportFormula) {  
           Stack<Integer> stk = new Stack<Integer>();  
           for (int i = 0; i < strReportFormula.length(); i++) {  
                char ch = strReportFormula.charAt(i);  
                if (ch == '(')  
                     stk.push(i);  
                else if (ch == ')') {  
                     try {  
                          int p = stk.pop() + 1;  
                     } catch (Exception e) {  
                     }  
                }  
           }  
           if (!stk.isEmpty()) {  
                return false;  
           } else {  
                return true;  
           }  
      }  
 }  


Enjoy programming:)



Sunday 9 August 2015

Java program to Swap Two Numbers



There are different ways with which you can implement this program.Its very common question asked in interviews about swapping of two numbers so you must know all the way to do this program.

Here is the implementation below:


 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class SwapNumbers {  
      public static void main(String args[]) {  
           int a = 10;  
           int b = 20;  
           swapNumbersUsingTemporaryVariable(a, b);  
           swapNumbersWithoutUsingTemporaryVariable(a, b);  
           swapNumbersUsingXOROperator(a, b);  
           swapNumbersUsingMuliplicationAndDivisionOperator(a, b);  
      }  
      private static void swapNumbersUsingMuliplicationAndDivisionOperator(int a,  
                int b) {  
           System.out.println("***swapNumbersUsingMuliplicationAndDivisionOperator***\n");  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           b = a * b;  
           a = b / a;  
           b = b / a;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
      private static void swapNumbersUsingXOROperator(int a, int b) {  
           System.out.println("\n***swapNumbersUsingXOROperator***\n");  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           a = a ^ b;  
           b = a ^ b;  
           a = a ^ b;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
      private static void swapNumbersWithoutUsingTemporaryVariable(int a, int b) {  
           System.out.println("\n***swapNumbersWithoutUsingTemporaryVariable***\n");  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           a = a + b;  
           b = a - b;  
           a = a - b;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
      private static void swapNumbersUsingTemporaryVariable(int a, int b) {  
           System.out.println("\n***swapNumbersUsingTemporaryVariable***\n");  
           int temp;  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           temp = a;  
           a = b;  
           b = temp;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
 }  


Enjoy Coding. :)

Saturday 8 August 2015

Jasper Report Chart Customizer class


                                      Jasper Report Chart Customizer class


Jasper Report Chart Customizer class:-Chart customizer class are nothing but java classes that can be used to modify or change the appearance of your  jasper report chart.For ex: you can change style of your line from solid to dashed,change the color of line from black to yellow,white etc.

Here is the sample implementation of customizer class,I have used XY plot series graph where I have to display lines of different color and different style of line of each data.

For implementation you need to extend class JRAbstractChartCustomizer.This class contains customize method which accepts JFreeChart and JRChart as arguments.Inside customize method you can customize your graph according to the way you want.

 import java.awt.BasicStroke;  
 import java.awt.Color;  
 import java.awt.Shape;  
 import java.awt.Stroke;  
 import java.awt.geom.Ellipse2D;  
 import java.util.ArrayList;  
 import java.util.HashSet;  
 import java.util.List;  
 import java.util.Set;  
 import net.sf.jasperreports.engine.JRAbstractChartCustomizer;  
 import net.sf.jasperreports.engine.JRChart;  
 import org.jfree.chart.JFreeChart;  
 import org.jfree.chart.plot.XYPlot;  
 import org.jfree.chart.renderer.xy.XYItemRenderer;  
 import org.jfree.data.xy.XYDataset;  
 public class KPIChartCustomizer extends JRAbstractChartCustomizer {  
      // different styles of line strokes  
      Stroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,  
                BasicStroke.JOIN_MITER, 10.0f, new float[] { 10.0f }, 0.0f);  
      Stroke dotted = new BasicStroke(1f, BasicStroke.CAP_ROUND,  
                BasicStroke.JOIN_ROUND, 1f, new float[] { 2f }, 0f);  
      Stroke solid = new BasicStroke(1.7f);  
      Stroke medium = new BasicStroke(1f);  
      Stroke thin = new BasicStroke(0.4f);  
      Stroke solidDashedWithCapButt = new BasicStroke(1.5f, BasicStroke.CAP_BUTT,  
                BasicStroke.JOIN_MITER, 10.0f, new float[] { 10.0f }, 0.0f);  
      Stroke solidDashedWithCapSquare = new BasicStroke(1.5f,  
                BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f,  
                new float[] { 10.0f }, 0.0f);  
      float[] dash2 = { 1f, 1f, 1f };  
      float[] dash4 = { 4f, 4f, 1f };  
      Stroke smallDots = new BasicStroke(1, BasicStroke.CAP_BUTT,  
                BasicStroke.JOIN_ROUND, 1.0f, dash2, 2f);  
      Stroke dashedAndDots = new BasicStroke(1, BasicStroke.CAP_BUTT,  
                BasicStroke.JOIN_ROUND, 1.0f, dash4, 2f);  
      Stroke[] basicStrokeArr = { solid, dashed, dotted, smallDots, medium,  
                dashedAndDots, thin };  
      @Override  
      public void customize(JFreeChart freeChart, JRChart jrChart) {  
           XYPlot plot = (XYPlot) freeChart.getPlot();  
           XYItemRenderer renderer = plot.getRenderer();  
           int seriesCount = plot.getSeriesCount();  
           XYDataset dataSet = plot.getDataset();  
           Set<String> nameStr = new HashSet<String>();  
           Set<String> reportTypeStr = new HashSet<String>();  
           boolean oneKpiAndMultipleAPFlag = false;  
           List<Color> listOfColors = new ArrayList<Color>();  
           String[] dnNames = new String[nameStr.size()];  
           nameStr.toArray(dnNames);  
           String[] reportTypes = new String[reportTypeStr.size()];  
           reportTypeStr.toArray(reportTypes);  
           for (int i = 0; i < seriesCount; i++) {  
                String name = (String) dataSet.getSeriesKey(i);  
                Color seriesColor = getColor(name, reportTypes);  
                renderer.setSeriesPaint(i, seriesColor);  
                Stroke lineStroke = getLineStroke(name, dnNames);  
                renderer.setSeriesStroke(i, lineStroke);  
                Shape shape = new Ellipse2D.Double(-0.75, -0.75, 2, 2);  
                renderer.setSeriesShape(i, shape);  
           }  
      }  
      /**  
       * return type of line stroke .  
       *   
       * @param name  
       * @param reportTypes  
       * @return  
       */  
      private Stroke getLineStroke(String name, String[] reportTypes) {  
           Stroke lineStroke = null;  
           if (name.contains(reportTypes[0])) {  
                // colour yellow  
                lineStroke = basicStrokeArr[0];  
           } else if (name.contains(reportTypes[1])) {  
                // colour yellow  
                lineStroke = basicStrokeArr[1];  
           } else if (name.contains(reportTypes[2])) {  
                // colour yellow  
                lineStroke = basicStrokeArr[2];  
           } else if (name.contains(reportTypes[3])) {  
                // colour yellow  
                lineStroke = basicStrokeArr[3];  
           } else if (name.contains(reportTypes[4])) {  
                // colour yellow  
                lineStroke = basicStrokeArr[4];  
           } else if (name.contains(reportTypes[5])) {  
                // colour yellow  
                lineStroke = basicStrokeArr[5];  
           } else if (name.contains(reportTypes[6])) {  
                // colour yellow  
                lineStroke = basicStrokeArr[6];  
           }  
           return lineStroke;  
      }  
      private Color getColor(String name, String[] dnNames) {  
           Color seriesColor = null;  
           if (name.contains(dnNames[0])) {  
                // colour blue  
                seriesColor = Color.BLUE;  
           } else if (name.contains(dnNames[1])) {  
                // colour Red  
                seriesColor = Color.RED;  
           } else if (name.contains(dnNames[2])) {  
                // colour green  
                seriesColor = Color.GREEN;  
           } else if (name.contains(dnNames[3])) {  
                // colour magenta  
                seriesColor = Color.MAGENTA;  
           } else if (name.contains(dnNames[4])) {  
                // colour black  
                seriesColor = Color.BLACK;  
           } else if (name.contains(dnNames[5])) {  
                // colour cyan  
                seriesColor = Color.CYAN;  
           } else if (name.contains(dnNames[6])) {  
                // colour light gray  
                seriesColor = Color.LIGHT_GRAY;  
           } else if (name.contains(dnNames[7])) {  
                // colour yellow  
                seriesColor = Color.YELLOW;  
           } else if (name.contains(dnNames[8])) {  
                // colour pink  
                seriesColor = Color.PINK;  
           }  
           return seriesColor;  
      }  
 }  

In order to use customizer class,You need to mention customizer class in your jrxml file also.

For example :

<summary>  
           <band height="443">  
                <timeSeriesChart>  
                     <chart isShowLegend="true" customizerClass="com.ipaccess.nos.business.pm.impl.KPIChartCustomizer">  
                          <reportElement mode="Opaque" x="0" y="0" width="766" height="443" isPrintInFirstWholeBand="true"/>  
                          <chartTitle position="Top">  
                               <font size="14" isBold="true" pdfFontName="Courier-Bold" isPdfEmbedded="true"/>  
                               <titleExpression><![CDATA[$P{REPORT_NAME}]]></titleExpression>  
                          </chartTitle>  
                          <chartSubtitle/>  
                          <chartLegend position="Bottom">  
                               <font size="8"/>  
                          </chartLegend>  
                     </chart>  
           </band>  
      </summary>  





Enjoy reading :)

Error : “The user specified as a definer does not exist” when importing mysqldump


                      Change the Definer of Mysql Stored Procedures

Sometimes when we try to import mysqldump into our local machine through command line terminal,we end up getting following error

mysqldump: Got error: 1449: The user specified as a definer ('user@%') does not exist when using LOCK TABLES

This error comes because the database we are trying to import contains procedures and functions that are defined by the user 'user'.

You can monitor your procedure characteristics like database name,type,creator,creation time and character set information by using this command:

         SHOW procedure status;

after executing this command, you can see some procedures creator name is ('user@%').

So you need to change it to 'root@%' or 'root'@'localhost',you should update definer for procedures using this command in Mysql terminal,

         UPDATE 'mysql'.'proc' p SET definer='root@%' WHERE definer='user@%';

keep in mind one thing this command will update definer for all procedures.

Other way to achieve this is create user name 'user' in your database and grant all permission to it.

        GRANT all on *.* to 'user@%' identified by 'password' with grant option;

You can also view grants on any user using this command,

        SHOW GRANTS for 'user@%';




I hope this solution helps you.Enjoy coding :)


Saturday 1 August 2015

Convert Collection into Comma Separated String


                            Convert Collection into Comma Separated String

while coding some module ,there comes a scenario where you need to convert your collection into comma separated string.
Suppose for example you need to pass list of strings to Stored procedure but your procedure argument accepts only varchar value.
in that case you need to convert your list of strings into comma separeted strings.


Below are some ways which you can implement.

1) Iterate over list elements,Concatenate each of the list elements and comma until last element  

 package com.ipaccess.nos.gui.module.config.wizard.changeProductClass;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class ListToString {  
   public static void main(String[] args) {  
    //Supoose this is your list containing integer {1,2,3,4}  
    List<Integer> numbers = new ArrayList<Integer>();  
    numbers.add(1);  
    numbers.add(2);  
    numbers.add(3);  
    numbers.add(4);  
    //StringBuilder to store comma separated string    
    StringBuilder commaSepString = new StringBuilder();  
    // iterate over list,append numbers and comma until last element    
    for (int i = 0; i < numbers.size(); i++) {  
      commaSepString.append(numbers.get(i));  
      if (i != numbers.size() - 1) {  
       commaSepString.append(", ");  
      }  
    }  
    System.out.println(commaSepString.toString());  
   }  
 }  


2) you can make use of google-collections.jar which has a utility class called Joiner

    String commaSepString=Joiner.on(",").join(numbers);
  
  To download this jar ,you can use this link 
http://www.java2s.com/Code/Jar/g/Downloadgooglecollections10jar.htm

3) Another way is you can use StringUtils class which has function called join.To make use of StringUtils class,you need to use common-lang3.jar

    String commaSepString=StringUtils.join(slist, ',');
  To download this jar ,you can use this link 
http://www.java2s.com/Code/Jar/c/Downloadcommonlang3jar.htm



Enjoy Learning.:)