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