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



Tuesday 27 December 2016

How to upload multiple file using jsp




save as 'img.jsp'

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
    <script language="javascript" type="text/javascript">
       function chkFile(){         
      var fileChk =  document.getElementById("fileupload").value;
           if(fileChk==null || fileChk==""){
            alert("Please upload any file !");
           return false;
           }
       }
        window.onload = function () {
            var fileUpload = document.getElementById("fileupload");
            fileUpload.onchange = function () {
                if (typeof (FileReader) != "undefined") {
                    var dvPreview = document.getElementById("dvPreview");
                    dvPreview.innerHTML = "";
                    var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.pdf|.xls|.xlsx|.doc|.docx)$/;
                    for (var i = 0; i < fileUpload.files.length; i++) {
                        var file = fileUpload.files[i];
                        if (regex.test(file.name.toLowerCase())) {
                            var reader = new FileReader();
                            reader.onload = function (e) {
                                var img = document.createElement("IMG");
                                img.height = "100";
                                img.width = "100";
                                img.src = e.target.result;
                                dvPreview.appendChild(img);
//alert("img >> "+file.name+img);
                            }
                            reader.readAsDataURL(file);
                        } else {
                            alert(file.name + " is not a valid image file.");
                            dvPreview.innerHTML = "";
                            document.getElementById("fileupload").value="";
                            return false;
                        }
                    }
                } else {
                    alert("This browser does not support HTML5 FileReader.");
                }
            }
        };
    </script>
</head>
<body>
 <form action="upload_file_multipale.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
    <div>
        <input id="fileupload" name="file" type="file" multiple="multiple" />
        <hr />
        <b>Live Preview</b>
        <br />
        <br />
        <div id="dvPreview">
        </div>
           <input type="submit" name="Submit" value="Submit files" onClick="chkFile();" />
    </div>
    </form>
</body>
</html>


save as 'upload_file_multipale.jsp'


   <%@ page import="java.util.List" %>
   <%@ page import="java.util.Iterator" %>
   <%@ page import="java.io.File" %>
   <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
   <%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
   <%@ page import="org.apache.commons.fileupload.*"%>
   <%@ page contentType="text/html;charset=UTF-8" language="java" %>
   <center><table border="2">
        <tr><td><h1>Your files  uploaded </h1></td></tr>
   <%
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 if (!isMultipart) {
 } else {
  FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  List items = null;
  try {
  items = upload.parseRequest(request);
  } catch (FileUploadException e) {
  e.printStackTrace();
  }
  Iterator itr = items.iterator();
  while (itr.hasNext()) {
  FileItem item = (FileItem) itr.next();
  if (item.isFormField()) {
  } else {
  try {
  String itemName = item.getName();
  File savedFile = new File("G:/uploadedFiles/"+itemName);
  item.write(savedFile);  
  out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  }
   }
   %>
    </table>
   </center>



Friday 18 November 2016

How to Encrypt and Decrypt file using java code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncriptDecrypt {
    
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES";
    
    public static void main(String args[]) throws Exception{
        
       EncriptDecrypt.decrypt(new File("c:\\encryptFile\\encr.xls"), new File("c:\\decryptFile\\decr.xls"));  
       EncriptDecrypt.encrypt(new File("c:\\test.xls"), new File("c:\\decryptFile\\encr.xls"));  
    }
    
       public static void encrypt(File inputFile, File outputFile)
            throws Exception {
        doCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile);
    }

    public static void decrypt(File inputFile, File outputFile)
            throws Exception {
        doCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile);
    }
    
    private static void doCrypto(int cipherMode, File inputFile,
            File outputFile) throws Exception {
        try {
            byte[] keyLength = new byte[16];
            Key secretKey = new SecretKeySpec(keyLength, ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKey);
            FileInputStream inputStream = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            inputStream.read(inputBytes);
            byte[] outputBytes = cipher.doFinal(inputBytes);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            outputStream.write(outputBytes);
            inputStream.close();
            outputStream.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
}



Wednesday 30 March 2016

ITMS emailschedular

package com.itms.resource;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Vector;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.itms.bo.EmailSchedularBO;
import com.itms.dao.VException;

public class EmailSchedular implements Job{

static final Logger _log=Logger.getLogger(com.itms.resource.EmailSchedular.class);
static ResourceBundle szResBundl = ResourceBundle.getBundle("com/itms/resource/mailProperties");
String message = szResBundl.getString("MESSAGE_EMAIL_SCHEDULAR");
String subject= szResBundl.getString("SUBJECT_EMAIL_SCHEDULAR");
EmailSchedularBO szMailJob7DaysBO;
HashMap szHmap=null;
HashMap szMap=null; 
HashMap szMapW=null;
HashMap mailMap=null;
Vector szVec = null;
Vector szVec1 = null;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
java.util.Date utildate = new Date();
java.sql.Date sqlDate = new java.sql.Date(utildate.getTime());
Calendar calendar = Calendar.getInstance();

public void execute(JobExecutionContext jExeCtx) throws JobExecutionException {
// TODO Auto-generated method stub

System.out.println("<<< TestSchedular start >>> ");
try {

_log.info("In MailJob7Days Schedular >> job method >> ");
System.out.println("In MailJob7Days Schedular >> job method >> ");
szMailJob7DaysBO = new EmailSchedularBO(); 
szHmap= new HashMap();
mailMap=new HashMap();
szMapW= new HashMap();
szMap= new HashMap();
szVec= new Vector();
szVec1= new Vector();
try{
System.out.println("Email schedular srart for sending Mail ... ");
String toDayDate=sqlDate+"";
System.out.println(toDayDate);
// szHmap.put("", "");
szVec = szMailJob7DaysBO.getApprovedPreClerance(szHmap);
System.out.println("szVec -- "+szVec.size() +" -- "+szVec1.size());
String userName ="";
String submittedDate=""; 
String itms ="";
// System.out.println(szMapW.get("RowNum") +" "+ szMapW.get("alldate"));
// System.out.println(szMap.get("EMAIL_ID")); //APPROVAL_DATE


for(int k=0;k<szVec.size();k++){
szMap = (HashMap) szVec.get(k);
System.out.println("szMap: : "+ szMap);
szVec1 =szMailJob7DaysBO.getWorkingDay(szMap);
System.out.println("szVec1== "+szVec1);
userName =(String) szMap.get("EMPLOYEE_NAME"); 
for(int i=0;i<szVec1.size();i++)
{
szMapW = (HashMap) szVec1.get(i);
System.out.println("alldate  >> "+szMapW.get("alldate"));
}
submittedDate =(String) szMap.get("SUBMITTED_ON");

String date1 = submittedDate;
System.out.println("date1 >>"+date1);
String [] datePass1 = submittedDate.split(" ",0);
                    //System.out.println("datePass1 "+datePass1[0]);

itms =(String) szMap.get("PRE_ITMS_NO");
message = message.replaceAll("#USER#",userName);
message = message.replaceAll("#DATE#",datePass1[0]);
subject = subject.replaceAll("#ITMSNO#",itms);
subject = subject.replaceAll("#DATE#",datePass1[0]);
mailMap.put("ITMS_NO", itms);
mailMap.put("EMP_OS_NAME", userName);
mailMap.put("EMAIL_ID", szMap.get("EMAIL_ID"));
mailMap.put("MESSAGE", " ");
mailMap.put("CCEMAIL", " ");
mailMap.put("EMAIL_DATE", toDayDate);
String [] allDate1 = szMapW.get("alldate").toString().split(" ");
String dt = allDate1[0];
System.out.println(dt+" ================= dt  >> " +toDayDate);
if(dt.equals(toDayDate)){
//EmailSend.sendEmail((String) szMap.get("EMAIL_ID"), "", subject, message);
szMailJob7DaysBO.insertEmailSchedular(mailMap);
}
 }

}catch(Exception ex){
ex.printStackTrace();
System.out.println("MailJob7Days Exception >> "+ex);
} catch (VException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}