Wednesday, August 4, 2010

Javascript : Disable right click

While browsing through my bank account site when i used right click i observed that right click was disabled of that page, off course due to security reasons. May be they do not want to show there internal code implementation. so i was searching on web to get code which can be used to disable right click of the browser.


I got a Javascript code, which can be used to do this. Just copy-page below code in a head section of your page.


<script language="JavaScript">
   
        var message="Right click Disabled!";

        function checkIEBrowser()
        {
            if (event.button==2)
            {
                alert(message);
                return false;
            }
        }

        function checkOtherBrowser(e)
        {
            if (document.layers||document.getElementById&&!document.all)
            {
                if (e.which==2||e.which==3)
                {
                    alert(message);
                    return false;
                }
            }
        }

        if (document.layers)
        {
            document.captureEvents(Event.MOUSEDOWN);
            document.onmousedown=checkOtherBrowser;
        }
        else if (document.all&&!document.getElementById)
        {
            document.onmousedown=checkIEBrowser;
        }

        document.oncontextmenu=new Function("alert(message);return false");

    </script>


Output























Https protocol


Due to security reason we do this thing, i used this code along with Https protocol.
to know about Https protocol click here

Https protocol : SSL Configuration

Secure Socket Layer

SSL, or Secure Socket Layer, is a technology which allows web browsers and web servers to communicate over a secured connection. This means that the data being sent is encrypted by one side, transmitted, then decrypted by the other side before processing. This is a two-way process, meaning that both the server AND the browser encrypt all traffic before sending out data.

Another important aspect of the SSL protocol is Authentication. This means that during your initial attempt to communicate with a web server over a secure connection, that server will present your web browser with a set of credentials, in the form of a "Certificate", as proof the site is who and what it claims to be. In certain cases, the server may also request a Certificate from your web browser, asking for proof that you are who you claim to be. This is known as "Client Authentication," although in practice this is used more for business-to-business (B2B) transactions than with individual users. Most SSL-enabled web servers do not request Client Authentication.

Apache Reference

To know more click here

I used following, to implement Https protocol :

  • JDK 1.6
  • Tomcat 6


1 . Create a certificate keystore:

HTTPS requires an SSL Certificate. When you generate an SSL Certificate, you are creating a keystore file (dot keystore file).

{JAVA_HOME}\bin> keytool -genkey -alias tomcat -keyalg RSA

Eg :

C:\Program Files\Java\jdk1.6.0_21\bin>keytool -genkey -alias tomcat -keyalg RSA
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: madan chaudhary
What is the name of your organizational unit?
[Unknown]: Technology
What is the name of your organization?
[Unknown]: Hewitt
What is the name of your City or Locality?
[Unknown]: Mumbai
What is the name of your State or Province?
[Unknown]: Maharashtra
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=madan chaudhary, OU=Technology, O=Hewitt, L=Mumbai, ST=Maharashtra, C=IN c
orrect?
[no]: y

Enter key password for
(RETURN if same as keystore password):
Re-enter new password:

C:\Program Files\Java\jdk1.6.0_21\bin>

note : Remember your tomcat password, which we will use in our tomcat configuration file ie server.xml

Lets look at a console window

Console Window

 Now check your Home folder ie 

     C:\Documents and Settings\{user home}

     and observe a .keystore file


























2. Configuring Tomcat for using the Keystore file

Now add the following codes in

{CATALINA_HOME}/conf/server.xml

file

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true" keystoreFile="${user.home}/.keystore" keystorePass="your tomcat password"
clientAuth="false" sslProtocol="TLS" />



You change ${user.home} according to your requirement.

Also don't forget to set JAVA_HOME and CATALINA_HOME in environment variable.



Now we are done with our settings now start the tomcat server, if you look at the console it will look something like this
































Now lets create any testing page (htm/jsp etc).
lets say my page is https://localhost:8443/Test/index.jsp

















Monday, August 2, 2010

Java : Read / Write/ Update XLS file using JExcel

Java Excel API - A Java API to read, write, and modify Excel spreadsheets


Java Excel API is a mature, open source java API enabling developers to read, write, and modifiy Excel spreadsheets dynamically.

Lets look at a Simple Example, which can be used for reading, writing and updating Excel (.xls) file, Even it's cell can be formatted according to user requirement.

To know more about Java Excel API click here

In this example we will first create Excel file (Sample.xls) using writeXLSFile() method and then we will read same Excel file (Sample.xls) using readXLSFile() method

For Java Excel API Click here

You will need to Download jxl.jar file


Assuming you have set jxl.jar in classpath


//SimpleJExcelExample.java


import java.io.File;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class SimpleJExcelExample {

public void writeXLSFile()
{
System.out.println("--- writeXLSFile() ---");

try
{
WritableWorkbook workbook = Workbook.createWorkbook(new File("Sample.xls"));

WritableSheet sheet = workbook.createSheet("Sheet1", 0);

WritableFont headerFont = new WritableFont (WritableFont.TIMES, 10,WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE );
WritableCellFormat headerCells = new WritableCellFormat(headerFont);
headerCells.setBackground(Colour.TAN);

int column = 0;

for (int row=0;row <5;row++) {

Label label = new Label(row,column,"Header "+row,headerCells);
label.setCellFormat(headerCells);
sheet.addCell(label);
}

column ++;

WritableFont normalFont = new WritableFont(WritableFont.TIMES, 10);
WritableCellFormat normalCell = new WritableCellFormat(normalFont);

for (int col=column;col <5;col++)
{
for (int row=0;row <5;row++)
{

Label label = new Label(row,col,"cell "+row+" "+col,normalCell);
label.setCellFormat(normalCell);
sheet.addCell(label);
}
}

workbook.write();
workbook.close();

System.out.println("Sample.xls created sucessfully");
}
catch(Exception ee)
{
System.out.println("Exception :: "+ee);
}
}

public void readXLSFile()
{
System.out.println("--- readXLSFile() ---");

try
{
Workbook workbook = Workbook.getWorkbook(new File("Sample.xls"));

// Get the first sheet
Sheet sheet = workbook.getSheet(0);

for(int column = 0; column < sheet.getColumns(); column++)
{
for(int row = 0; row < sheet.getRows(); row++)
{
Cell cell = sheet.getCell(row,column);
System.out.print(cell.getContents());
}
System.out.println();
}
}
catch(Exception ee)
{
System.out.println("Exception :: "+ee);
}
}

public static void main(String[] args) throws Exception
{
SimpleJExcelExample obj = new SimpleJExcelExample();

obj.writeXLSFile();

obj.readXLSFile();
}
}



Console Output


--- writeXLSFile() ---
Sample.xls created sucessfully
--- readXLSFile() ---
Header 0Header 1Header 2Header 3Header 4
cell 0 1cell 1 1cell 2 1cell 3 1cell 4 1
cell 0 2cell 1 2cell 2 2cell 3 2cell 4 2
cell 0 3cell 1 3cell 2 3cell 3 3cell 4 3
cell 0 4cell 1 4cell 2 4cell 3 4cell 4 4


Sample.xls file


Friday, July 30, 2010

Java : Simple Lucene 3.0 example

Apache Lucene is a high-performance, full-featured text search engine library. Here's a simple example how to use Lucene for indexing and searching

To run this example you need to download lucene-3.0.2.zip from http://www.apache.org/dyn/closer.cgi/lucene/java

If you need more information about Lucene go to http://lucene.apache.org/java/docs/index.html

To use Lucene, an application should:

1. Create Documents by adding Fields;
2. Create an IndexWriter and add documents to it with addDocument();
3. Call QueryParser.parse() to build a query from a string; and
4. Create an IndexSearcher and pass the query to its search() method.


Lets create a directory called "AllFiles" that contains text files that we are going to index. We have a directory called "LuceneIndexDirectory". This will hold the index that lucene creates.

Now Lets create few files in "AllFiles" folder which will contain few key words which we will search. Here are the files below.

Look at sample folder structure



Java.txt

String
Object
ArrayList
Hashtable
Integer
Random

SQL.txt

Select
Group by
Where
From
random

Javascript.txt

object
Var
function
random

Now lets look at a simple example SimpleLucenExaple.java

First we will create index of all files in our "LuceneIndexDirectory" folder using createIndex(); method, then we will try to search few key words in our files using searchIndex(""); method

To know about this example lets look at Lucene 3.0.1 API

Assuming you have set lucene-core-3.0.2.jar, lucene-demos-3.0.2.jar in classpath.


/*
SimpleLucenExaple.java
*/

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class SimpleLucenExaple {

String allFiles = "AllFiles";

String luceneIndexDirectory = "LuceneIndexDirectory";

IndexSearcher searcher = null; //the searcher used to open/search the index

Query query = null; //the Query created by the QueryParser
TopDocs hits = null; //the search results

public void searchIndex(String searchString)
{
System.out.println("Searching.... '" + searchString + "'");

try
{
IndexReader reader = IndexReader.open(FSDirectory.open(new File(luceneIndexDirectory)), true);
searcher = new IndexSearcher(reader);

Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30 );//construct our usual analyzer

QueryParser qp = new QueryParser(Version.LUCENE_30 , "contents", analyzer);
query = qp.parse(searchString); //parse the query and construct the Query object

hits = searcher.search(query, 100); // run the query

if (hits.totalHits == 0)
{
System.out.println("No data found.");
}
else
{
for (int i = 0; i < hits.totalHits; i++) 


   Document doc = searcher.doc(hits.scoreDocs[i].doc); //get the next  document 
   String url = doc.get("path"); //get its path field  
   System.out.println("Found in :: "+url); }


catch (Exception e) 

   e.printStackTrace(); 

} 

public void createIndex() 


Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);  
try 
 
    // Store the index in file 

   Directory directory = new SimpleFSDirectory(new File(luceneIndexDirectory));      
   IndexWriter iwriter = new IndexWriter(directory, analyzer, true,MaxFieldLength.UNLIMITED); 
   File dir = new File(allFiles); 

   File[] files = dir.listFiles();  

   for (File file : files) 
   { 
    System.out.println(file.getPath());  
    Document doc = new Document(); 
    
    doc.add(new Field("path", file.getPath(), Field.Store.YES, Field.Index.ANALYZED )); 

    Reader reader = new FileReader(file.getCanonicalPath()); 

    doc.add(new Field("contents", reader)); iwriter.addDocument(doc); 
   }

   iwriter.optimize(); iwriter.close(); 
 } 
catch (Exception e) 


e.printStackTrace();




public static void main(String[] args) 


   SimpleLucenExaple obj = new SimpleLucenExaple(); 
   System.out.println("************Creating Index************"); 
   obj.createIndex(); 
   System.out.println("************Searching************"); 
   obj.searchIndex("Object AND Random"); 
   obj.searchIndex("Object"); 
   obj.searchIndex("random OR Object"); 
   obj.searchIndex("ObjectRandom"); 
   obj.searchIndex("Function"); 
   obj.searchIndex("Group"); 
   obj.searchIndex("form where"); 
}

}  


Console output

************Creating Index************
AllFiles\Java.txt
AllFiles\Javascript.txt
AllFiles\SQL.txt
************Searching************
Searching.... 'Object AND Random'
Found in :: AllFiles\Javascript.txt
Found in :: AllFiles\Java.txt
Searching.... 'Object'
Found in :: AllFiles\Javascript.txt
Found in :: AllFiles\Java.txt
Searching.... 'random OR Object'
Found in :: AllFiles\Javascript.txt
Found in :: AllFiles\Java.txt
Found in :: AllFiles\SQL.txt
Searching.... 'ObjectRandom'
No data found.
Searching.... 'Function'
Found in :: AllFiles\Javascript.txt
Searching.... 'form where'
Found in :: AllFiles\SQL.txt


To know about this example lets look at Lucene 3.0.1 API


Any feedback/comments? Do write me, I would love to answer it.

Monday, February 15, 2010

MS SQL / Oracle : Get all Table / Column names from database

MS SQL

Get all table names of particular database
Query: select NAME from SYSOBJECTS where TYPE = 'U'

Get all column names of a table
Query: SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = '<table name>'

Oracle

Get all table names of particular database
Query: select TABLE_NAME from DBA_TABLES where OWNER like '<database name>'

Get all column names of a table
Query: select COLUMN_NAME from ALL_TAB_COLS where TABLE_NAME ='<table name>'