Sunday 11 October 2020

Create Builder Design Pattern in Java

Builder Design Pattern in Java

The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.


The builder pattern, as name implies, is an alternative way to construct complex objects. This should be used only when you want to build different immutable objects using same object building process.



package com.vehicle;


public class Car {

private final String carCompany;

private final String name;

private final String model;

private final String colour;

private final String engine;

private Car(Builder builder) {

this.carCompany=builder.carCompany;

this.name=builder.name;

this.model=builder.model;

this.colour=builder.colour;

this.engine=builder.engine;

}

//All getter, and NO setter to provde immutability in Car

public String getName() {

return this.name;

}

public String getModel() {

return this.model;

}

public String getColour() {

return this.colour;

}

public String getEngine() {

return this.engine;

}

public static class Builder{

   

private final String carCompany;

private String name;

private String model;

private String colour;

private String engine;

public Builder(String carCompany){

this.carCompany = carCompany;

}

public Builder setName(String name) {

this.name=name;

return this;

}

public Builder setModel(String model) {

this.model=model;

return this;

}

public Builder setColour(String colour) {

this.colour=colour;

return this;

}

public Builder setEngine(String engine) {

this.engine=engine;

return this;

}

public Car build() {

return new Car(this);

}

}

@Override

public String toString() {

return "Builder [carCompany=" + carCompany + ", name=" + name + ", model=" + model + ", colour=" + colour+ ", engine=" + engine + "]";

}

}


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


package com.vehicle;


public class Main {


public static void main(String[] args) {


Car car1 = new Car.Builder("Maruti").setName("Alto").setEngine("900CC").setModel("k10Vxi").build();

Car car2 = new Car.Builder("Ford").setName("Escort").setEngine("1600CC").setModel("MK2").build();

System.out.println(car1);

System.out.println(car2);

}


}





Tuesday 6 October 2020

Use of Comparable and Comparator class for sorting ArrayList Objects


Use of Comparable class for sorting ArrayList Objects


package com.test;


import java.util.ArrayList;

import java.util.Collections;

import java.util.List;


class Employee implements  Comparable{

private Integer rollNo;

private String name;

private Integer age;


public Employee(Integer rollNo, String name, Integer age) {

super();

this.rollNo = rollNo;

this.name = name;

this.age = age;

}


@Override

public String toString() {

return "Employee [rollNo=" + rollNo + ", name=" + name + ", age=" + age + "]\n";

}


@Override

public int compareTo(Object o) {  

Employee e = (Employee) o;

return this.rollNo.compareTo(e.rollNo);

}

}


public class Demo {


public static void main(String[] args) {

Employee emp = null;

    List<Employee> list = new ArrayList<Employee>();

    list.add( emp = new Employee(101, "Cheten", 36));

    list.add( emp = new Employee(603, "Brijesh", 29));

    list.add( emp = new Employee(308, "Ajay", 38));

    list.add( emp = new Employee(902, "Mansi", 26));

    list.add( emp = new Employee(327, "sunil", 40));

    list.add( emp = new Employee(206, "Aman", 32));

    list.add( emp = new Employee(490, "vimal", 25));

    Collections.sort(list);

    System.out.println(list);

    

}

}








Use of Comparator class for sorting ArrayList Objects

package com.test;


import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;


class Employee{

public Integer rollNo;

public String name;

public Integer age;


public Employee(Integer rollNo, String name, Integer age) {

super();

this.rollNo = rollNo;

this.name = name;

this.age = age;

}


@Override

public String toString() {

return "Employee [rollNo=" + rollNo + ", name=" + name + ", age=" + age + "]\n";

}

}


public class Demo {


public static void main(String[] args) {

Employee emp = null;

    List<Employee> list = new ArrayList<Employee>();

    list.add( emp = new Employee(101, "Cheten", 36));

    list.add( emp = new Employee(603, "Brijesh", 29));

    list.add( emp = new Employee(308, "Ajay", 38));

    list.add( emp = new Employee(902, "Mansi", 26));

    list.add( emp = new Employee(327, "sunil", 40));

    list.add( emp = new Employee(206, "Aman", 32));

    list.add( emp = new Employee(490, "vimal", 25));

    

  

    Comparator<Employee> com = new Comparator<Employee>() {

@Override

public int compare(Employee o1, Employee o2) {

if(o1.rollNo > o2.rollNo)

return 1;

return -1;

}

    };


    System.out.println("Before sorting by rollNo : \n"+list);

    Collections.sort(list,com);

    System.out.println("After sorting by rollNo : \n"+list);

    

}

}








Tuesday 5 February 2019

Download HTML Table data into Excel file using javascript




<script>
function exportTableToExcel(tableID){
    var downloadLink;
var  filename = '';
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    
    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';
    
    // Create download link element
    downloadLink = document.createElement("a");
    
    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
    
        // Setting the file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
    }
}
</script>

<html>
<table id="dataTableID" Border="1px">
    <tr>
    <th>From</th>
        <th>To</th>
        <th>Name</th>
        <th>Email</th>
        <th>City</th>
    </tr>
    <tr>
    <td>Agra</td>
        <td>New Delhi</td>
        <td>Aman Kumar</td>
        <td>aman@gmail.com</td>
        <td>UP</td>
    </tr>
    <tr>
    <td>Mussoorie</td>
        <td>Haridwar</td>
        <td>Suraj</td>
        <td>Suraj@gmail.com</td>
        <td>UK</td>
    </tr>
    <tr>
    <td>Jammu</td>
        <td>Ghaziabad</td>
        <td>Ajay Sharma</td>
        <td>Ajay@gmail.com</td>
        <td>MP</td>
    </tr>
<tr>
    <td>Kanpur</td>
        <td>Allahabad</td>
        <td>Rahul Singh</td>
        <td>sam@gmail.com</td>
        <td>MP</td>
    </tr>
</table>
<br/>
<button onclick="exportTableToExcel('dataTableID')">Download Excel File</button>
</html>

Thursday 11 October 2018

How to decode JSON without create pojo in java


import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;

/****  
   How to decode Json  
   JSON >> [0,{"signedPdfBase64":"JVBERi0xLjUKJeLjz9M=="}]
*****/
public class JsonDecode {
  public static void main(String[] args){

  JSONParser parser = new JSONParser();
  String jsonMaked = "[0,{\"signedPdfBase64\":\"JVBERi0xLjUKJeLjz9M==\"}]";
  System.out.println("****** JSON is *******");
      System.out.println(jsonMaked);
      try{
         Object obj1 = parser.parse(jsonMaked);
         JSONArray array = (JSONArray)obj1;
         System.out.println("\n******** Get 2nd element of array *******");
         System.out.println(array.get(1));
         
         JSONObject obj2 = (JSONObject)array.get(1);
         System.out.println("\n******** After decode JSON is *********");
         System.out.println(obj2.get("signedPdfBase64")); 
         
      }catch(ParseException pe){
         System.out.println("position: " + pe.getPosition());
         System.out.println(pe);
      }
   }
}


Friday 31 August 2018

How to create a table with add and remove rows functionality using Jquery









<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="keywords" content="How to create a table with add and remove rows functionality using Jquery">
<style>
@font-face{font-family: Lobster;src: url('Lobster.otf');}
h1{font-family: Lobster;text-align:center;}
table{border-collapse:collapse;border-radius:25px;width:800px;}
table, td, th{border:1px solid #CCC;}
tr,input{height:25px;border:1px solid #fff;}
input{text-align:center;}
input:focus{border:1px solid blue;} 
.space{margin-bottom: 1px;}
#container{margin-left:110px;}
.but{width:100px;background:#0088CC;border:1px solid #00BB64;height:40px;border-radius:3px;color:white;margin-top:5px;margin:0px 0px 0px 200px;}
</style>
<script src='jquery.min.js'></script>
</head>
<body>
<h1>Purchase Order</h1>
<div id='container'>

<form id='students' method='post' name='students' action=''>

<table border="1" cellspacing="0">
  <tr>
    <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
    <th>PO #</th>
    <th>PO Date</th>
    <th>PO Duration Start Date</th>
    <th>PO Duration End Date</th>
    <th>PO TERM</th>
    <th>PO Amount</th>
    <th>Remarks</th>
<th>Upload PO</th>
  </tr>
  <tr>
    <td><input type='checkbox' class='case'/></td>
    <td><span id='snum'>1.</span></td>
    <td><input type='text' id='po_date' name='po_date[]'/></td>
    <td><input type='text' id='po_ duration_start_date' name='po_ duration_start_date[]'/></td>
    <td><input type='text' id='po_duration_end_date' name='po_duration_end_date[]'/></td>
    <td><input type='text' id='po_term' name='po_term[]'/> </td>
    <td><input type='text' id='po_amount' name='po_amount[]'/></td>
    <td><input type='text' id='remarks_po' name='remarks_po[]'/> </td>
<td><input type='file' id='upload_po' name='upload_po[]'/> </td>
  </tr>
</table>

<button type="button" class='delete'>- Delete</button>
<button type="button" class='addmore'>+ Add More</button>

<button type='button' name='submit' value='Submit' >submit </button>
</form>

<div class="clearfix"></div>
<br/>


</div>
<script>
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
    $('.check_all').prop("checked", false); 
check();

});
var i=2;
$(".addmore").on('click',function(){
count=$('table tr').length;
    var data="<tr><td><input type='checkbox' class='case'/></td><td><span id='snum"+i+"'>"+count+".</span></td>";
    data +="<td><input type='text' id='po_date"+i+"' name='po_date[]'/></td> <td><input type='text' id='po_ duration_start_date"+i+"' name='po_ duration_start_date[]'/></td><td><input type='text' id='po_duration_end_date"+i+"' name='po_duration_end_date[]'/></td><td><input type='text' id='po_term"+i+"' name='po_term[]'/></td><td><input type='text' id='po_amount"+i+"' name='po_amount[]'/></td><td><input type='text' id='remarks_po"+i+"' name='remarks_po[]'/></td><td><input type='file' id='upload_po"+i+"' name='upload_po[]'/></td></tr>";
$('table').append(data);
i++;
});

function select_all() {
$('input[class=case]:checkbox').each(function(){ 
if($('input[class=check_all]:checkbox:checked').length == 0){ 
$(this).prop("checked", false); 
} else {
$(this).prop("checked", true); 
});
}

function check(){
obj=$('table tr').find('span');
$.each( obj, function( key, value ) {
$('#'+id).html(key+1);
});
}

</script>


</body>
</html>


Monday 20 November 2017

Parse and write JSON data in Java with Gson

Here i am showing you full examples of using following Gson streaming APIs to read and write JSON data.

As a pre-requisite, you are required to download the gson-2.1.jar




Create A GetJson.java class as bellow.


public class GetJson {
   public static void main(String args[]){
   GetJson  obj= new GetJson(); 
   obj.getJsonData();
   } 
   public void getJsonData(){
   
   //[{amount":9283.41,"balanceAfterTransaction":9283.41,"bank":"Bank_0160021000998","category":"OPENING_BALANCE","dateTime":"01/05/2017","description":"OPENING BALANCE","remark":null,"transactionNumber":null,"type":"CREDIT","valueDate":null},{"amount":100000.0,"balanceAfterTransaction":109283.41,"bank":"Bank_01698210009909","category":"OTHER","dateTime":"01/05/2017","description":" BY INST 51 : CTO12- 1 DAY LAT","remark":null,"transactionNumber":"KZT2","type":"CREDIT","valueDate":null}]    
   String inputLine = "[{amount\":9283.41,\"balanceAfterTransaction\":9283.41,\"bank\":\"Bank_0160021000998\",\"category\":\"OPENING_BALANCE\",\"dateTime\":\"01/05/2017\",\"description\":\"OPENING BALANCE\",\"remark\":null,\"transactionNumber\":\"trx009\",\"type\":\"CREDIT\",\"valueDate\":null},{\"amount\":100000.0,\"balanceAfterTransaction\":109283.41,\"bank\":\"Bank_01698210009909\",\"category\":\"OTHER\",\"dateTime\":\"01/05/2017\",\"description\":\" BY INST 51 : CTO12- 1 DAY LAT\",\"remark\":null,\"transactionNumber\":\"KZT2\",\"type\":\"CREDIT\",\"valueDate\":null}]";    
   String jsonData = "{\"bankTransactionList\":"+inputLine+"}";
   int sizeList =0;
    String amount =null;
String balanceAfterTransaction =null;
String bank =null;
String category = null;
String dateTime = null;
String description = null;
String remark = null;
String transactionNumber = null;
String type = null;
String valueDate = null;
   try{
   Gson gson = new Gson();
   BankArrayList myData = gson.fromJson(jsonData, BankArrayList.class);
   System.out.println("myDataList size >> "+myData.bankTransactionList.size());
   sizeList = myData.bankTransactionList.size();
   for(int i=0;i<sizeList;i++){
   System.out.println("Amount >> "+ myData.bankTransactionList.get(i).amount);
   System.out.println("balanceAfterTransaction >> "+ myData.bankTransactionList.get(i).balanceAfterTransaction);
   System.out.println("bank >> "+ myData.bankTransactionList.get(i).bank);
   System.out.println("dateTime >> "+ myData.bankTransactionList.get(i).dateTime);
   System.out.println("description >> "+ myData.bankTransactionList.get(i).description);
   System.out.println("transactionNumber >> "+ myData.bankTransactionList.get(i).transactionNumber);
   System.out.println("type >> "+ myData.bankTransactionList.get(i).type);
   System.out.println("valueDate >> "+ myData.bankTransactionList.get(i).valueDate);
   System.out.println("--------------------------------------------------------");
   
   }
   
   }catch(Exception ex){
  ex.printStackTrace(); 
   }
   }

}


Create A Bank.java class as bellow.

public class Bank {
public String amount;
public String balanceAfterTransaction;
public String bank;
public String category;
public String dateTime;
public String description;
public String remark;
public String transactionNumber;
public String type;
public String valueDate;
}


Create A BankArrayList.java class as bellow.

public class BankArrayList {
public ArrayList<Bank> bankTransactionList = new ArrayList <Bank>();

}

After run GetJson.java file, Result will be display as bellow image