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






Friday 7 July 2017

Login with Google via OAuth Service


Google is providing OAuth Service. You can implement Google Login on your website so that user doesn't need to remember another password for your website. You will also get worthy email addresses to connect with users.

Here i will show you, how to implement OAuth Service in your web Application.

OAuth 2.0 Flow

1)  User will click on Auth login link
2.) Google Auth server will show permission screen to user
3.) Once user accepts to the scope, It will send code to App Server ( Redirect URI)
4.) Once we got code, get access token by using client secret id
5.) Access User's Information using that access token 

Get OAuth 2.0  Credentials from Google developer console 

1.) Go to Google Developer Console https://console.developers.google.com
2.) Create Project and Open that project
3.) Go to API & Auth > Credentials > Create New Client ID 





Login With Google plus JavaScript example code

Below code save as index.jsp  page and run this jsp on web server.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Login with Google Account</title>
<script src="jquery.min.js"></script>
<script src="jquery-1.8.0.js"></script>
<script>
function onSuccess(googleUser) {
var profile = googleUser.getBasicProfile();
gapi.client.load('plus', 'v1', function () {
    var request = gapi.client.plus.people.get({
        'userId': 'me'
    });
    //Display the user details
    request.execute(function (resp) {
        var profileHTML = '<div class="profile"><div class="head">Welcome '+resp.name.givenName+'! <a href="javascript:void(0);" onclick="signOut();">Sign out</a></div>';
        profileHTML += '<img src="'+resp.image.url+'"/>';
        profileHTML += '<div class="proDetails"><p>'+resp.displayName+'</p>';
        profileHTML += '<p>'+resp.emails[0].value+'</p>';
        profileHTML += '<p>'+resp.gender+'</p>';
        profileHTML += '<p>'+resp.id+'</p>';
        profileHTML += '<p><a href="'+resp.url+'">View Google+ Profile</a></p></div></div>';
        //alert(profileHTML);
        $('.userContent').html(profileHTML);
        $('#gSignIn').slideUp('slow');
    });
});
}
 function onFailure(error) {
  alert(error);
 }
function renderButton() {
gapi.signin2.render('gSignIn', {
    'scope': 'profile email',
    'width': 200,
    'height': 40,
    'longtitle': true,
    'theme': 'dark',
    'onsuccess': onSuccess,
    'onfailure': onFailure
});
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
    $('.userContent').html('');
    $('#gSignIn').slideDown('slow');
});
}
</script>
</head>
<body>
<div id="gSignIn"></div>
<div class="userContent"></div>
<div class="divid">  </div>
</body>
</html>










Friday 23 June 2017

How to convert Base64 code to file, and download it.





   <script type="text/javascript" src="jquery.js"></script>
 
 <script>
  function getImageDownload() {
 
debugger;
var filename ="download";
var contentType = "pdf"
var v = [];
v.push($('#gstNoProofBlob').val());
v[0] = v[0].replace(/\@/gi, '+');
//alert(v[0]);
var link = document.createElement("a");
var dName=filename+"."+contentType;
link.download = (dName);
link.href = "data:image/pdf;base64," + v[0];
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
 }
 </script>

 <textarea rows="10" cols="50" id="gstNoProofBlob" name="gstNoProofBlob"> </textarea><br/><br/>    <input type="button" value="Download File" onclick="getImageDownload()" />






Wednesday 5 April 2017

Convert digits into words with JavaScript



<script>

function AmountWithCommas(x) {
                var currencyId = '${currencyId}';
                if (x != "") {
                    var y = x.replace(/,/g, '');
                    y = y.toString();
                    var afterPoint = '';
                    if (y.indexOf('.') > 0)
                        afterPoint = y.substring(y.indexOf('.'), y.length);
                    y = Math.floor(y);
                    y = y.toString();
                    var lastThree = y.substring(y.length - 3);
                    var otherNumbers = y.substring(0, y.length - 3);
                    if (otherNumbers != '')
                        lastThree = ',' + lastThree;
                    var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
                    document.getElementById("auctionAmount").value = res;
                    var z = x.replace(/,/g, '');
                    document.getElementById("amountValue").value = z;
                    //alert(z);
                    if (currencyId == 1) {
                        onAuctionAmount(z);
                    } else if (currencyId == 2) {
                        GetNumber2(z)
                    } else {
                        onAuctionAmount(z)
                    }

                }
                if (document.getElementById("invoiceExcludingRatio").value != "") {
                    onInvoiceOnloadExcludingRatioWord();
                }
            }
            var a = ['', 'ONE ', 'TWO ', 'THREE ', 'FOUR ', 'FIVE ', 'SIX ', 'SEVEN ', 'EIGHT ', 'NINE ', 'TEN ', 'ELEVEN ', 'TWELVE ', 'THIRTEEN ', 'FOURTEEN ', 'FIFTEEN ', 'SIXTEEN ', 'SEVENTEEN ', 'EIGHTEEN ', 'NINETEEN '];
            var b = ['', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'];
            function onAuctionAmount(num) {
                //alert(num);
                //                                alert(num);
                var a = ['', 'ONE ', 'TWO ', 'THREE ', 'FOUR ', 'FIVE ', 'SIX ', 'SEVEN ', 'EIGHT ', 'NINE ', 'TEN ', 'ELEVEN ', 'TWELVE ', 'THIRTEEN ', 'FOURTEEN ', 'FIFTEEN ', 'SIXTEEN ', 'SEVENTEEN ', 'EIGHTEEN ', 'NINETEEN '];
                var b = ['', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'];
                var val = num.split(".");
                num = val[0];
                //                alert(num.toString().length);
                if ((num = num.toString()).length > 10)
                    return 'overflow';
                n = ('00000000000' + num).substr(-11).match(/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
                if (!n)
                    return;
                var str = '';
                str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + ' HUNDRED CRORE ' : '';
                str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + ' CRORE ' : '';
                str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + ' LAKH ' : '';
                str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + ' THOUSAND ' : '';
                str += (n[5] != 0) ? (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + ' HUNDRED ' : '';
                str += (n[6] != 0) ? ((str != '') ? 'AND ' : '') + (a[Number(n[6])] || b[n[6][0]] + ' ' + a[n[6][1]]) + '' : '';
                //alert(str);
                document.getElementById("auctionAmountWord").innerHTML = str;
            }
function onInvoiceOnloadExcludingRatioWord() {
                var x = document.getElementById("invoiceExcludingRatio").value;
                var temp = x.replace(/%/, '');
                var s = (document.getElementById("amountValue").value / 100) * temp;
                //alert("s ==="+s)
                document.getElementById("invoiceExcludingAmount").value = s.toFixed(2);
                document.getElementById("invoiceExcludingAmounts").innerHTML = s.toFixed(2);
            }
function auctionAmountChange() {
                var invoiceExcludingRatio = document.getElementById("invoiceExcludingRatio").value;
                $('#interestTotalEventAmount').html(interestLevelComma($('#auctionAmount').val()));
                //                alert("Arul Here == "+invoiceExcludingRatio.replace(/%/g , ""));
                invoiceExcludingRatio = invoiceExcludingRatio.replace(/%/g, "");
                if (invoiceExcludingRatio > 0) {
                    onInvoiceExcludingRatioWord();
                }
            }
function auctionProfileValue() {
                if (document.getElementById("amountValue").value != "") {
                    //  var y = ((parseFloat(document.getElementById("selectedInvoicesValue").value) / parseFloat(document.getElementById("amountValue").value))) * 100;
                    if (document.getElementById("selectedBoardedInvoicesValue").value == 0) {
                        var y = 0;
                    } else {
                        var y = (parseFloat(1) - ((parseFloat(document.getElementById("amountValue").value)) / parseFloat(document.getElementById("selectedBoardedInvoicesValue").value))) * 100;
                    }
                    if (y < 0) {
                        y = 0;
                    }
                    var p = parseInt(y);
                    //                    alert(p);
                    document.getElementById("progressval").innerHTML = p;
                    document.getElementById("auctionProfile").value = p;
                    //                    alert(p);
                    progress_bar('progressbar');
                } else {
                    //                    var y = (parseFloat(1)) * 100;
                    var y = 0;
                    if (y < 0) {
                        y = 0;
                    }
                    var p = parseInt(y);
                    document.getElementById("progressval").innerHTML = p;
                    document.getElementById("auctionProfile").value = p;
                    progress_bar('progressbar');
                    //alert(p);
                }

            }
</script>
  <input type="text" value="" id="auctionAmount" name="auctionAmount" onKeyUp="AmountWithCommas(this.value);" onblur="auctionProfileValue(); auctionAmountChange();" />
  <strong class="font12" id="auctionAmountWord" ></strong>
  <input  id="amountValue" name="amountValue" type="hidden" value="" />


Wednesday 22 February 2017

How to upload files on Amazon s3 AWS in java

package awss3app;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.ClientConfiguration;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

public class S3Sample {
    private static String bucketName     = "purgecoveringletter"; 
    private static String keyId   = "ASASASXIQBFDERREWWW";
    private static String keyName = "wew23434cb/0KBRvubU+vqwqqw223";
    //private static String END_POINT_URL = "http://s3-ap-southeast-1.amazonaws.com";
    private static String END_POINT_URL = "http://s3.amazonaws.com";
    private static String S3_CACHE="60";
    static String fileName = "images.jpg";

    public static void main(String[] args) throws IOException {
    AWSCredentials credentials = new BasicAWSCredentials(keyId,keyName);
    java.security.Security.setProperty("networkaddress.cache.ttl", S3_CACHE);
    AmazonS3 s3Client = new AmazonS3Client(credentials);
    Region southEast1 = Region.getRegion(Regions.AP_SOUTHEAST_1);
    //Region res = Region.getRegion(Regions. "ap-south-1");
    s3Client.setRegion(southEast1);
    s3Client.setEndpoint(END_POINT_URL);
    
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    clientConfiguration.setSignerOverride("AWSS3V4SignerType");

    //s3Client.setEndpoint("http://s3.amazonaws.com");
    try {
        System.out.println("Uploading a new object to S3 from a file\n");
        //File file = new File(uploadFileName);
        // Upload file
        //s3Client.putObject(new PutObjectRequest(bucketName, keyName, file));
        s3Client.putObject(new PutObjectRequest(bucketName, fileName,new File("G:\\images.jpg")));

        GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, keyName);
        S3Object objectPortion = s3Client.getObject(rangeObjectRequest);
        System.out.println("Printing bytes retrieved:");
        displayTextInputStream(objectPortion.getObjectContent());
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which " +
                   "means your request made it " +
                                       "to Amazon S3, but was rejected with an error response" +
                   " for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());

    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " +
                   "means the client encountered " +
                                       "an internal error while trying to " +
                                       "communicate with S3, " +
                   "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());

    }

    }

    private static void displayTextInputStream(InputStream input)
    throws IOException {
    // Read one text line at a time and display.
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    while (true) {
        String line = reader.readLine();
        if (line == null) break;

        System.out.println("    " + line);
    }
    System.out.println();       
    }
}


Dependency jars



After upload the file you can check S3 Browser for uploaded files