Saturday, 25 July 2015

Window batch file created folder in current date and copy files.

Windows batch file creating folder in current date as name.

In following example contains the concept for 

1.substring  in batch file
2.comments in batch file
3.creating the folder 
4.for loop 

substring in batch

SET yy=%date:~-4%
 my date is "Sat 07/25/2015 " by using the above code i have cut the "2015" only

Comments
By using  :: i did comments Ref line no 2 author 

my system date format is Sat 07/25/2015  By using substring i have convert into dd-mm-yy

Instruction: Do leave the space between variable declaration and initializing eg. Ref: line no 5-10


@ECHO off
::author bala2e
SET appName=bala2e

SET yy=%date:~-4%
SET mm=%date:~-10,2%
SET dd=%date:~-7,2%
SET MYDATE=%dd%-%mm%-%yy%
SET baseDir=\\192.168.10.88\home\%MYDATE%
SET serverDir=\\192.168.8.202\eGurkha\manager\tomcat\webapps\final
SET appBaseDir=%baseDir%\%appName%
SET controllerDir=%appBaseDir%\controller
SET viewDir=%appBaseDir%\view
SET mkDirectory=(%baseDir% %appBaseDir% %controllerDir% %viewDir%)

FOR %%i IN %mkDirectory% DO MKDIR %%i
SET FILE_LIST=(%serverDir%\reporter\file.jsp %serverDir%\WEB-INF\classes\com\reporter\file.java %serverDir%\WEB-INF\classes\com\db\MsSqlConnect.java %serverDir%\WEB-INF\classes\com\db\OracleConnect.java)

FOR %%i IN %FILE_LIST% DO COPY %%i %baseDir%


COPY "%serverDir%\reporter\scripts\%appName%\*.*" %appBaseDir%
COPY "%serverDir%\reporter\scripts\%appName%\controller\*.*" %controllerDir%
COPY "%serverDir%\reporter\scripts\%appName%\view\*.*" %viewDir%

Tuesday, 14 July 2015

How to run sql queries in parallel in java and give response to user Performance increace with select query using thread

How to run SQL Queries simultaneous in java and get response.

The will show you how to run SQL query parallel using java thread and  give response once all finished its execution.

By using below Two java programs .For Reference please see below sql dump. I have used MySQL.

Below link contains all File 


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 
 * @author Bala2e
 *
 */
public class ThreadWithSQL {

 public void runAllThreads() {

  final Connection con = this.getConnection();
  final SQLQuery sqlQuery = new SQLQuery();

  Thread firstQueryThread = new Thread(new Runnable() {
   public void run() {
    sqlQuery.getEmployeeDetails(con);
   }
  });

  Thread secondQueryThread = new Thread(new Runnable() {
   public void run() {
    sqlQuery.getSalesmanDetails(con);

   }
  });
  Thread thridQueryThread = new Thread(new Runnable() {
   public void run() {
    sqlQuery.getClientDetails(con);
   }
  });

  firstQueryThread.start();
  secondQueryThread.start();
  thridQueryThread.start();

  try {
   firstQueryThread.join();
   secondQueryThread.join();
   thridQueryThread.join();

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

  }

  ResultSet rsEmp    = sqlQuery.rsEmp;
  ResultSet rsSales  = sqlQuery.rsSales;
  ResultSet rsClient = sqlQuery.rsclient;

  try {
   
   System.out.println("---------------- Emp Details----------------------");
   while (rsEmp != null && rsEmp.next()) {
    System.out.println("id-" + rsEmp.getString(1) + " name- "+ rsEmp.getString(2));
   }
   
   System.out.println("---------------- Salesman Details----------------------");

   while (rsSales != null && rsSales.next()) {
    System.out.println("id-" + rsSales.getString(1) + "  name- "+ rsSales.getString(2));
      

   }
   System.out.println("---------------- Client Details----------------------");
   while (rsClient != null && rsClient.next()) {
    System.out.println("id-" + rsClient.getString(1) + " name- "+ rsClient.getString(2));

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

 }

 public Connection getConnection() {
  Connection con = null;
  try {
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection(
     "jdbc:mysql://localhost:3306/test", "root", "root");
  } catch (Exception e) {
   e.printStackTrace();

  }

  return con;
 }

 public static void main(String[] args) {
  ThreadWithSQL threadWithSQL = new ThreadWithSQL();

  threadWithSQL.runAllThreads();

  // threadWithSQL.runAllThreads();

 }
}


Second Program

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 * 
 * @author Bala2e
 *
 */
public class SQLQuery {
 ResultSet rsEmp, rsSales, rsclient;

 public void getEmployeeDetails(Connection con) {

  try {
   Statement stmt = con.createStatement();
   rsEmp = stmt.executeQuery("select e.emp_id,e.emp_name from  test.employee e");
     

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

 public void getSalesmanDetails(Connection con) {
  try {
   Statement stmt = con.createStatement();
   rsSales = stmt.executeQuery("select  sm.sales_man_id,sm.name from  test.sales_man sm");
     

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

 }

 public void getClientDetails(Connection con) {

  try {
   Statement stmt = con.createStatement();
   rsclient = stmt.executeQuery("select c.client_id, c.client_name from test.client c");
     

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



Following is the SQL Dump.

CREATE DATABASE  IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `test`;
-- MySQL dump 10.13  Distrib 5.6.17, for Win64 (x86_64)
--
-- Host: localhost    Database: test
-- ------------------------------------------------------
-- Server version 5.6.21-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `client`
--

DROP TABLE IF EXISTS `client`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `client` (
  `client_id` int(11) NOT NULL,
  `client_name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `client`
--

LOCK TABLES `client` WRITE;
/*!40000 ALTER TABLE `client` DISABLE KEYS */;
INSERT INTO `client` VALUES (1,'murugan store'),(2,'kumar store');
/*!40000 ALTER TABLE `client` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `employee`
--

DROP TABLE IF EXISTS `employee`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `employee` (
  `emp_id` int(11) NOT NULL,
  `emp_name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `employee`
--

LOCK TABLES `employee` WRITE;
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` VALUES (1,'Arun'),(2,'Bala');
/*!40000 ALTER TABLE `employee` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `master_user_details`
--

DROP TABLE IF EXISTS `master_user_details`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `master_user_details` (
  `user_detail_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` varchar(255) DEFAULT NULL,
  `mobile_no` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`user_detail_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `master_user_details`
--

LOCK TABLES `master_user_details` WRITE;
/*!40000 ALTER TABLE `master_user_details` DISABLE KEYS */;
INSERT INTO `master_user_details` VALUES (1,'B.Balamurugan','27','9042221'),(2,'BALA','27','56565656'),(3,'cc','cccv','vv');
/*!40000 ALTER TABLE `master_user_details` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `sales_man`
--

DROP TABLE IF EXISTS `sales_man`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sales_man` (
  `sales_man_id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`sales_man_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `sales_man`
--

LOCK TABLES `sales_man` WRITE;
/*!40000 ALTER TABLE `sales_man` DISABLE KEYS */;
INSERT INTO `sales_man` VALUES (1,'ajay'),(2,'pinkku');
/*!40000 ALTER TABLE `sales_man` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `user_details`
--

DROP TABLE IF EXISTS `user_details`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_details` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role_id` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `user_details`
--

LOCK TABLES `user_details` WRITE;
/*!40000 ALTER TABLE `user_details` DISABLE KEYS */;
INSERT INTO `user_details` VALUES (1,'bala','bala','1');
/*!40000 ALTER TABLE `user_details` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2015-07-14 23:56:07


Saturday, 11 July 2015

Ext JS MVC Pattern ,AJAX Call in Ext JS , Show AJAX Response in grid with Java Servlet

Sencha ‘s Ext JS.

It is the object oriented framework in the base of javascript.
It is used create the web pages with object oriented pattern just like JAVA’S Class method MVC s.
By default it provides many class to create the as input box, combo box etc in page. in its API  
It provides methods for the default and customs validation and control the DOM .
It just like plug and play.

Below URL contains the war file for below example

Now am going to give an example to design web page by apply MVC pattern in ext JS. 
Following example covers
  1.      . MVC pattern in Ext js
  2.        Applying Ajax in combo box
  3.        Displaying Ajax JSON response given by JAVA servlet in Ext js grid panel.

                                                    Before AJAX  Response.

   
After Ajax JSON response Show in grid View

Below URL contains the war file for above example




Wednesday, 13 May 2015

"main" javax.mail.AuthenticationFailedException:

Java email sending exception with google account

Exception in thread "main" javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbuup
534-5.7.14 IqqkRuDjMmFzeS4jfmU-M1RYjtZoIp1O6J8adnURMIQe6PZgmbT456zZ6zVtEFguXUz8Zl
534-5.7.14 mPMP1hK_73NkWIVs37DecEtdMmFRyg9yBu9VhUgjhkB95CRhvJHgBHDfuX5jPVCZFCNuvm
534-5.7.14 KDphLQyCoQ-QsOcTEGT2dnBOcCR4srrI1IaD-ms5o4fX9kcPH9fx3ghZxpTV5PEUSlWSJC
534-5.7.14 l-q_JybfhW1akjyXPY4ZIZb4E1dE> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 gj5sm20978260pbb.22 - gsmtp

at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
at javax.mail.Service.connect(Service.java:271)

at javax.mail.Service.connect(Service.java:91)


Solution.
1.Login in your gmail account
2.https://www.google.com/settings/security/lesssecureapps
3. Turn on it






Wednesday, 24 September 2014

In crystal report How to avoid or disable login prompt popup in java

Avoid or disable  CrystalReport login prompt popup in java

use belew code in viewer file:-


CrystalReportViewer crystalReportPageViewer = new CrystalReportViewer();
    
ConnectionInfos connInfos = new ConnectionInfos();
IConnectionInfo connInfo1 = new ConnectionInfo();
    
 connInfo1.setUserName("YourUserName");
        connInfo1.setPassword("Yourpassword");
        connInfos.add(connInfo1);

    crystalReportPageViewer.setEnableParameterPrompt(false);
    crystalReportPageViewer.setDatabaseLogonInfos(connInfos);








Cystal Report new line with java .

By using Can Grow option in conditional formulas, we can achieve the new line in crystal 
report 

if it returns true, can Grow option will enabled for the required field.

Sunday, 17 August 2014

Spring Exception

org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:491) 


The above exception relates the command object
It will occur following scenario.
 1.when  command  object to view page not properly set into the page.
2.command object name misspelled 
 
 

Saturday, 16 August 2014

Spring Login Example.

Spring Login with username and password.

Following example demonstrate the simple login in web page.

I have used annotation for the controller

user name:  bala
password : bala123
spring Login Example war

Page 1  Login page:











Page 2 : Success Page:



Page 3 Failure Page
When user enter Incorrect  Username or password.


Following link contains the war file to execute the login spring application

spring Login Example war

Wednesday, 11 June 2014

Create Jar File in windows

Create Jar File in windows:

set class path for java
set path = C:\Program Files\Java\jdk1.6.0\bin

jar file creation command for all class files in current and sub directory

commad  :- jar cvf jarFileName directory

examnple: jar cvf "myjar1.jar" .\in

jar file creation command for particular files

commad  :- jar cvf jarFileName  "fileName 1,fileName 2,fileName 3"

examnple: jar cvf "myjar1.jar" "sample.class,example.class"

To cheack jar file:

E:\NewFolder\jboss-4.0.3\server\default\deploy\timesheet.war\WEB-INF\classes>jar  tvf myjar1.jar

Tuesday, 15 April 2014

My Exceptions

org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435).
java.lang.IllegalStateException

At point of nothing to response to client (browser)

Following is sample example
if(a.equals("7")){
  RequestDispatcher dispatcher= getServletContext().getRequestDispatcher("/login.jsp");
   dispatcher.forward(request,response);

}

if(b.equals("6")){
  RequestDispatcher dispatcher= getServletContext().getRequestDispatcher("/login.jsp");
    dispatcher.forward(request,response);

}

In first  block itself it respond to browser . In step 2 nothing to response
so this exception will occur

To Avoid Exception java.lang.IllegalStateException.
Add return statement .
if(a.equals("7")){
      RequestDispatcher dispatcher= getServletContext().getRequestDispatcher("/login.jsp");
    dispatcher.forward(request,response);
      return;
}

Javascript Useful Code

 Dynamic Regex :-
Try the following code when systen test is not function in  javascript. while regex  validation.
or
Dynamic create the Regex that is stored in another variable and compare
check In if condition you have place the regex pattern and email  in correct location as follow
if(pattern.test(emailid)
 
var emailid='balamurugan2b@gmail.com';
var regexpattern='^([\w-]+(?:\.[\w-]+)*)@(gmail.com)$';
var pattern = new RegExp(regexpattern);

if(pattern.test(emailid)){
true;
}else{
false;
}


add more rows and delete row

Click Here


jquery drag and drop file upload

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
#dragandrophandler
{
border:2px dotted #0B85A1;
width:400px;
color:#92AAB0;
text-align:left;vertical-align:middle;
padding:10px 10px 10 10px;
margin-bottom:10px;
font-size:200%;
}
.progressBar {
    width: 200px;
    height: 22px;
    border: 1px solid #ddd;
    border-radius: 5px; 
    overflow: hidden;
    display:inline-block;
    margin:0px 10px 5px 5px;
    vertical-align:top;
}
 
.progressBar div {
    height: 100%;
    color: #fff;
    text-align: right;
    line-height: 22px; /* same as #progressBar height if we want text middle aligned */
    width: 0;
    background-color: #0ba1b5; border-radius: 3px; 
}
.statusbar
{
    border-top:1px solid #A9CCD1;
    min-height:25px;
    width:700px;
    padding:10px 10px 0px 10px;
    vertical-align:top;
}
.statusbar:nth-child(odd){
    background:#EBEFF0;
}
.filename
{
display:inline-block;
vertical-align:top;
width:250px;
}
.filesize
{
display:inline-block;
vertical-align:top;
color:#30693D;
width:100px;
margin-left:10px;
margin-right:5px;
}
.abort{
    background-color:#A8352F;
    -moz-border-radius:4px;
    -webkit-border-radius:4px;
    border-radius:4px;display:inline-block;
    color:#fff;
    font-family:arial;font-size:13px;font-weight:normal;
    padding:4px 15px;
    cursor:pointer;
    vertical-align:top
    }
</style>
</head>
 
<body>
<div id="dragandrophandler">Drag & Drop Files Here</div>
<br><br>
<div id="status1"></div>
<script>
function sendFileToServer(formData,status)
{
    var uploadURL ="fileUpload.jsp"; //Upload URL
    var extraData ={}; //Extra Data.
    var jqXHR=$.ajax({
            xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();
            if (xhrobj.upload) {
                    xhrobj.upload.addEventListener('progress', function(event) {
                        var percent = 0;
                        var position = event.loaded || event.position;
                        var total = event.total;
                        if (event.lengthComputable) {
                            percent = Math.ceil(position / total * 100);
                        }
                        //Set progress
                        status.setProgress(percent);
                    }, false);
                }
            return xhrobj;
        },
    url: uploadURL,
    type: "POST",
    contentType:false,
    processData: false,
        cache: false,
        data: formData,
        success: function(data){
            status.setProgress(100);
 
            $("#status1").append("File upload Done<br>");         
        }
    }); 
 
    status.setAbort(jqXHR);
}
 
var rowCount=0;
function createStatusbar(obj)
{
     rowCount++;
     var row="odd";
     if(rowCount %2 ==0) row ="even";
     this.statusbar = $("<div class='statusbar "+row+"'></div>");
     this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
     this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
     this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
     this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
     obj.after(this.statusbar);
 
    this.setFileNameSize = function(name,size)
    {
        var sizeStr="";
        var sizeKB = size/1024;
        if(parseInt(sizeKB) > 1024)
        {
            var sizeMB = sizeKB/1024;
            sizeStr = sizeMB.toFixed(2)+" MB";
        }
        else
        {
            sizeStr = sizeKB.toFixed(2)+" KB";
        }
 
        this.filename.html(name);
        this.size.html(sizeStr);
    }
    this.setProgress = function(progress)
    {       
        var progressBarWidth =progress*this.progressBar.width()/ 100;  
        this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
        if(parseInt(progress) >= 100)
        {
            this.abort.hide();
        }
    }
    this.setAbort = function(jqxhr)
    {
        var sb = this.statusbar;
        this.abort.click(function()
        {
            jqxhr.abort();
            sb.hide();
        });
    }
}
function handleFileUpload(files,obj)
{
   for (var i = 0; i < files.length; i++) 
   {
        var fd = new FormData();
        fd.append('file', files[i]);
 
        var status = new createStatusbar(obj); //Using this we can set progress.
        status.setFileNameSize(files[i].name,files[i].size);
        sendFileToServer(fd,status);
 
   }
}
$(document).ready(function()
{
var obj = $("#dragandrophandler");
obj.on('dragenter', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
    $(this).css('border', '2px solid #0B85A1');
});
obj.on('dragover', function (e) 
{ 
     
     e.stopPropagation();
     e.preventDefault();
});
obj.on('drop', function (e) 
{
 
     $(this).css('border', '2px dotted #0B85A1');
     e.preventDefault();
     var files = e.originalEvent.dataTransfer.files;
 
     //We need to send dropped files to Server
     handleFileUpload(files,obj);
});
$(document).on('dragenter', function (e) 
{
  
    e.stopPropagation();
    e.preventDefault();
});
$(document).on('dragover', function (e) 
{

  e.stopPropagation();
  e.preventDefault();
  obj.css('border', '2px dotted #0B85A1');
});
$(document).on('drop', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
});
 
});
</script>
</body>
</html>


fileUpload.jsp

<!--
File Name :-fileUpload.jsp
Created By:-B.Balamurugab
Created on:-May 14,2014.
Description:- This file is used for upload
    droped file 
Edited By 
-->


<%@ page language="java" import="java.io.*,java.util.*" %>
<%@ page import="java.sql.*,in.textech.library.DatabaseLibrary,in.textech.common.ConstantValues" %>
<%@page import="in.textech.library.DatabaseLibrary"%>
<%@ page import="in.textech.library.LocaleDateTime" %>
<%@page import="in.textech.common.ConstantValues"%>

<%@page import="java.sql.Connection"%>
<%@page import="com.mysql.jdbc.Driver"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.io.File"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%

response.setContentType("text/html");
response.setHeader("Cache-control","no-cache");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
try{
if(!ServletFileUpload.isMultipartContent(request)) {
  out.println("Request does not contain upload data");
  return;
 }

 // configures upload settings
 DiskFileItemFactory factory = new DiskFileItemFactory();

 factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    String UPLOAD_DIRECTORY = "PO";

 // constructs the directory path to store upload file
 String uploadPath = System.getProperty("java.io.tmpdir")+ UPLOAD_DIRECTORY;
 // creates the directory if it does not exist
 File uploadDir = new File(uploadPath);
 if (!uploadDir.exists()) {
  uploadDir.mkdir();
 }
 String filePath = "";

 // parses the request's content to extract file data
 List formItems = upload.parseRequest(request);
 Iterator iter = formItems.iterator();

 // iterates over form's fields
 while (iter.hasNext()) {
  FileItem item = (FileItem) iter.next();
  // processes only fields that are not form fields
  if (!item.isFormField()) {
   String fileName = new File(item.getName()).getName();
   if(fileName!=null && !"".equals(fileName)){
    filePath = uploadPath + File.separator + fileName;
    File storeFile = new File(filePath);
    // saves the file on disk
    item.write(storeFile);
    
    
         }
  }
 }
}catch(Exception e){
 e.printStackTrace();
 
}

response.getWriter().write("y");

%>
drag and drop file upload pure java script .


                window.onload = function() {
                var dropbox = document.getElementById("dropbox");
                dropbox.addEventListener("dragenter", noop, false);
                dropbox.addEventListener("dragexit", noop, false);
                dropbox.addEventListener("dragover", noop, false);
                dropbox.addEventListener("drop", dropUpload, false);
            }

            function noop(event) {
                event.stopPropagation();
                event.preventDefault();
            }

            function dropUpload(event) {
                noop(event);
                var files = event.dataTransfer.files;
               for (var i = 0; i < files.length; i++) {
    var xhr = new XMLHttpRequest();
                               xhr.open("POST", fileUpload.jsp, false); 
                                    xhr.send(formData)
} } function upload(file,poID) { } function uploadProgress(event) { // Note: doesn't work with async=false. var progress = Math.round(event.loaded / event.total * 100); document.getElementById("status").innerHTML = "Progress " + progress + "%"; } function uploadComplete(event) { alert("Complete Request"); }

Show only month and year 

Call  setYearToDropDown() in onload of page

Html Code

<html>
<body onload="setYearToDropDown()">

<table>
<tr><td><td>Month</td><td>
<select name="year" id="year" style="width:155px" size="1" onchange="display_month()" >
</td>
</tr>
<tr><td><td>Year</td><td>

<select name="month" id="month"  style="width:155px"   size="1"  >
</td>
</tr>
</body>

<script>

function setYearToDropDown(){
   var currentDate = new Date();
         var currentYear = currentDate.getFullYear(); 
   var nextYear = currentYear +1; 
   var nextNextYear = nextYear+1;
   
     document.getElementById("year").options.length = 0;
  document.getElementById("year").options[0] = new Option('Select','');
  document.getElementById("year").options[1] = new Option(currentYear,currentYear);
  document.getElementById("year").options[2] = new Option(nextYear,nextYear);
  document.getElementById("year").options[3] = new Option(nextNextYear,nextNextYear);

   
 }

 function display_month() {

 var year = document.getElementById("year").value;
 var k=1;
 var d = new Date();
 var n = d.getMonth(); 
 var Currentyear = d.getFullYear()
 var month=new Array();
  month[0]="January";
  month[1]="February";
  month[2]="March";
  month[3]="April";
  month[4]="May";
  month[5]="June";
  month[6]="July";
  month[7]="August";
  month[8]="September";
  month[9]="October";
  month[10]="November";
  month[11]="December";
  
 if(document.getElementById("year").value !="") {      
  document.getElementById("month").options.length = 0;
  document.getElementById("month").options[0] = new Option('Select','');
  
  if(Currentyear==year) {
  
   for(var i=n;i<month.length;i++) {
    document.getElementById("month").options[k] = new Option(month[i],i+1);
   k++;
   }
  }
  else {
   
   for(var i=1;i<=month.length;i++) {
    document.getElementById("month").options[i] = new Option(month[i-1],i);
   }
  }
 }
 else {
  document.getElementById("month").options.length = 0;
  document.getElementById("month").options[0] = new Option('Select','');
 
 }
 
}
</script>
</html>

jQuery get radio buttom value

<td> <input type="radio" name="sendMail"  id="sendMailYes" value="yes" >Yes<br>
       <input type="radio" name="sendMail" id="sendMailNo" value="no" >No</td>

var issendMail =  $('input[name=sendMail]:checked').val(); 



To Select Multi select dropdwon

function selectTeamSubgroup(){
  $("#selectedVendor").each(function(){
            $("#selectedVendor option").attr("selected","selected"); });
  
 }
 

File Upload to Server  on change of input Box
window.addEventListener('load',function(){ var emailAttachment = document.getElementById("files"); emailAttachment.addEventListener("change", handleFileSelect, false); }); function handleFileSelect(e) { var storedFiles = []; var valuesCount; var requestAttachment; var files = e.target.files; var filesArr = Array.prototype.slice.call(files); filesArr.forEach(function(f) { storedFiles.push(f); var reader = new FileReader(); reader.onload = function (e) { } reader.readAsDataURL(f); }); var data = new FormData(); valuesCount =storedFiles.length; for(var i=0, len=storedFiles.length; i<len; i++) { data.append('files', storedFiles[i]); } if (window.XMLHttpRequest) { requestAttachment = new XMLHttpRequest(); } else if (window.ActiveXObject) { requestAttachment = new ActiveXObject("Microsoft.XMLHTTP"); } var url = "conversionEmailAttachment.jsp"; requestAttachment.open("POST", url, true); requestAttachment.onreadystatechange =callbackUpload(requestAttachment,mainUpload); requestAttachment.send(data); } function callbackUpload(requestAttachment,responseXmlHandler){ return function(){ if(requestAttachment.readyState == 4) { if(requestAttachment.status == 200){ var height = 600; document.getElementById("selDiv").innerHTML=""; var jsonObj = JSON.parse(requestAttachment.responseText); for (var key in jsonObj) { if (jsonObj.hasOwnProperty(key)) { var fileName1 = jsonObj[key]; var html = "<div>" + fileName1.split("\\").pop() + " <img src=\"images/icon/attachmentDel.png\" onClick='deleteMe("+JSON.stringify(key)+");'/></div>"; document.getElementById("selDiv").innerHTML+= html; height +=30; } } document.getElementById("email_send").style.height = height+"px"; } else{ alert("Http error :"+requestAttachment.status); } } } } function mainUpload(main) { } function deleteMe(fileID){ var url = "deleteEmailAttachment.jsp?fileID="+fileID; var request; try{ if (window.XMLHttpRequest){ request = new XMLHttpRequest(); } else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP"); } request.open("GET", url, true); request.onreadystatechange = callbackDelete(request,mainDelete); request.send(null); } catch(e){ alert(e); } } function callbackDelete(request,responseXmlHandler1){ return function(){ if(request.readyState == 4) { if(request.status == 200){ var jsonObj = JSON.parse(request.responseText); document.getElementById("selDiv").innerHTML=""; for (var key in jsonObj) { if (jsonObj.hasOwnProperty(key)) { var fileName1 = jsonObj[key]; var html = "<div>" + fileName1.split("\\").pop() + " <img src=\"images/icon/attachmentDel.png\" onClick='deleteMe("+JSON.stringify(key)+");'/></div>"; document.getElementById("selDiv").innerHTML+= html; } } } else{ alert("Http error :"+requestAttachment.status); } } } } function mainDelete(main) { }

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

Disable dates in jquery Calender 


var x="Threshold Reached";

    <% 

    CustomThreshold threshold = new CustomThreshold();
    String[] disabledDays= threshold.dateFoundCheck(employee_id);
    //String[] params = request.getParameterValues("someField");  
 
 int disableDaysLength=disabledDays.length;
    
    
    for (int i=0;i<disabledDays.length;i++) {
out.println("unavailableDates["+i+"]='"+disabledDays[i]+"';");
}
%> function unavailable(date) {
        ymd = date.getFullYear() + "-" + ("0"+(date.getMonth()+1)).slice(-2) + "-" + ("0"+date.getDate()).slice(-2);
        day = new Date(ymd).getDay();
        if ($.inArray(ymd, unavailableDates) < 0 ) {
            return [true, "enabled", ""];
        } else {
            return [false,"disabled",x];
        }
    }

/* create datepicker */
jQuery(document).ready(function() {
  jQuery('#startdate').datepicker({
 
    minDate: new Date(2010, 0, 1),
    maxDate: '+1Y',
 //minDate: 0,
    dateFormat: 'dd-mm-yy',
    constrainInput: true,
    showOn: "button",
    buttonImage: "../images/cal1.gif",
    buttonImageOnly: true,
   beforeShowDay:unavailable
  });
});
jQuery(document).ready(function() {
  jQuery('#enddate').datepicker({
 
    minDate: new Date(2012, 0, 1),
    maxDate: '+1Y',
 
    dateFormat: 'dd-mm-yy',
    constrainInput: true,
    showOn: "button",
    buttonImage: "../images/cal1.gif",
    buttonImageOnly: true,
   beforeShowDay:unavailable
  });
});