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>





Wednesday 15 July 2015

Preventing User to go back after logout in jsp


 <%
  response.setHeader("Cache-Control","no-cache");
  response.setHeader("Cache-Control","no-store");
  response.setHeader("Pragma","no-cache");
  response.setDateHeader ("Expires", 0);

  if(session.getAttribute("user")==null)
      response.sendRedirect("index.jsp");

  %> 

Wednesday 25 February 2015

How to generate a random alpha numeric String in java.


package com.digit;

import java.util.Date;
import java.util.Random;

public class RandumString {
public static void main(String args[]){
//Randum ren= new Randum();
String a = Randum.generateRandomString(6);
System.out.println(a);
}
}

class Randum{

private static Random random = new Random((new Date()).getTime());

    public static String generateRandomString(int length) {
      char[] values = {'a','b','c','d','e','f','g','h','i','j',
               'k','l','m','n','o','p','q','r','s','t',
               'u','v','w','x','y','z','0','1','2','3',
               '4','5','6','7','8','9'};

      String out = "";

      for (int i=0;i<length;i++) {
          int idx=random.nextInt(values.length);
        out += values[idx];
      }

      return out;
    }
}


Saturday 21 February 2015

How to send Email to multiple recipients with multiple text messages via SMTP with javaMail

Here i am going to showing how to Send email in java using Gmail SMTP and JavaMail API.

I have used one dependency jar "javax.mail.jar"


package com.mail.system;

import java.util.Properties;

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;

public class EmailTest {

public static void main(String[] args) {

String mailSmtpHost = "smtp.gmail.com";

String[] mailTo = {"mail1@gmail.com","mail2@hotmail.com"};  
String mailCc = "ccMail@rediffmail.com";
String mailFrom = "fromMail@gmail.com";
String mailSubject = "Email from Java";
String[] mailText = {"send email for gmail domain","send email to hotmail domain"};

for (int i = 0; i < mailTo.length; i++) {

sendEmail(mailTo[i], mailCc, mailFrom, mailSubject, mailText[i], mailSmtpHost);
}
}

public static void sendEmail(String to, String cc, String from, String subject, String text, String smtpHost) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
//Session emailSession = Session.getDefaultInstance(properties);

// If you want to use SSL
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");

Session emailSession = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "fromMail@gmail.com";        
String password = "password";
return new PasswordAuthentication(username,password);

}
});

Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
emailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
emailMessage.setText(text);

emailSession.setDebug(true);
Transport transport = emailSession.getTransport("smtp");
transport.send(emailMessage);
System.out.println("Mail successfully Send to ....."+to);
transport.close();
System.out.println("\n");
System.out.println("Transport Session Close .....");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}


Thursday 30 October 2014

How to Convert Tables 'MyISAM' to 'InnoDB' Engine in mysql database


-- QUERY TO CONVERT TABLES 'MyISAM' to 'InnoDB' Engine

SET @DATABASE_NAME = 'database';

SELECT  CONCAT('ALTER TABLE ', table_name, ' ENGINE=InnoDB;') AS sql_statements
FROM    information_schema.tables AS tb
WHERE   table_schema = @DATABASE_NAME
AND     `ENGINE` = 'MyISAM'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;


-- QUERY TO CONVERT TABLES 'InnoDB' TO 'MyISAM' ENGINE


SET @DATABASE_NAME = 'database';

SELECT  CONCAT('ALTER TABLE ', table_name, ' ENGINE=MyISAM;') AS sql_statements
FROM    information_schema.tables AS tb
WHERE   table_schema = @DATABASE_NAME
AND     `ENGINE` = 'InnoDB'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;



Monday 9 June 2014

Create a CRUD application using with DAO design pattern.


DAO or Data Access Object design pattern is good example of abstraction and encapsulation object oriented principles.
It separates persistence logic is a separate layer called Data access layer which enable application to react safely on change in Persistence mechanism.
In short Data Access Object or DAO design pattern is way to reduce coupling between Business logic and Persistence logic

DAO pattern allows you to encapsulate code for performing CRUD operation against persistence from rest of application.
Which means any change on persistence logic will not affect other layers of application which is already tested.

Here i am showing you how to make a CRUD application using with DAO design pattern.




create a table in Mysql database

CREATE TABLE student (
RollNo INT(10)  PRIMARY KEY NOT NULL,
NAME  VARCHAR(50) NOT NULL,
Course VARCHAR(25) NOT NULL,
Address VARCHAR(255)
);


----------------- ConnectionFactory.java -------------------


package com.ramsis.dao;

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

public class ConnectionFactory {
String driverClassName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String dbUser = "root";
String dbPwd = "root";

private static ConnectionFactory connectionFactory = null;

private ConnectionFactory() {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public Connection getConnection() throws SQLException {
Connection conn = null;
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
return conn;
}

public static ConnectionFactory getInstance() {
if (connectionFactory == null) {
connectionFactory = new ConnectionFactory();
}
return connectionFactory;
}
}

------------------------ StudentBean.java --------------------------
package com.ramsis.dao;

import java.io.Serializable;

public class StudentBean implements Serializable {
int rollNo;
String name="";
String course="";
String address="";

public StudentBean() {

}

public StudentBean(int roll, String name, String course, String address) {
this.rollNo = roll;
this.name = name;
this.course = course;
this.address = address;
}

public int getRollNo() {
return rollNo;
}

public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCourse() {
return course;
}

public void setCourse(String course) {
this.course = course;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}


------------------------- StudentJDBCDAO.java ------------------------------
package com.ramsis.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentJDBCDAO {
Connection connection = null;
PreparedStatement ptmt = null;
ResultSet resultSet = null;

public StudentJDBCDAO() throws IOException{

}

private Connection getConnection() throws SQLException {
Connection conn;
conn = ConnectionFactory.getInstance().getConnection();
return conn;
}

public void add(StudentBean studentBean) {
try {
String queryString = "INSERT INTO student(RollNo, Name, Course, Address) VALUES(?,?,?,?)";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, studentBean.getRollNo());
ptmt.setString(2, studentBean.getName());
ptmt.setString(3, studentBean.getCourse());
ptmt.setString(4, studentBean.getAddress());
ptmt.executeUpdate();
System.out.println("Data Added Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}

}

public void update(StudentBean studentBean) {

try {
String queryString = "UPDATE student SET Name=? WHERE RollNo=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, studentBean.getName());
ptmt.setInt(2, studentBean.getRollNo());
ptmt.executeUpdate();
System.out.println("Table Updated Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
}

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

}
}
}

public void delete(int rollNo) {

try {
String querySelectId = "SELECT RollNo FROM student where RollNo=?";
String queryString = "DELETE FROM student WHERE RollNo=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, rollNo); 
ptmt.executeUpdate();
System.out.println("Data deleted Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}

}

public void findAll() {
try {
String queryString = "SELECT * FROM student";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
resultSet = ptmt.executeQuery();
while (resultSet.next()) {
System.out.println("Roll No " + resultSet.getInt("RollNo")
+ ", Name " + resultSet.getString("Name") + ", Course "
+ resultSet.getString("Course") + ", Address "
+ resultSet.getString("Address"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null)
resultSet.close();
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}
}
}


----------------------------- Main.java ------------------------------
package com.ramsis.dao;

import java.io.IOException;
import java.util.Scanner;

public class Main {
public static void main(String[] args) throws IOException{
Scanner scan  = new Scanner(System.in);
StudentJDBCDAO jdbc = new StudentJDBCDAO();
StudentBean bean = new StudentBean();

String ch="";
String num="";
String name="";
String course="";
String address="";
Integer rollNo;


do{        
System.out.println("please number what you want to do ? ");
System.out.println("1) Add data. ");
System.out.println("2) Update data. ");
System.out.println("3) delete data. ");
System.out.println("4) Show data. ");

num = scan.next();

if(num.equals("1")){

System.out.println("Enter the name : ");
name = scan.next();
bean.setName(name);

System.out.println("Enter Roll Number : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);

System.out.println("Enter Course : ");
course = scan.next();
bean.setCourse(course);

System.out.println("Enter the Address : ");
address = scan.next();
bean.setAddress(address);
jdbc.add(bean);
}

else if(num.equals("2")){

System.out.println("Enter the name : ");
name = scan.next();
bean.setName(name);

System.out.println("Enter the roll Number : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);
jdbc.update(bean);

}

else if(num.equals("3")){

System.out.println("Enter the roll Number for delete : ");
rollNo = scan.nextInt();
bean.setRollNo(rollNo);
jdbc.delete(rollNo);
}
else if(num.equals("4")){

jdbc.findAll();

}
else
{
System.out.println("Please enter 1 , 2 , 3 , 4 only.");
}


ch = scan.next();
}while(ch.equals("y") || ch.equals("Y"));
System.out.println("Successfully Exit.");
System.exit(0);


}
}