Choose Your Language

Saturday 29 June 2013

Dictionary application using JAVA, JSP, AJAX and MySql with source code

Project Structure:

index.jsp

<%--
    Document   : index
    Created on : 29 Jun, 2013, 11:03:21 PM
    Author     : Aravind Sankaran
--%>

<%@page import="com.dictionary.common.LoadMyProperties"%>
<%@page import="com.dictionary.bean.DictionaryBean"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
DictionaryBean bean=new DictionaryBean();
            LoadMyProperties loadMyProperties=new  LoadMyProperties();          
            bean=loadMyProperties.getMyPropertiesFile(bean);
            String typeaword=bean.getTypeaword();
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Dictionary</title>
        <script type="text/javascript">

function loadXMLDoc1()
{
var xmlhttp;

var word=document.getElementById("word").value;

var urls="getmeaning.jsp?word="+word;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4)
    {
       
        document.getElementById("err1").innerHTML=xmlhttp.responseText;

    }
  }
xmlhttp.open("GET",urls,true);
xmlhttp.send();
}
</script>
    </head>
    <body>
        <table>
            <tr>
            <td>
          <form method="post" action="/Dictionary/Login">
          <table>
                  <tr>
                      <td></td><td></td><td><b><a href="" style="text-decoration: blink;">Login here&nbsp;</a></b></td>
                  </tr>
                  <tr>
                      <td>User Name</td><td>&nbsp;</td><td><input type="text" name="username"></td>
                  </tr>
                  <tr>
                      <td>Password</td><td>&nbsp;</td><td><input type="password" name="password"></td>
                  </tr>
                  <tr><td>&nbsp;</td>
                      <td></td><td><input type="submit" value="login" ></td>
                  </tr>
              </table>
          </form>
              </td>
              </tr>
        </table>
        <p>
            <center>
                <table width="30%" border="0">
                <tr>
                    <td>&nbsp;</td>
                    <td><b>Dictionary: </b></td>  
                    <td><b>The universe in alphabetical order</b></td>
                    <td>&nbsp;</td>   
                </tr><br><br>
                <tr>
                    <td>&nbsp;</td>
                    <td></td>  
                    <td></td>
                    <td>&nbsp;</td>   
                </tr><br><br>
                <tr>
                    <td>&nbsp;</td>
                    <td><b><%=typeaword%></b></td>  
                    <td><input type="text" name="word" id="word"  onkeyup="loadXMLDoc1()"></td>
                    <td>&nbsp;</td>
                </tr> 
                </table>
            </center><br><br>
            <span id="err1"> </span>
        </p>
       
</body>
</html>

getmeaning.jsp

<%--
    Document   : getmeaning
    Created on : 29 Jun, 2013, 11:26:25 PM
    Author     : Aravind Sankaran
--%>

<%@page import="com.dictionary.common.LoadMyProperties"%>
<%@page import="com.dictionary.bean.DictionaryBean"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%String word=request.getParameter("word");%>

<%! static Connection con;%>

<%
DictionaryBean bean=new DictionaryBean();
            LoadMyProperties loadMyProperties=new  LoadMyProperties();          
            bean=loadMyProperties.getMyPropertiesFile(bean);
            String dbUrl=bean.getDbUrl();
            String dbName=bean.getDbName();
            String dbUserName=bean.getDbUserName();
            String dbPassword=bean.getDbPassword();
            String driverName=bean.getDriverName();
 String typeaword=bean.getTypeaword();
 String errorMessage=bean.getErrorMessage();
 String newline=bean.getNewline();
 String outputmeaning=bean.getOutputmeaning();
Class.forName(driverName);
con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("select * from wordmeaning where word like '"+word+"%'");

%>

<!DOCTYPE html>
<%

 if(rs.next())
                    { 
    String words=rs.getString("word");    
    String meanings=rs.getString("meaning");
                        out.println("<center>");
                        out.println("<table width='30%'>");
                        out.println("<tr>");
                        out.println("<td><b><font size='5' color=black>"+words+":-</font></b></td>");
                        out.println("<td>&nbsp;&nbsp;&nbsp;</td>");
                        out.println("<td><b><font color=red></font></b></td>");                       
                        out.println("</tr>");
                       
                        out.println("<tr>");
                        out.println("<td></td>");
                        out.println("<td>&nbsp;&nbsp;&nbsp;</td>");
                        out.println("<td></td>");                       
                        out.println("</tr>");
                       
                        out.println("<tr>");
                        out.println("<td><b><font color=black>"+outputmeaning+"</font></b></td>");
                        out.println("<td>&nbsp;&nbsp;&nbsp;</td>");
                        out.println("<td><b><font color=red>"+meanings+"</font></b></td>");                       
                        out.println("</tr>");
                        out.println("</table>");
                        out.println("<center>");
                       
                        out.println("<tr>");
                        out.println("<td></td>");
                        out.println("<td><font color=black>"+newline+"</font></b></td>");
                        out.println("<td></td>");                       
                        out.println("</tr>");
                 
}else {
                        out.println("<center>");
                        out.println("<table>");
                        out.println("<tr>");
                        out.println("<td><b><font color=black>"+errorMessage+"</font></b></td>");                                              
                        out.println("</tr>");
                        out.println("</table>");
                        out.println("</center>");
                    }
rs.close();
s.close();
con.close();

%>

admin.jsp

<%--
    Document   : admin
    Created on : 29 Jun, 2013, 11:28:15 PM
    Author     : Aravind Sankaran
--%>

<%@page import="com.dictionary.common.LoadMyProperties"%>
<%@page import="com.dictionary.bean.DictionaryBean"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% String un=request.getParameter("un");%>
<%
DictionaryBean bean=new DictionaryBean();
            LoadMyProperties loadMyProperties=new  LoadMyProperties();          
            bean=loadMyProperties.getMyPropertiesFile(bean);
            String typeaword=bean.getTypeaword();
%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <p>
          <form method="post" action="/Dictionary/AddNewWords">       
     
      <center>
              <table width="50%" border="0">
              <tr>
                  <td>&nbsp;</td>
                  <td><b>Word</b></td>  
                  <td><input type="text" name="word"  ></td>
                  <td>&nbsp;</td>
              </tr>
              <tr>
                  <td>&nbsp;</td>
                  <td><b></b></td>  
                  <td></td>
                  <td>&nbsp;</td>
              </tr>
              <tr>
              <td>&nbsp;</td>
              <td><b>Meaning</b></td>  
              <td><textarea name="meaning" rows="5" cols="18"></textarea></td>
              <td>&nbsp;</td>
              </tr>
              <tr>
              <td>&nbsp;</td>
              <td><b></b></td>  
              <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="SUBMIT"></td>
              <td>&nbsp;</td>
              </tr> 
              </table>
              </form>
        </p>
    </body>
</html>

com.dictionary.bean package

1.DictionaryBean.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dictionary.bean;

/**
 *
 * @author Aravind Sankaran
 */
public class DictionaryBean {
   
private String  userName;
private String userPassword;
private String  dbName;
private String dbUserName;
private String dbPassword;;
private String dbUrl;
private String word;
private String meaning;
private String driverName;
private String typeaword;
private String errorMessage;
private String newline;
private String outputmeaning;
private boolean valid;
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getDbName() {
        return dbName;
    }

    public String getDriverName() {
        return driverName;
    }

    public void setDriverName(String driverName) {
        this.driverName = driverName;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getNewline() {
        return newline;
    }

    public void setNewline(String newline) {
        this.newline = newline;
    }

    public String getOutputmeaning() {
        return outputmeaning;
    }

    public void setOutputmeaning(String outputmeaning) {
        this.outputmeaning = outputmeaning;
    }

    public String getTypeaword() {
        return typeaword;
    }

    public void setTypeaword(String typeaword) {
        this.typeaword = typeaword;
    }

    public void setDbName(String dbName) {
        this.dbName = dbName;
    }


    public String getDbPassword() {
        return dbPassword;
    }

    public void setDbPassword(String dbPassword) {
        this.dbPassword = dbPassword;
    }

    public String getDbUrl() {
        return dbUrl;
    }

    public void setDbUrl(String dbUrl) {
        this.dbUrl = dbUrl;
    }

    public String getDbUserName() {
        return dbUserName;
    }

    public void setDbUserName(String dbUserName) {
        this.dbUserName = dbUserName;
    }

    public String getMeaning() {
        return meaning;
    }

    public void setMeaning(String meaning) {
        this.meaning = meaning;
    }

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }
}

com.dictionary.common package 
1. AddNewWords.java

package com.dictionary.common;
import com.dictionary.bean.DictionaryBean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AddNewWords extends HttpServlet {
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       // processRequest(request, response);
        String word=request.getParameter("word");
        String meaning=request.getParameter("meaning");
        DictionaryBean db=new DictionaryBean();
        db.setWord(word);
        db.setMeaning(meaning);
      
        db=Operations.addNewWord(db);
        if(db.isValid()){
            HttpSession session=request.getSession(true);
            session.setAttribute("admin", db);
            response.sendRedirect("admin.jsp");
        }else{
            response.sendRedirect("index.jsp");
        }
    }

}

2.DbConnect.java

package com.dictionary.common;
import com.dictionary.bean.DictionaryBean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Aravind Sankaran
 */
public class DbConnect {
static Connection con=null;      
    public static Connection getConnection(){
        try{
            DictionaryBean bean=new DictionaryBean();
            LoadMyProperties loadMyProperties=new  LoadMyProperties();          
            bean=loadMyProperties.getMyPropertiesFile(bean);
            String dbUrl=bean.getDbUrl();
            String dbName=bean.getDbName();
            String dbUserName=bean.getDbUserName();
            String dbPassword=bean.getDbPassword();
            String driverName=bean.getDriverName();
            Class.forName(driverName);
            try{
            con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
            System.out.println("connection occured");          
            }
            catch(SQLException se){
               
            }
        }catch(ClassNotFoundException e){
           
        }
      return con;
    }
}

3.LoadMyProperties.java

package com.dictionary.common;
import com.dictionary.bean.DictionaryBean;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 *
 * @author Aravind Sankaran
 */
public class LoadMyProperties {
 Properties configProp=new Properties();
     public DictionaryBean getMyPropertiesFile(DictionaryBean myBean){   
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("com/dictionary/resources/db.properties");
        try {
          configProp.load(in);
          String dbUrl=configProp.getProperty("dbUrl");
          String dbName=configProp.getProperty("dbName");
          String dbUserName=configProp.getProperty("dbUserName");
          String dbPassword=configProp.getProperty("dbPassword");
        
          String driverName=configProp.getProperty("driverName");
          String typeaword=configProp.getProperty("typeaword");
          String errorMessage=configProp.getProperty("errorMessage");
          String newline=configProp.getProperty("newline");
          String outputmeaning=configProp.getProperty("outputmeaning");
         
          myBean.setDbUrl(dbUrl);
          myBean.setDbName(dbName);
          myBean.setDbUserName(dbUserName);
          myBean.setDbPassword(dbPassword);
         
          myBean.setDriverName(driverName);
          myBean.setTypeaword(typeaword);
          myBean.setErrorMessage(errorMessage);
          myBean.setNewline(newline);
          myBean.setOutputmeaning(outputmeaning);
          myBean.setValid(true);
        } catch (IOException e) {
            e.printStackTrace();
        }      
      
        return myBean;
    }
}

 4.Login.java

package com.dictionary.common;
import com.dictionary.bean.DictionaryBean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 public class Login extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      //  processRequest(request, response);
        String userName=request.getParameter("username");
        String userPassword=request.getParameter("password");
        DictionaryBean db=new DictionaryBean();
        db.setUserName(userName);
        db.setUserPassword(userPassword);      
        db=Operations.login(db);
        if(db.isValid()){
            HttpSession session=request.getSession(true);
            session.setAttribute("admin", db);
            String un=db.getUserName();
            response.sendRedirect("admin.jsp?un="+un);
        }else{
            response.sendRedirect("index.jsp");
        }
    }
}

5. Operations.java

package com.dictionary.common;
import com.dictionary.bean.DictionaryBean;
import java.sql.*;

/**
 *
 * @author Aravind Sankaran
 */
public class Operations {
 public static DictionaryBean login(DictionaryBean bean){
        String userName=bean.getUserName();
        String userPassword=bean.getUserPassword();
        String query="select * from login where username='"+userName+"' AND password='"+userPassword+"'";
        Connection con=DbConnect.getConnection();
        try {
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery(query);
            boolean more=rs.next();{
            if(!more){
                System.out.print("no more records");
                bean.setValid(false);
            }else if(more){
             
               String username=rs.getString("username");
               String password=rs.getString("password");
               bean.setUserName(username);               
               bean.setUserPassword(password);
               bean.setValid(true);
            }
        }
        } catch (SQLException ex) {
           System.out.println("error occured in Login Operations");
        }
        return bean;
    }
  
    public static DictionaryBean addNewWord(DictionaryBean bean){
        String word=bean.getWord();
        String meaning=bean.getMeaning();
        PreparedStatement ps= null;

        String query="insert into wordmeaning(word,meaning) values(?,?)";
        Connection con=DbConnect.getConnection();
        try {
            ps=(PreparedStatement) con.prepareStatement(query);
            ps.setString(1, word);
            ps.setString(2, meaning);           
            ps.executeUpdate();
         
            bean.setWord(word);         
            bean.setMeaning(meaning);
            bean.setValid(true);
        } catch (SQLException ex) {
           System.out.println("error occured in adding new word ");
        }
        return bean;
    }
}
}
com.dictionary.resources  package

db.properties

dbUrl=jdbc:mysql://localhost:3306/dictionary?
dbName=dictionary
dbUserName=root
dbPassword=root
driverName=com.mysql.jdbc.Driver
typeaword=Type a word:
errorMessage=If a word in the dictionary were misspelled, how would we know?
newline=-----------------------
outputmeaning=Meaning:

jar file:

mysql-connector-java-3.1.14-bin.jar

Output:




Friday 28 June 2013

Dictionary application using JAVA, JSP, AJAX and MySql


Home Page



AdminHome



compile a java program using another java program

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompileAnotherJavaProgram {
    public static void main ( String [] a) {
        JavaCompiler compiler=ToolProvider.getSystemJavaCompiler();
        int compilerResult=compiler.run(null, null, null, "src/packagename/Hello.java");
        System.out.println("Compiler Result Code is "+compilerResult);
    }
}

public class Hello {
   public static void main(String s[]){
       System.out.println("Hello");
   }
}

output:
Compiler Result Code is  0// only if there is no error
Compiler Result Code is  1// only if there is error




Java Program to print Yesterdays Date and Time

import java.util.Calendar;
import java.util.Date;

public class YesterdaysDateTime {
    public static void main(String a[]){
        Calendar calendar = Calendar.getInstance();
        Date today = calendar.getTime();
        calendar.add(Calendar.DAY_OF_YEAR, -2);
        Date yesterday = calendar.getTime();    
        System.out.println("Today's Date Time is  "+today);
        System.out.println("Yesterdays's Date Time is "+yesterday);          

    }
}

Thursday 27 June 2013

Java Program to print Tomorrows Date and Time

import java.util.Calendar;
import java.util.Date;

public class TomorrowsDateTime {
    public static void main(String a[]){
        Calendar calendar = Calendar.getInstance();
        Date today = calendar.getTime();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        Date tomorrow = calendar.getTime();         
        System.out.println("Today's Date Time is  "+today);
        System.out.println("Tomorrow's Date Time is  "+tomorrow);         
    }
}

output:
Today's Date Time is  Thu Jun 27 22:26:44 IST 2013
Tomorrow's Date Time is  Fri Jun 28 22:26:44 IST 2013

How to capture screenshot and save it to a file using Java

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.util.Date;
public class ScreenShot {
    public static void main(String a[]) throws Exception{
        ScreenShot screenShot=new ScreenShot ();
        Date date=new Date();
        String time=String.valueOf(date.getTime());
        String fileName="C:\\folderName\\screenshot"+time+".png";
        screenShot.captureScreen(fileName);
    }
   public void captureScreen(String fileName) throws Exception {

   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));

}
}

How to Generate a Password Protected PDF Document Uing java

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.util.Calendar;
import java.util.Locale;
import org.joda.time.DateTime;

public class GeneratePDFWithPassword {
   
private static String USER_PASS = "aravind";

private static String OWNER_PASS = "aravind";    
    
    public static void main(String[] args) {
        try {
       
            DateTime dateTime = new DateTime();
           
            String hour =String.valueOf(dateTime.getHourOfDay());
            String minute =String.valueOf(dateTime.getMinuteOfHour());
            String second =String.valueOf(dateTime.getSecondOfMinute());
            String millisecond =String.valueOf(dateTime.getMillisOfSecond());
           
            String day = dateTime.dayOfMonth().getAsText();           
            String monthName = dateTime.monthOfYear().getAsText();
            String yearName = dateTime.year().getAsText();
           
            String date=day+"-"+monthName+"-"+yearName+"  "+hour+"hrs-"+minute+"min-"+second+"sec-"+millisecond+"msec";           
           
             OutputStream file = new FileOutputStream(new File("C:\\folderName\\report_"+date+".pdf"));

            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, file);

            writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);

            document.open();
            document.add(new Paragraph("Welcome Aravind"));           
            document.add(new Paragraph(new Date().toString()));

            document.close();
            file.close();
       
    }
       
        catch (Exception e) {

            e.printStackTrace();
        }
    }
}

jar file needed:
itextpdf-5.2.1
bcmail-jdk16-1.46.jar
bcprov-jdk16-1.46.jar
bctsp-jdk16-1.46.jar

joda-time-2.2.jar
joda-time-2.2-javadoc.jar
joda-time-2.2-sources


Monday 24 June 2013

Java program to play music on system default music player

public class PlayMusicWithJava {
   
 public static void main(String args[])
    {
        String windowsMediaPlayer="\"%programfiles%\\Windows Media Player\\wmplayer.exe\"";
        String songPath="C:\\mymusic\\salsa.mp3"; // mymusic is the folder name
        try
        {     
        Runtime.getRuntime().exec("cmd /c start "+windowsMediaPlayer+" "+songPath);
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Sunday 23 June 2013

create a software that will speak what you type

Open a Notepad
Write this code on that

Dim msg, sp
msg=InputBox("Enter your text here that will speak to you"
Set sp=CreateObject("sapi.spvoice")
sp.Speak msg

Save it as talktome.vbs

Double click on the saved  file to run software.



Anything you enter in textbox & click ok will be spoken.

Thursday 20 June 2013

Multi language support web application using AJAX, Properties file

Project Structure


Step 1: Create a Web Application using netbean IDE

Step 2: Create 3 packages namely
2.a. com.mybean
2.b. com.resources
2.c. com.dao

Step 3: Create a Class Named MyBean under  com.mybean package


 package com.mybean;

/**
 *
 * @author Aravind Sankaran
 */

public class MyBean {
 private String firstName;
 private String middleName;
 private String lastName;  
 private String language;
 private String welcome;
 private boolean valid;
    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
    public String getWelcome() {
        return welcome;
    }

    public void setWelcome(String welcome) {
        this.welcome = welcome;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
   
    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
  
}




Step 4: Create two properties file config under  com.resources package with names en and ma
4.a. Right click  com.resources
4.b. New
4.c. properties file

paste below text on en.properties file

# To change this template, choose Tools | Templates
# and open the template in the editor.
welcome=Welcome
firstname=Aravind
middlename=Sankaran
lastname=Nair


paste below text on ma.properties file
# To change this template, choose Tools | Templates
# and open the template in the editor.
welcome=à´¸്à´µാà´—à´¤ം
firstname=à´…à´°à´µിà´¨്à´¦്
middlename=ശങ്കരൻ
lastname=à´¨ായർ

Step 5: Create a Class Named LoadMyProperties under  com.dao package
paste the below text


package com.dao;

import com.mybean.MyBean;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 *
 * @author Aravind Sankaran
 */

public class LoadMyProperties {
    private Properties configProp = new Properties();
    public MyBean getMyPropertiesFile(MyBean myBean){        
       
        String lang=myBean.getLanguage();
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("com/resources/"+lang+".properties");
        System.out.println("property file selected is");
        System.out.println("com/resources/"+lang+".properties");
        try {
          configProp.load(in);
          String  firstname=configProp.getProperty("firstname");       
          String  lastname=configProp.getProperty("lastname");
          String welcome=configProp.getProperty("welcome");
          String middlename=configProp.getProperty("middlename");
          myBean.setFirstName(firstname);
          myBean.setMiddleName(middlename);
          myBean.setLastName(lastname);
          myBean.setWelcome(welcome);
         
          myBean.setValid(true);
        } catch (IOException e) {
            e.printStackTrace();
        }      
      
        return myBean;
    }
}
 


Step 5: Paste the below code in index.jsp file
<%--
    Document   : index
    Created on : 21 Jun, 2013, 12:42:38 AM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
var e=document.getElementById("utype");
var str=e.options[e.selectedIndex].value;
var urls="myhome.jsp?lang="+str;

if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4)
    {
           document.getElementById("err").innerHTML=xmlhttp.responseText;

    }
  }
xmlhttp.open("GET",urls,true);
xmlhttp.send();
}
</script>

    </head>
    <body bgcolor="black">
        <center>
        <table>
            <tr>
                <td><font color="white">Choose Language</font></td>
                <td>
                    <select name="utype" id="utype" onchange="loadXMLDoc()">
                                                <option value="-select-">-select-</option>
                                                <option value="en">english</option>
                                                <option value="ma">malayalam</option>
                                               
                    </select>
                </td>
            </tr>
        </table>
        <span id="err"></span>
    </center>
    </body>
</html>
 
 

Step 6: Paste the below code in myhome.jsp file 
<%--
    Document   : myhome
    Created on : 21 Jun, 2013, 12:54:33 AM
    Author     : Aravind Sankaran
--%>

<%@page import="com.dao.LoadMyProperties"%>
<%@page import="com.mybean.MyBean"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% String lang=request.getParameter("lang");%>
<%!String welcome;%>
<%!String myFirstName;%>
<%!String myMiddleName;%>
<%!String myLastName;%>

        <%
        MyBean myBean=new MyBean();
        myBean.setLanguage(lang);
        LoadMyProperties loadMyProperties=new LoadMyProperties();
        myBean=loadMyProperties.getMyPropertiesFile(myBean);%>
        <% if (myBean.isValid()) {
            welcome=myBean.getWelcome();
            myFirstName=myBean.getFirstName();
            myMiddleName=myBean.getMiddleName();
            myLastName=myBean.getLastName();
        %>
       
        <% } else { %>
            <p> No data in properties file</p>
<% } %>
             
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1><font color="white"><%=welcome%>&nbsp;<%=myFirstName%>&nbsp;<%=myMiddleName%>&nbsp;<%=myLastName%></font></h1>
    </body>
</html>

Output
click on the image to view in full size


click on the image to view in full size


click on the image to view in full size

click on the image to view in full size
 

Wednesday 19 June 2013

How to use properties file in a Java Web Application


Project Structure

 

Step 1: Create a Web Application using netbean IDE

Step 2: Create 3 packages namely
2.a. com.mybean
2.b. com.resources
2.c. com.dao

Step 3: Create a Class Named MyBean under  com.mybean package

package com.mybean;
/**
 *
 * @author Aravind Sankaran
 */
public class MyBean {
    private String firstName;
    private String lastName;
    private boolean valid;

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
  
}

Step 4: Create a properties Named config under  com.resources package
4.a. Right click  com.resources
4.b. New
4.c. properties file

paste below text on config.properties file

# To change this template, choose Tools | Templates
# and open the template in the editor.
firstname=aravind
lastname=sankaran nair

Step 5: Create a Class Named LoadMyProperties under  com.dao package
paste the below text

package com.dao;
import com.mybean.MyBean;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class LoadMyProperties {
   private Properties configProp = new Properties();
      public  MyBean getMyPropertiesFile(){   
              MyBean myBean= new MyBean();
              InputStream in = this.getClass().getClassLoader().getResourceAsStream("com/resources  /config.properties");
                  try {
                       configProp.load(in);
                       String  firstname=configProp.getProperty("firstname");       
                       String  lastname=configProp.getProperty("lastname");
                       myBean.setFirstName(firstname);
                       myBean.setLastName(lastname);
                       myBean.setValid(true);
                         } catch (IOException e) {
                                   e.printStackTrace();
                        }
        
               return myBean;
    }
}

Step 5: Paste the below code in index.jsp file

<%--
    Document   : index
    Created on : 19 Jun, 2013, 7:07:36 PM
    Author     : Aravind Sankaran
--%>

<%@page import="com.mybean.MyBean"%>
<%@page import="com.dao.LoadMyProperties"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>      
        <%!String myFirstName;%>
        <%!String myLastName;%>
        <%
        MyBean myBean=new MyBean();
        LoadMyProperties loadMyProperties=new LoadMyProperties();
        myBean=loadMyProperties.getMyPropertiesFile();%>
        <% if (myBean.isValid()) {
            myFirstName=myBean.getFirstName();
            myLastName=myBean.getLastName();
        %>       
        <% } else { %>
            <p> No data in properties file</p>
        <% } %>
             
        welcome&nbsp;<%=myFirstName%>&nbsp;<%=myLastName%>
    </body>
</html>


Output:
welcome aravind  sankaran nair



How to print Hello World without using System.out.print() statement?

import static java.lang.System.*;
/**
 *
 * @author Aravind Sankaran
 */
public class HelloWorld{
    public static void main(String a[]){
        out.println("Hello World");
       }
}

Tuesday 18 June 2013

Embedding javascript in servlet to open a jsp page in new window

MyServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            out.println("<script>function openWin(){myWindow=window.open('mypage.jsp','mypage.jsp','width=200,height=100'); myWindow.focus();}</script>");
            }
           
}



index.html
<html>
          <body>
                     <form method="post"  action="/MyServlet ">
                                    <input type="submit"  value="click me">
                     </form>
          </body>
</html>

Casting Numeric String to Integer Using Java

Class CastingStringToInt{
public static void main(String a[]){
      String input="12345";
      int output=Integer.parseInt(input);
      System.out.println(output);
      }
}

output
12345

Running a Java Program from Command Prompt (Using Temporary path & Permanent Path)


Create a  folder C:\myjava. 
Open the Notepad and write below text 

    public class MyFirstJavaProgram
    {
      public static void main(String[] args)
      {
        System.out.println("my first java program");
      }
    }

 Save your file as MyFirstJavaProgram.java in C:\myjava. 
Note: Make sure your file name is MyFirstJavaProgram.java,
(not MyFirstJavaProgram.java.txt), first choose "Save as file type:" All files, then type in the file name MyFirstJavaProgram.java.

Run Command Prompt (start--->run dialog box will appear--->type cmd--->press enter)
   Go to myjava folder by typing
    C:\> cd C:\myjava
    This makes C:\myjava the current directory.
    C:\myjava >

To compile a nd run java program you need to set path. Two ways we can set path one is temporary path and another one is permanent path.
please refer this blog (it says how to set java path)..click here

Using Temporary path
    C:\myjava > set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin
    This tells the system where to find JDK programs.
    C:\myjava > javac MyFirstJavaProgram.java
    This runs javac.exe, the compiler.  You should see nothing but the next system prompt...

    C:\myjava >
    javac has created the MyFirstJavaProgram.class file.  You should see MyFirstJavaProgram.java and   MyFirstJavaProgram.class among the files.

    C:\myjava > java MyFirstJavaProgram

    output:
    my first java program

Using Permanent Path
 C:\myjava > javac MyFirstJavaProgram.java
    This runs javac.exe, the compiler.  You should see nothing but the next system prompt...

    C:\myjava >
    javac has created the MyFirstJavaProgram.class file.  You should see MyFirstJavaProgram.java and MyFirstJavaProgram.class among the files.

    C:\myjava > java MyFirstJavaProgram

    output:
    my first java program

Does subclasses inherit private fields of superclass in java?

Answer is YES.

public class MySubClass extends MySuperClass {
public static void main(String a[]){
MySubClass mySubClass=new MySubClass ();

System.out.println(
mySubClass.getPrivateVariable());

}
}

class
MySuperClass {

private int y=20;

public int getPrivateVariable(){
return y;
}

}


output is:
20