Thursday 28 February 2013

Disable f5 button and Right click in IE using Javascript

Java Script:

<script type="text/javascript">

var message="";

function clickIE()
 
{if (document.all)
{(message);return false;}}
 
function clickNS(e) {
if
(document.layers||(document.getElementById&&!document.all))
{
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers)
{document.captureEvents(Event.MOUSEDOWN);document.  onmousedown=clickNS;}
else
{document.onmouseup=clickNS;document.oncontextmenu  =clickIE;}
 
document.oncontextmenu=new Function("return false")
window.history.forward(1);
document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler() {
    switch (event.keyCode) {
        case 116 : // 'F5'
            event.returnValue = false;
            event.keyCode = 0;
            window.status = "We have disabled F5";
            break;
    }
}
</script>

Display clock or count down timer in jsp page


<html><head>  
<script>  
<!--  
<%  
String clock = request.getParameter( "clock" );  
if( clock == null ) clock = "180";  
%>  
var timeout = <%=clock%>;  
function timer()  
{  
if( --timeout > 0 )  
{  
document.forma.clock.value = timeout;  
window.setTimeout( "timer()", 1000 );  
}  
else  
{  
document.forma.clock.value = "Time over";  
///disable submit-button etc  
}  
}  
//-->  
</script>  
<body>  
<form action="<%=request.getRequestURL()%>" name="forma">  
Seconds remaining: <input type="text" name="clock" value="<%=clock%>" style="border:0px solid white">  
...  
</form>  
<script>  
<!--  
timer();  
//-->  
</script>  
</body></html>  

//File type should be .JSP it will not work in .HTML types.

Disable back button in browser using javascript


Code Snippet:

<script type="text/javascript">
        window.history.forward();
        function noBack() { 
              window.history.forward(); 
         }
</script>

Download DB values as CSV file with JNDI Connection Pool Method


Context.xml

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="root" password="" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/cdcol"/>

 //This should be added in the servers context,xml file. For example if you are using apache server then the context.xml will be found in C:\apache-tomcat-6.0.26\conf\Context.xml

web.xml

  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

//This should be added in the web.xml of the local project. (Not in server's web.xml).


Program:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class UploadFile extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream output = null;
ByteArrayInputStream fileToDownload = null;
StringBuffer data = new StringBuffer("First Name, Last Name, Mobile Number, Company Name");
data.append("\n");
Connection con = null;
Statement stmt;
    try
     {
        Context ctx=new InitialContext();
        Context envContext = (Context)ctx.lookup("java:comp/env");
        DataSource ds=(DataSource)envContext.lookup("jdbc/TestDB");//TestDB is the Database Name
        con=ds.getConnection();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("Select * from <table_name> where <condition>");
        while(rs.next())  //This is for four columns
        {
        data.append(rs.getString(1));
        data.append(',');
        data.append(rs.getString(2));
        data.append(',');
        data.append(rs.getString(3));
        data.append(',');
        data.append(rs.getString(4));
        data.append('\n');
        }
     }
    catch(Exception e)
     { //Print the stack trace }
    fileToDownload = new ByteArrayInputStream(data.toString().getBytes());
    output = response.getOutputStream();
    response.setContentType("application/csv");
    response.setHeader("Content-Disposition", "attachment; filename=data.csv");//data.csv - Download file name
    response.setContentLength(fileToDownload.available());
    int c;
    while ((c = fileToDownload.read()) != -1)
    {
    output.write(c);
    }
    output.flush();
    output.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// The code can be done in post also
}

} 

Get image dimensions from an URL


This is one of the simplest method to find the dimensions of image.
URL url=new URL("Any web image url");
BufferedImage image = ImageIO.read(url);
int height = image.getHeight();
int width = image.getWidth();
System.out.println("Height : "+ height);
System.out.println("Width : "+ width);

Import data from database in to Excel using java

You can use Apache POI to import data into excel from database. But the easiest way is to download as CSV file. The difference is with CSV file you cannot format the cells but with excel you can format cells as you wish. E.G)Like cell border, cell highlight, fonts these things can be done only if excel download is used. If you no need formatting then you can choose the simplest way CSV download.

ClassNotFoundException com.mysql.jdbc.Driver in eclipse

In Eclipse:
Just copy the MySql-Connector.jar in apache tomcat's lib folder and then remove the jar in project's lib folder, and then, run the project.

In how many different ways can we declare a main method in java?

Ways of declaring main methods in Java:

  1. public static void main(String[] args) or public static void main(String args[])
  2. public static void main(String... args). The positions of public and static may change as the programmer wish. But remember void should always come before main method. You can also use any parameters for the main method but the main with String[] args will only be executed first. You can also execute a java program without a main method. For this you need to make use of static block with a break statement at the end.

What is faster: JDBC or JNDI?

This is what i have found about JNDI and JDBC. 
JNDI: 

  1. This is a technology which works like a telephone directory which is used to search the name on server and data source remotely. 
  2. JNDI creates a connection pool. 
  3. Connection pool is an environment on the server where JNDI and Database encapsulated to for Type4 connectivity. 
  4. Connection parameters will be called only once during server startup. 

JDBC: 

  1. A Java API that enables Java programs to execute SQL statements. 
  2. This allows Java programs to interact with any SQL-compliant database. 
  3. JDBC is similar to ODBC, but is designed specifically for Java programs, whereas ODBC is language-independent. 
  4. JDBC was developed by Sun Microsystems. 
  5. Connection parameters will be called many times depending on the code.

JNDI is faster and efficient.