Choose Your Language

Friday, 5 December 2014

How to access the private member of a class in another class?

public class MyMainClass{
   
    public static void main(String args[])
    {
    MySubClass mySubClass=new MySubClass();
    System.out.println(mySubClass.getPrivateMethod());
    }
    }

class MySubClass {         
           
         private String myPrivateMethod(){
         return "Aravind Sankaran";
         }
        
         public String getPrivateMethod(){
             return myPrivateMethod();
         }
    }

Output:
Aravind Sankaran

Wednesday, 3 December 2014

How to access non-static member of a class using it's static method

package com.test.java;

public class Pen {
    String name="Aravind";//non static member
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub       
        displayName();
    }

    static void displayName(){
        Pen p=new Pen();
        System.out.println(p.name);
    }
}

Output:
Aravind

Saturday, 26 July 2014

How to override static method

package overriding;

/**
 *
 * @author Aravind Sankaran
 */
public class SubClass extends SuperClass{
    public static void main(String args[]){
        SubClass subClass=new SubClass();
        subClass.display();
        subClass.display(10);
    }
    int x;
    void display(){
        System.out.println("inside display() of SubClass");
    }
    void display(int x){
        this.x=x;;
        System.out.println("inside display("+x+") of SubClass");
    }
}

class  SuperClass{
    int x;
    void display(){
        System.out.println("inside display() of SuperClass");
    }
    void display(int x){
        this.x=x;;
        System.out.println("inside display("+x+") of SuperClass");
    }
}


Output:
inside display() of SubClass
inside display(10) of SubClass

Friday, 23 May 2014

How to build our own library using java

1. Create a "Java Project" named as "OurOwnLibrary", and create a "Class" named "OurOwnLibrary" add three method named "diplayStaticMethod", "diplayNonStaticMethod", "diplayMethodWithArgument" under "OurOwnLibrary" class.

Here is the project Structure:




OurOwnLibrary.java

package ourownlibrary;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class OurOwnLibrary {

    /**
     * @param args the command line arguments
     */
    public static String diplayStaticMethod() {
        // TODO code application logic here
        return "You are using OurOwnLibrary Class and its diplayStaticMethod()";
    }
     public String diplayNonStaticMethod() {
        // TODO code application logic here
        return "You are using OurOwnLibrary Class and its diplayNonStaticMethod()";
    }
     public String diplayMethodWithArgument(String myArgument) {
        // TODO code application logic here
        return "You are using OurOwnLibrary Class and its diplayNonStaticMethod(). Argument is "+myArgument;
    }
}

Right click "OurOwnLibrary" project and select clean and build.
A jar file is created in dist  folder in which the project is located.

2. Create a "Java Project" named as "OurOwnLibraryImplimentaion", and create a "Class" named "OurOwnLibraryImplimentaion".

 Here is the project Structure:



OurOwnLibraryImplimentaion.java

package ourownlibraryimplimentaion;
import ourownlibrary.OurOwnLibrary;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class OurOwnLibraryImplimentaion {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println(OurOwnLibrary.diplayStaticMethod());
        OurOwnLibrary ourOwnLibrary=new OurOwnLibrary();
        System.out.println(ourOwnLibrary.diplayNonStaticMethod());
        System.out.println(ourOwnLibrary.diplayMethodWithArgument("aravind"));
    }
}


 Right click "OurOwnLibraryImplimentaion " project and select properties.
A new window popups
Select libraries
Click Add JAR/Folder
A new window popups and ask you to add external jar file.
Specify the jar file location (ie, jar file inside dist folder of OurOwnLibrary project)
After selection the jar file, clik open
Now the jar file is listed in the librarylist
Click ok.
Run OurOwnLibraryImplimentaion.java

Output:
You are using OurOwnLibrary Class and its diplayStaticMethod()
You are using OurOwnLibrary Class and its diplayNonStaticMethod()
You are using OurOwnLibrary Class and its diplayNonStaticMethod(). Argument is aravind

Wednesday, 21 May 2014

How to create our own Marker Interface in java

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

/**
 *
 * @author Aravind Sankaran Nair
 */
public class MarkerInterface {
    public static void main(String args[]){
        MarkerImplementation markerImplementation=new MarkerImplementation();
       
      if(markerImplementation instanceof FirstMarker)  {
           System.out.println(markerImplementation.display());
      }
      if(markerImplementation instanceof SecondMarker)  {
          System.out.println(markerImplementation.display());
      }
    }
}
interface FirstMarker{
   
}
interface SecondMarker{
   
}
class MarkerImplementation implements FirstMarker{
   String display(){        
       return getClass().getInterfaces()[0].getSimpleName()+" interface is implimented";
   }
   
}

Output:
FirstMarker interface is implimented

Sunday, 11 May 2014

WSDL (Web Services Description Language)



             As communications protocols and message formats are standardized in the     web community, it becomes increasingly possible and important to be able to describe the communications in some structured way.WSDL addresses this need by defining an XML grammar for describing network services as collections   of communication  endpoints  capable of  exchanging messages.

                    WSDL service  definitions provide documentation for   distributed systems and serve as a recipe for automating the details involved in applications communication

               A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

           Types– a container for data type definitions using some type system (such as XSD).

           Message– an abstract, typed definition of the data being communicated.

           Operation– an abstract description of an action supported by the service.

           Port Type–an abstract set of operations supported by one or more endpoints.

           Binding– a concrete protocol and data format specification for a particular port type.

           Port– a single endpoint defined as a combination of a binding and a network address.

           Service– a collection of related endpoints.

               It is important to observe that WSDL does not introduce a new type definition language.   WSDL recognizes the need for rich type systems for describing message formats, and supports the XML Schemas specification (XSD) [11] as its canonical type system. However, since it is unreasonable to expect a single type system grammar to be used to describe all message formats present and future, WSDL allows using other type definition languages via extensibility.

                In addition, WSDL defines a common binding mechanism. This is used to attach a specific protocol or data format or structure to an abstract message, operation, or endpoint. It allows the reuse of abstract definitions.

               In addition to the core service definition framework, this specification introduces specific binding extensions for the following protocols and message formats:

           SOAP 1.1
           HTTP GET / POST
           MIME

Structure Of A WSDL Document

<definitions>

<types>

 definition of types........

</types>

<message>

 definition of a message....

</message>

<portType>

 definition of a port.......

</portType>

<binding>

  definition of a binding....

</binding>

</definitions>

What is a Web service



Web service is a way of communication that allows interoperability between different applications on different platforms, for example, a java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.

Web services are browsers and operating system independent service, which means it can run on any browser without the need of making any changes.

The World Wide Web Consortium (W3C) has defined the web services. According to W3C, “Web Services are the message-based design frequently found on the Web and in enterprise software. The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”

Types of web services
WSDL
  • WSDL stands for Web Services Description Language
  • WSDL is an XML-based language for describing Web services.
  • WSDL is a W3C recommendation
SOAP
  • SOAP stands for Simple Object Access Protocol
  • SOAP is an XML based protocol for accessing Web Services.
  • SOAP is based on XML
  • SOAP is a W3C recommendation
UDDI
  • UDDI stands for Universal Description, Discovery and Integration
  • UDDI is a directory service where companies can search for Web services.
  • UDDI is described in WSDL
  • UDDI communicates via SOAP
RDF
  • RDF stands for Resource Description Framework
  • RDF is a framework for describing resources on the web
  • RDF is written in XML
  • RDF is a W3C Recommendation

Friday, 9 May 2014

Dynamic class loading and invoking its methods

package dynamic;
import java.lang.reflect.Method;
/**
 *
 * @author Aravind Sankaran
 */
public class DynamicClassLoading {
    public static void main(String ar[]){       
        Class noParameter[]={};
        Class stringParameter[]=new Class[1];      
        stringParameter[0]=String.class;       
        try{
            System.out.println("Dynamic Loading");
            Class classLoader=Class.forName("dynamic.Dynamic");
            Object object=classLoader.newInstance();
            Method method=classLoader.getDeclaredMethod("display",noParameter);
            method.invoke(object, null);
            method=classLoader.getDeclaredMethod("display", stringParameter);
            method.invoke(object,"Aravind");
           
        }catch(Exception e){
           
        }
    }     
}
class Dynamic{
   public void display(){
        System.out.println("Inside Dynamic Class");
    }
   public void display(String name){
        System.out.println("Inside Dynamic Class"+name);
    }
}

output:
Dynamic Loading
Inside Dynamic Class
Inside Dynamic Class Aravind

Thursday, 17 April 2014

java program to rotate image

package imaging;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author Aravind Sankaran
 */
public class RotateImage {
    public  static void main(String args[]){
        try {    
        String path="C:\\images\\ppp.jpg";
        File fileInput=new File(path);
        BufferedImage  img = ImageIO.read(new File(path)); // try/catch IOException
        int width = img.getWidth();
        int height = img.getHeight();        
        String fileName=fileInput.getName();
        fileName=fileName.substring(0, fileName.lastIndexOf('.'));
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = bufferedImage.createGraphics();
      
// draw graphics     
        double angle=45.0;     
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.rotate(Math.toRadians(angle), width, width);
        g2d.drawImage(img, 0, 0, null);        
        g2d.dispose();
//save as png
File file = new File("C:\\images\\"+fileName+".png");
ImageIO.write(bufferedImage, "png", file);
     } catch (IOException ex) {
      
     }

    }
}
input:

output:


Friday, 11 April 2014

Analog clock using java swing

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

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.TimerTask;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Aravind Sankaran
 */
public class AnalogClock  extends JPanel{
  
ImageIcon img;

private GregorianCalendar m_calendar;
private int[] x=new int[2];
private int[] y=new int[2];
private java.util.Timer clocktimer=new java.util.Timer();

/**You could set the TimeZone for the clock here. I used the Dfault time
zone from the user so that every time the program runs on different
computers the correct time is displayed*/

private TimeZone clockTimeZone=TimeZone.getDefault();

//Constructor
public AnalogClock()
{
this.setPreferredSize(new Dimension(210,210));
this.setMinimumSize(new Dimension(210,210));

//schedules the clocktimer task to scan for every 1000ms=1sec
clocktimer.schedule(new TickTimerTask(),0,1000);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setTitle("Analog Clock");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

AnalogClock m_AnalogClock=new AnalogClock();
frame.add(m_AnalogClock);
frame.setVisible(true);
   
}
//The Clock Face instance method
public void paint(Graphics g)
{

g.setColor(Color.WHITE);
g.fillRect(0,0,this.getWidth(),this.getHeight());
drawCardinals((Graphics2D)g);
drawHands((Graphics2D)g);

}

//Endpoints of the Clock Hand
void clockMinutes(int startRadius,int endRadius,double theta)
{
theta-=Math.PI/2;
x[0]=(int)(getWidth()/2+startRadius*Math.cos(theta));
y[0]=(int)(getHeight()/2+startRadius*Math.sin(theta));
x[1]=(int)(getWidth()/2+endRadius*Math.cos(theta));
y[1]=(int)(getHeight()/2+endRadius*Math.sin(theta));
}

//The Hours/Cardinals of the clock
/** Set Stroke sets the thickness of the cardinals and hands*/
void drawCardinals(Graphics2D g)
{
//g.setStroke(new BasicStroke(9));
g.setStroke(new BasicStroke(12));
g.setColor(Color.black);

for(double theta=0;theta<Math.PI*2;theta+=Math.PI/6)
{
clockMinutes(100,100,theta);
/**Draws a sequence of connected lines defined by arrays of x and
*y coordinates. Each pair of (x, y) coordinates defines a point.
*The figure is not closed if the first point
differs from the last point.*/
g.drawPolyline(x,y,2);
}
}

//The Hand of the Clocks instance method
public void drawHands(Graphics2D g)
{
double h=2*Math.PI*(m_calendar.get(Calendar.HOUR));
double m=2*Math.PI*(m_calendar.get(Calendar.MINUTE));
double s=2*Math.PI*(m_calendar.get(Calendar.SECOND));

g.setStroke(new BasicStroke(9));

clockMinutes(0,55,h/12+m/(60*12));
g.setColor(Color.BLACK);
g.drawPolyline(x,y,2);

clockMinutes(0,70,m/60+s/(60*60));
g.setColor(Color.black);
g.drawPolyline(x,y,2);

clockMinutes(0,70,s/60);
g.setColor(Color.red);
g.drawPolyline(x,y,2);

g.fillOval(getWidth()/2-8,getHeight()/2-8,16,16);
}



//method to update/refresh the clock every second
class TickTimerTask extends TimerTask
{
public void run()
{
m_calendar=(GregorianCalendar)GregorianCalendar.getInstance(clockTimeZone);
repaint();
}
}
}
   

output:

Thursday, 10 April 2014

Checking User Name Availability Using AJAX, JSP And MySQL and javascript

 userregistration.jsp
<%--
    Document   : userregistration
    Created on : 17 May, 2013, 11:22:42 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 validateForm()
            { 
            var x=document.forms["login"]["username"].value;
            var y=document.getElementById('actual').value;           
           
                if (y=="taken")
                {
                       alert("Name already exist in database");
                    return false;
                }else
                {
                        alert("No name exist");
                }
                   
                   
             }
        </script>
        <script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
var k=document.getElementById("username").value;
var urls="checkusername.jsp?ver="+k;

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">
        <form name="login" method="get" action="" onsubmit="return validateForm();">
        <p>
    <center>
        <font color="white">User Name: </font><input type="text" name="username" id="username" onkeyup="loadXMLDoc()"><br>
        <span id="err"> </span>
    </center>
        </p>
        </form>
    </body>
</html>

checkusername.jsp
<%--
    Document   : checkusername
    Created on : 9 May, 2013, 12:42:25 PM
    Author     : Aravind Sankaran
--%>

<%@ page import="java.io.*,java.sql.*" %>
<%@ page contentType="text/html" pageEncoding="UTF-8"%>

<%
                    String sn=request.getParameter("ver");
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/daodatabase","root","root");
                    Statement st=con.createStatement();
                    ResultSet rs = st.executeQuery("select * from usertable where username='"+sn+"'");  // this is for name
                    if(rs.next())
                    {   %>
                        <font color=red>
                        Name already taken
                        <input type="hidden" id="actual" name="actual" value="taken">
                        <input type="submit" value="submit">
                        </font>

                   <% }else {%>
                        <font color=green>
                        <input type="hidden" id="actual" name="actual" value="available">
                        Available
                        </font>
                        <input type="submit" value="submit">
                   <% }%>
                   
     <%              
rs.close();
st.close();
con.close();
%>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>userregistration.jsp</welcome-file>
    </welcome-file-list>
</web-app>


Wednesday, 9 April 2014

java program to display space count of a given string

public class SpaceCounter{
    static  int spaceCounter=1;
    public static void main(String ar[]){
       
        String input="hello aravind sankaran nair";
       
        for (char space : input.toCharArray()) {
          if(Character.isWhitespace(space)){
           spaceCounter=spaceCounter+1;
          }
         }
        System.out.println("number of words = "+spaceCounter);
    }
}

output:
number of words = 4

Tuesday, 8 April 2014

Java program to connect MySql using ArrayList

Create database with name "employeedb"
Create table with name "employee"
CREATE TABLE `employee` (
  `empname` varchar(45) NOT NULL,
  `empdesignation` varchar(45) NOT NULL,
  `empsalary` varchar(45) NOT NULL
);

java code:
package mysqlconnectionusingarraylist;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class MySqlConnectionUsingArrayList {
  
     public static void main(String[] args) {
         ArrayList<Employee> employeeList =new ArrayList<Employee>();
         String url = "jdbc:mysql://localhost:3306/employeedb";
         try{
            Connection conn = DriverManager.getConnection(url, "root", "root");
            Statement st = conn.createStatement();
             ResultSet rs = st.executeQuery("SELECT * FROM employee");
                while(rs.next()){
                Employee employee=new Employee();             
                employee.setEmpName(rs.getString("empname"));
                employee.setEmpDesignation(rs.getString("empdesignation"));
                employee.setEmpSalary(rs.getString("empsalary"));
                employeeList.add(employee);               
                }
                 for(int i=0;i<employeeList.size();i++){
                System.out.println("Employee name is "+employeeList.get(i).getEmpName());
                System.out.println("Employee designation is "+employeeList.get(i).getEmpDesignation());
                System.out.println("Employee salary is "+employeeList.get(i).getEmpSalary());
                System.out.println("");
                }
         }catch(Exception e){
            
         }
          
     }
}
class Employee{
    private String empName;
    private String empDesignation;
    private String empSalary;

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getEmpDesignation() {
        return empDesignation;
    }

    public void setEmpDesignation(String empDesignation) {
        this.empDesignation = empDesignation;
    }

    public String getEmpSalary() {
        return empSalary;
    }

    public void setEmpSalary(String empSalary) {
        this.empSalary = empSalary;
    }
   
}

output:
Employee name is aravind
Employee designation is software engineer
Employee salary is 25000

Employee name is ambili
Employee designation is software engineer
Employee salary is 35000

Sunday, 6 April 2014

Checking User Name Availability Using AJAX, JSP And MySQL updated version

Project structure:





userregistration.jsp
<%--
    Document   : userregistration
    Created on : 17 May, 2013, 11:22:42 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 k=document.getElementById("username").value;
var urls="checkusername.jsp?ver="+k;

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">
        <p>
    <center>
        <font color="white">User Name: </font><input type="text" name="username" id="username" onkeyup="loadXMLDoc()"><br>
        <span id="err"> </span>
    </center>
        </p>
    </body>
</html>

checkusername.jsp
<%--
    Document   : checkusername
    Created on : 9 May, 2013, 12:42:25 PM
    Author     : Aravind Sankaran
--%>

<%@ page import="java.io.*,java.sql.*" %>
<%@ page contentType="text/html" pageEncoding="UTF-8"%>

<%
                    String sn=request.getParameter("ver");
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/daodatabase","root","root");
                    Statement st=con.createStatement();
                    ResultSet rs = st.executeQuery("select * from usertable where username='"+sn+"'");  // this is for name
                    if(rs.next())
                    {   %>
                        <font color=red>
                        Name already taken
                        </font>

                   <% }else {%>
                        <font color=green>
                        Available
                        </font>
                        <input type="submit" value="submit">
                   <% }%>
                   
     <%              
rs.close();
st.close();
con.close();
%>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>userregistration.jsp</welcome-file>
    </welcome-file-list>
</web-app>
output: