Tuesday, August 31, 2010

Establishing DataBase Connection in Oracle

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db;

import java.sql.*;

/**
 *
 * @author subinsuresh
 */
public class dbconnection {

    Statement stmt;
    Connection con;

    public void start() {
        try {
            ResultSet rs;
            //Register the JDBC driver for Oracle.
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            /*
             * Define URL of database server for database  on the localhost      
             * with the default port number 1521.      
             */
           String url = "jdbc:oracle:thin:@localhost:1521:serviceID";
            /*
             * Get a connection to the database for a user named root with the password
             * subin
             */
         con = DriverManager.getConnection(url, "root", "subin");

            //Display URL and connection information
            System.out.println("URL: " + url);
            System.out.println("Connection: " + con);
        //Get a Statement object
        stmt = con.createStatement();
        //Query the database, storing the result in an object of type ResultSet
         rs = stmt.executeQuery("SELECT * from tablename");
     } catch (Exception e) {
            e.printStackTrace();
        }//end catch
    }

    public Statement getstatement() throws SQLException {
      stmt=con.createStatement();
      return stmt;
    }
}

Monday, August 30, 2010

Configuring Netbeans with firefox in linux

In Netbeans

Tools--options--general

in that web browser field --- select firefox

and click on edit button

Name Firefox   

Process /usr/local/bin/firefox/firefox

Arguments {URL}


Note : In my linux system firefox is installed in /usr/local/bin/firefox

Inside this there will be one file called firefox, we have to give path up to here
(this is nothing like .exe file in windows)

Sunday, August 29, 2010

Zip and Unzip file in linux

The zip and unzip programs work almost exactly like their cousins PKZIP and PKUNZIP in the DOS environment. You can squash a bunch of files together into a zip file like this:

zip test.zip file1 file2 file3

Then you can extract the original files like this:

unzip test.zip

Wednesday, August 25, 2010

PopUp AlertMessagebox for JSF

In my last post i have written Javascript function for email validation. Today i will be discussing  PopUp AlertMessagebox for JSF
When we develop websites we often have to display to user some alerts if user makes some mistakes
In such cases we can use jsf-components.
Steps to implementation
1) Download  jsf-components.jar..
2)Include this taglib <%@taglib prefix="jc" uri="http://jsf-components" %>
and also add<jc:AlertMessage /> tag after <h:form>tag
3)Add below method .If you are having a java class for common methods
it's better to add this method there for reuseibility
/**
* Add a Message to the Faces Context
* @param msg
*/
public static void showMessage(String msg) {
msg = "" + msg;
FacesMessage fm = new FacesMessage(msg);
FacesContext.getCurrentInstance().addMessage(msg, fm);
}
4)Use it
configure managebean in faces-config.xml
<managed-bean>
<managed-bean-name>userlogin</managed-bean-name>
<managed-bean-class>client.gui.main.Login</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

In JSP paste the below code
<h:outputLabel id="lb_USR_NAME" value="UserName:" styleClass="label"/>
<h:inputText id="tf_USR_NAME" autocomplete="off" value="#{userlogin.tf_USR_NAME}" />
<h:outputLabel id="lb_PASS" value="Password:" styleClass="label"/>
<h:inputText id="tf_PASS" autocomplete="off" value="#{userlogin.tf_PASS}" />
<h:commandButton id="cb_login" value="Login" action="#{userlogin.submit}"/>

In Java Class paste the below code
package client.gui.main;
/**
*
* @author Subin Suresh
*/
public class Login{
public String submit(){
String status = null;
String userName = (String) getTf_USR_NAME().toString();
String passWord = (String) getTf_PASS().toString();
if (((userName.equals("subin"))) && ((passWord.equals("subin")))) {
showMessage("UserName and Password Does not Matches .");
status = "failure";
}else{
status = "success";
}
return status; 
}
}

Download  jsf-components.jar..

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Configuring firefox browser in Linux


In panel you can see web browser icon, right click on it, select properties option
Now you can find "Launch Properties" window, in that "command" field you can browse the Firefox path where Firefox is installed in your system

for ex: /usr/local/bin/firefox/firefox

or u can view simply htmlview %u

Tuesday, August 24, 2010

Deleting folders/sub folders/files in linux

rm myfile.txt

Remove the file myfile.txt without prompting the user.

rm -r directory

Remove a directory, even if files existed in that directory. 

Note: if you use rm to remove a file, it is usually possible to recover the contents of that file. If you want more assurance that the contents are truly unrecoverable, consider using shred.

rmdir mydir - removes the directory mydir

shred myfile.txt

Permanently deleted and makes the file myfile.txt unrecoverable (unless stored elsewhere or on a backup).

Monday, August 23, 2010

ServerSide Email Validator

In my last post i have written Javascript function for email validation. In this i will be discussing about ServerSide Email Validator. For application to be safe it is necessary to have both client and server side validators.
Steps for implementing ServerSide Email Validator
1. In jsp define the email component in the following way
  <h:outputLabel id="lb_MAIL_ID" value="Mail ID:" styleClass="label"/>
<h:inputText id="tf_MAIL_ID" autocomplete="off" value="#{userlogin.tf_MAIL_ID}" />
2. In java class get email component value and apply serverside email validator for it as shown below

/*
* Getting the tf_MAIL_ID component value
*/
String emailId = (String) getTf_MAIL_ID().toString();
 if (emailId == null || !emailId.matches("^[A-z0-9_\\-\\.]+[@][A-z0-9_\\-]+([.][A-z0-9_\\-]+)+[A-z]{2,4}")) {
             System.out.println("Please enter Valid Email-Id");
        }

Instead of  using  System.out.println you can use PopUp AlertMessagebox for JSF  as it clear idea for the user who is using it. 

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Java program to Get Heap Size of JVM

Java program to Get Heap Size of JVM 

public class GetHeapSize {
        public static void main(String[]args){
    
            //Get the jvm heap size.
            long heapSize = Runtime.getRuntime().totalMemory();
    
            //Print the jvm heap size.
            System.out.println("Heap Size = " + heapSize);
        }
    }

Sunday, August 22, 2010

Deploying a war file(project) in Tomcat web server in Windows

Steps for Deploying a project in Tomcat web server in Windows

1.Open the NetBeans IDE
2.Open the project
3.Right click on the project in projects tab
4.Click on the 'clean and build' option
5.Click on 'Deploy' option
6.Now go to folder where your project is reside in your system
say D:\projects\nameoftheproject\dist folder
7.You can find the nameoftheproject.war file in dist folder
8.Open the tomcat foder in your system say c:\program files\ApacheSoftwareFoundation\Tomcat6.0
9.Open the logs folder
10.Delete all the log files which are present upto now
11.Open the work folder--->catalina--->localhost
12.Delete all the folders(all these folders are temporary folders created by the tomcat)
13.Open the webapps folder
14.Delete the war file and project folder(if it is already present, before this you need to stop the tomcat server)
15.Copy the war file and paste in the c:\program files\ApacheSoftwareFoundation\Tomcat6.0\webapps folder
16.Run the project in the firefox with appropriate url say:http://localhost:8080/nameoftheproject

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Friday, August 20, 2010

Configuring tomcat in windows

Download 32-bit Windows zip file which is binary flavour of apache tomcat

This flavour comes in zip file, which runs on on both 32 and 64 bit Windows platforms
Extract the zip file, now you will get apache tomcat software

Where you can find startup.bat and shutdown.bat files in apache-tomcat-6.0.26\bin folder

Copy the downloaded apache tomcat folder and paste in appropriate folder say c:\program files

Now configure the apache tomcat in Environment Variables

Right click on the My Computer icon

Go to Advanced---> Environment Variables

In System Variables create a new system variable called CATALINA_HOME and value is c:\program files\apache-tomcat-6.0.26

In System Variables select path variable and click on Edit button and append the following one

%CATALINA_HOME%\bin;

if you want to run apache tomcat as a service in windows

download 32-bit/64-bit Windows Service Installer

after downloading you can see a .exe file

by clicking on that file you can install apache tomcat in your system

while installing it asks you for full or custom installation, choose depends on your requirement

and after it asks you java path which is installed on your system

Note: java software is mandatory to run the apache tomcat

and after installing successfully configure in Environment Variables

Thursday, August 19, 2010

Increasing Heap size of Java

Java heap is the heap size allocated to JVM applications which takes care of the new objects being created. If the objects being created exceed the heap size, it will throw an error saying memoryOutofBound

Java's default heap size limit is 128MB
. If you need more than this, you should use the -Xms and -Xmx command line arguments when launching your program:

java -Xms -Xmx


Java programs executes in JVM uses Heap of memory to manage the data. If your Java program requires a large amount of memory, it is possible that the virtual machine will begin to throw OutOfMemoryError instances when attempting to instantiate an object. The default heap size if 1 MB and can increase as much as 16 MB.

Setting/Increase JVM heap size

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

Following are few options available to change Heap Size.

1    -Xms        set initial Java heap size
2    -Xmx
       set maximum Java heap size
3    -Xss
        set java thread stack size

For example, you can set minimum heap to 64 MB and maximum heap 256 MB for a Java program HelloWorld.

java -Xms64m -Xmx256m HelloWorld

Getting / Reading default heap size

It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.
    public class GetHeapSize {
        public static void main(String[]args){
    
            //Get the jvm heap size.
            long heapSize = Runtime.getRuntime().totalMemory();
    
            //Print the jvm heap size.
            System.out.println("Heap Size = " + heapSize);
        }
    }

Set Multiple Websites As Firefox Browser Home Page

Open your favorite websites such as Gmail, Facebook, Google, Twitter in Firefox Browser .


Now go to Tools > Options. In “General” tab, click on “Use Current Pages”. See the screenshot given below.
firefox-pages
Press OK. That’s it. Now Firefox will load all those website whenever it starts.

Wednesday, August 18, 2010

Creating DataBase Connection in MySQL

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db;

import java.sql.*;

/**
 *
 * @author subinsuresh
 */
public class dbconnection {

    Statement stmt;
    Connection con;

    public void start() {
        try {
            ResultSet rs;
            //Register the JDBC driver for MySQL.
            Class.forName("com.mysql.jdbc.Driver");
            /*
             * Define URL of database server for database named ems on the localhost      
             * with the default port number 3306.      
             */
           String url = "jdbc:mysql://localhost:3306/ems";
            /*
             * Get a connection to the database for a user named root with the password
             * subin, which is password spelled backwards.      
             */
         con = DriverManager.getConnection(url, "root", "subin");

            //Display URL and connection information
            System.out.println("URL: " + url);
            System.out.println("Connection: " + con);
        //Get a Statement object
        stmt = con.createStatement();
        //Query the database, storing the result in an object of type ResultSet
         rs = stmt.executeQuery("SELECT * from tablename");
     } catch (Exception e) {
            e.printStackTrace();
        }//end catch
    }

    public Statement getstatement() throws SQLException {
      stmt=con.createStatement();
      return stmt;
    }
}

Tuesday, August 17, 2010

Bean Scopes in JSF

There are three types of scopes for the JSF backing beans.

   1. Request Scope
   2. Session Scope
   3. Application Scope

Request:

Objects with this scope are visible from the start of the request until the end of the request. Request scope starts at the beginning of a request and ends when the response has been sent to the client. If the request is forwarded, the objects are visible in the forwarded page, because that page is still part of the same request/response cycle. Objects with request scope can use other objects with none, request, session, or application scope.

Session:

An object with session scope is visible for any request/response cycle that belongs to a session. Objects with this scope have their state persisted between requests and last until the object or the session is invalidated. Objects with session scope can use other objects with none, session, or application scope.

Application:

An object with application scope is visible in all request/response cycles for all clients using the application, for as long as the application is active. Objects with application scope can use other objects with none or application scope.

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Monday, August 16, 2010

Creating users for Oracle

Create User
SQL> CREATE SUBIN(USERNAME)IDENTIFIED BY SUBIN(PASSWORD);
User created.


Grant  permissions 
SQL> GRANT CONNECT, RESOURCE,DBA to SUBIN(USERNAME);
Grant succeeded.
 

Commit
SQL> COMMIT;

Sunday, August 15, 2010

JavaScript To Copy Text From One Field To Another

Often when creating a form on a web page, you need your customers to fill out a field such as a mailing address, as well as a billing address. Instead of having your customers fill out the form twice, you can use JavaScript to copy the form's data from one field to another.
Mailing Address 

Name:  
City:  
 Check this box if Billing Address and Mailing Address are the same.Billing Address 

Name:  
City: 


The JavaScript used to achieve the effect looks like this:


function FillBilling(f) {
  if(f.billingtoo.checked == true) {
    f.billingname.value = f.shippingname.value;
    f.billingcity.value = f.shippingcity.value;
  }
}
To add more fields, just add to the parameters shown above...like this:
f.billingstate.value = f.shippingstate.value;
    f.billingzip.value = f.shippingzip.value;
 The HTML for the form you will use looks like this:


 <b>Mailing Address</b>
<br><br>
<form>
<input type="text" name="shippingcity">
<br>
<input type="checkbox" name="billingtoo" onclick="FillBilling(this.form)">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<P>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname">
<br>
City:
<input type="text" name="billingcity">
</form>












Apple iPhone 4 Price, Specifications and Launch date India


Apple iPhone 4, the 4th generation of the iPhone that uses the iPhone OS 4.0 is recently released in the States. The features of the iPhone4 (latest version) include a new h/w design, 5 Mega Pixel camera with High Definition video recording, highly improved display, 1GHZ apple A4 chip, innovative applications, long battery life, gyroscope, and front camera for making video calls. The iPhone OS 4.0 (iOS 4.0) will be pre-installed.
Apple iPhone 4 Photos



iPhone 4 Hardware Specifications:

  • Apple iPhone 4 has the display of 3.5 inch similar to that of old models of iPhone such as 3GS and iPhone 3G.
  • The front side display is covered by glass which is 30X stronger than plastic.
  • A better screen resolution of 960×640 pixels and a contrast ratio of 800:1
  • The OLED display in iPhone 4 will help improve the pixel depth to 336 pixels/inch, thus providing 4X quality for watching pictures and videos.
  • The rear panel of iPhone 4 is wrapped up by glass and the remaining sides have stainless steel finishing.
  • It is said to be one of the thinnest phones on earth measuring only 9.3mm (24% smaller than iPhone3GS).
  • Apple iPhone 4 also larboards a gyroscope component, with an accelerometer assists new applications and games needing this facility.
  • The volume controls are rested in the left side, along with a mute button.
  • A 3.5 mm earphone jack, additional noise cancellation mic, and a sleep-wake push button at the upper side.
  • The underside of iPhone 4 includes normal Apple USB and dock connectors.
  • The main camera of 5MP with LED flash supports 5X digital zoom and records HD video at 720p.
  • Apple uses 1GHZ A4 chip for all iPhone 4 models, which supercharges the browsing, multimedia speeds and overall user experience of the mobile phone.
Apple has taken utmost care in enhancing the battery life of iPhone 4.
Battery Life:

  • 6 hours – 3G browsing,
  • 7 hours – 3G calling
  • 10 hours – WI-Fi browsing & videos
  • 40 hours – music.
Other salient features of iPhone 4 include Quad band 3G at 7.2 Mbps, Bluetooth with A2DP, GPS, WiFi, etc. iPhone is currently available in two colors, white and black.
Apple iPhone 4 Software Features:

  • Apple declared a new iMovie application program for editing videos from their device worth 5$, which can separately be purchased from their app store.
  • Zynga, NetFlix and Activision announced Hero applications for iOS [iPhone OS 4.0] such as Farmville, Netflix and Guitar.
  • iPhone OS 4.0 supports multi-tasking, folder view, iBook support, iAd support.
Apple iPhone 4 India Price and India Launch Date:

The 16GB iPhone 4 in the States is available at 199$ and 32GB at 299$ with 2 year contract. Existing AT&T iPhone users can upgrade to iPhone 4.
Apple iPhone 4 will be made available in India by September 2010. The present cost of iPhone 3GS in India is INR 36,000 for 16GB and INR 41,000 for 32GB model. So according to the estimates, iPhone 4 when launched in India, would cost around 38,000 to 45,000 INR. You can purchase iPhone 4 from Ebay India website or from the global seller for around Rs.60,000/- now and get it delivered in India. Otherwise you’ll have to wait until September 2010 for Apple to launch iPhone 4 officially in India. Watch out for official rates and supported mobile carriers.
   
 

Friday, August 13, 2010

How To Get Lyrics Of Music Video You Watch On YouTube Video [Chrome Extension]

YouTube is a great source of watching videos. Though there are other source available such as Myspace and Last.fm but I prefer watching music videos on YouTube. One problem with this video is its lyrics. It’s rare that any user upload lyrics along with the video. To find the lyrics I move to lyrics side.
YouTube Music Video Lyrics is a nice Chrome extension that lets you watch lyrics along with YouTube music video on the same tab.
Download Youtube Music Video Lyrics for Google Chrome.


Click Install Button



After installation, a small YouTube lyrics icon will appear on the extension bar.



 Now go to YouTube website and open any music video you like. After the video starts playing, click on the YouTube lyrics icon on the extension bar.

A small pop up appears, displaying the lyrics of the song. You can enjoy both song and lyrics on the same tab. No need to switch from current tab to watch lyrics. Nice. Isn’t it?


While using this extension, I saw some flaws. It displayed wrong lyrics of the song. It happens few times. That’s the biggest loop hole of the extension. To get the correct lyrics of the music video you might need to switch to other video song and then try again the extension. There is no search box in the pop up panel to search the correct song.
Download Youtube Music Video Lyrics for Google Chrome.

Thursday, August 12, 2010

Indian History..

Just read what INDIA was as per LORD MACAULAY on his statement on 2nd february 1835 , in the last snap. That would really shock us
Old Photographs from Indian History


The daughter of an Indian maharajah seated on a panther she shot, sometime during 1920s. 
 


A British man gets a pedicure from an Indian servant .


The Grand Trunk Road , built by Sher Shah Suri, was the main trade route from Calcutta to Kabul .

A rare view of the President's palace and the Parliament building in New Delhi .

Women gather at a party in Mumbai ( Bombay ) in 1910 .


A group from Vaishnava, a sect founded by a Hindu mystic. His followers are called Gosvami-maharajahs 


An aerial view of Jama Masjid mosque in Delhi , built between 1650 and 1658. 


The Imperial Airways 'Hanno' Hadley Page passenger airplane carries the England to India air mail, stopping in Sharjah to refuel .


Javascript function for email validation

 Email Validator In JSF Using JavaScript
In Javascript write the following function

function emailcheck(str) {
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
        alert("Invalid E-mail ID")
        return false
    }
    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
        alert("Invalid E-mail ID")
        return false
    }
    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(at,(lat+1))!=-1){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(dot,(lat+2))==-1){
        alert("Invalid E-mail ID")
        return false
    }

    if (str.indexOf(" ")!=-1){
        alert("Invalid E-mail ID")
        return false
    }

    return true
}

function validateUser()
{
    var flag = true;   
    var mailid = document.frmuser.tf_USER_MAILID;//frmuser is the form id

    if(mailid != null && mailid.value == "" ){
        flag = false;
        alert ("Mailid cannot be Empty...");
    }

    if (flag ) {
            flag =  emailcheck(mailid.value);
        }

    return flag;
}

In JSP:

Include javascript file into jsp using following code  
Call the javascript function using following code
<h:commandButton id="bt_SAVE" value="SAVE" onclick="javascript:return validateUser();" action="#{createuser.saveUserDetails}" style="font-size:16;font-weight:bold"/>

JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF,PopUp AlertMessagebox for JSF and more.....

Monday, August 9, 2010

YouTube Song Downloader for downloading YouTube Video in MP3 And Other Formats

If you are crazy about your favorite song but you can’t find it on internet to download then you don’t need to be worry. YouTube hosts almost every new and old songs. You can easily view and download it with the help of browser extensions and third party software. However, if you want to download youtube songs   in MP3, MP4, or WMV audio formats then there is a nifty tool known as YouTube Song downloader which performs the task pretty well.
It is a free application which downloads YouTube videos and convert them easily into various sound formats. The song can be played on your computer or your favorite music player such as iPod or MP3 player.

youtube-song-download-plus
To use the tool, download and install it on your computer. The application has easy to use interface. There is a search box available through which you can easily search for your favorite music video by entering the keyword. Also you can directly paste the URL of the video song.
You can anytime check the current status of active download and also the video you downloaded previously.  You can also preview files immediately, just select the search item and click on the play button next to it.
  • Search and download YouTube videos quickly and easily.
  • Save files as audio (MP3) or video file (AVI, MP4, FLV)
  • Outstanding HD quality.
  • Available for Windows XP, Vista and Windows 7
  • Free to use.
Download YouTube Song Downloader Software.