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();
}

}
}

Wednesday 16 March 2016

Excel make a query

="INSERT INTO MST_ITMS_ROLE_MAPPING  (EMP_OS_NAME,EMP_CODE,ROLE_ID,MAPPING_ID) VALUES('"&A2&"','"&B2&"','"&C2&"','"&D2&"');"

Sunday 24 January 2016

File upload validation with jquery




<script src="js/jquery-1.8.3.js"></script>

<script type="text/javascript">
    $(function () {
        $('#files').change(
            function () {
                var fileExtension = ['jpeg', 'jpg'];
                if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                     //alert("Only '.jpeg','.jpg' formats are allowed.");
                   // $('#files').attr("disabled", true);
                    $('#lblmsg').html("Only '.jpeg','.jpg' formats are allowed.");
$(this).val('');
                }
                else {
                    $('#files').attr("disabled", false);
                    $('#lblmsg').html(" ");
                } 
            })  
    })  
</script>

<form id="form1" action="home.html">
<div>  
File Upload <input type="file" id="files" ></input>
<input type="submit" value="submit" id="btnsubmit"></input>
</div> 
<label id ="lblmsg" style="color:RED">****</label>
</form>




Wednesday 29 July 2015

How to show loading image while calling AJAX request


 


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style>
            body, html {
            margin:0;
            padding;
            height:100%
        }

        a {
            font-size:1.25em;
        }

        #content {
            padding:25px;
        }

        #fade {
            display: none;
            position:absolute;
            top: 0%;
            left: 0%;
            width: 100%;
            height: 100%;
            background-color: #ababab;
            z-index: 1001;
            -moz-opacity: 0.8;
            opacity: .70;
            filter: alpha(opacity=80);
        }

        #modal {
            display: none;
            position: absolute;
            top: 45%;
            left: 45%;
            width: 100px;
            height: 100px;
            padding:20px 15px 15px;
            border: 3px solid #ababab;
            box-shadow:1px 1px 10px #ababab;
            border-radius:20px;
            background-color: white;
            z-index: 1002;
            text-align:center;
            overflow: auto;
        }

        #results {
            font-size:1.25em;
            color:red
        }
   
    </style>
   
   
    <script>
            function openModal() {
                document.getElementById('modal').style.display = 'block';
                document.getElementById('fade').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('modal').style.display = 'none';
            document.getElementById('fade').style.display = 'none';
        }
               
        function loadAjax() {
            document.getElementById('results').innerHTML = '';
            openModal();
            var xhr = false;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            }
            else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xhr) {
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        closeModal();
                        document.getElementById("results").innerHTML = xhr.responseText;
                    }
                }
                xhr.open("GET", "load.jsp", true);
                xhr.send(null);
            }
        }
   
    </script
</head>
<body>
    <div id="content">

        <!--<a href="/articles/1506-how-to-display-image-spinner-ajax-request">Click here to return to the
        tutorial.</a><br /><br /> <h2>Demo</h2> -->
   
       
        <a href="javascript: void(0);loadAjax();">Click here to load get data via Ajax</a><br /><br />
        <div id="results"><!-- Results are displayed here --></div>
        <div id="fade"></div>
        <div id="modal">
            <img id="loader" style="width:95px;height:95px;border:0px;" src="loadImage.gif" />
        </div>
    </div>
</body>
</html>