Tuesday, June 7, 2011

How to Get Column Names for a Table

For Fetching column names of a table ResultSetMetaData is used in JDBC .

package org.best.examples;

import java.sql.*;

public class GetColNames
    {
   
    public static void main(String args[])
        {
         try
             {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection connection = DriverManager.getConnection("jdbc:odbc:dd","","");
             // Create a result set
             Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM test");
           
             // Get result set meta data
             ResultSetMetaData rsmd = rs.getMetaData();
             int numColumns = rsmd.getColumnCount();
           
             // Get the column names; column indices start from 1
             for (int i=1; i                 {
                 String columnName = rsmd.getColumnName(i);
               
                 // Get the name of the column's table name
                 String tableName = rsmd.getTableName(i);
                 System.out.println("columnName "+columnName);
             }
         }
         catch (Exception e)
             {
             System.out.println(e);
         }
    }
}

Monday, June 6, 2011

Twelve rules for developing more secure Java code-Rule1


Rule 1: Don't depend on initialization

Most Java developers think there is no way to allocate an object without running a constructor. But this isn't true: there are several ways to allocate noninitialized objects.
The easy way to protect yourself against this problem is to write your classes so that before any object does anything, it verifies that it has been initialized. You can do this as follows:
  • Make all variables private. If you want to allow outside code to access variables in an object, this should be done via get and set methods. (This keeps outside code from accessing noninitialized variables.) If you're following Rule 3, you'll make the get and set methods final.
  • Add a new private boolean variable, initialized, to each object.
  • Have each constructor set the initialized variable as its last action before returning.
  • Have each nonconstructor method verify that initialized is true before doing anything. (Note that you may have to make exceptions to this rule for methods called by your constructors. If you do this, it's best to make the constructors call only private methods.)
  • If your class has a static initializer, you will need to do the same thing at the class level. Specifically, for any class that has a static initializer, follow these steps:
  • Make all static variables private. If you want to allow outside code to access static variables in the class, this should be done via static get and set methods. This keeps outside code from accessing noninitialized static variables. If you're following Rule 3, you'll make the get and set methods final.
  • Add a new private static boolean variable, classInitialized, to the class.
  • Have the static constructor set the initialized variable as its last action before returning.
Before doing anything, have each static method and each constructor verify that classInitialized is true. (Note: constructors are required to call a constructor of the superclass, or another constructor of the same class, as their first action. So you will have to do that before you check classInitialized.)

Show a message dialog with JOptionPane

This code example shows how to easily display a message dialog using the Swing class JOptionPane.

package org.best.examples.swing;

public class myFrame extends JFrame {

   public void displayMessage() {

      JOptionPane.showMessageDialog(this,
                                    "The message",
                                    "The Title",
                                    JOptionPane.INFORMATION_MESSAGE);
   }
}

Sunday, June 5, 2011

How to Send a POST Request with Parameters From a Java Class

This example shows how to sent a POST request to a server with attached parameters. Two parameters are sent in the example code below, width and height. We use the URL and URLConnection classes to open the connection to the destination. Then the output stream is retrieved by calling getOutputStream() on the URLConnection object. With the output stream we can write the parameters and then start reading the response from the server using the input stream which we get by calling getInputStream() on the same URLConnection object. We assume there will only be character based content returned from the server so we use the BufferedWriter to read the response line by line.

package org.best.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {
  
    /**
     * Extends the size of an array.
     */

    public void sendPostRequest() {
      
        //Build parameter string
        String data = "width=50&height=100";
        try {
          
            // Send the request
            URL url = new URL("http://www.somesite.com");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
          
            //write parameters
            writer.write(data);
            writer.flush();
          
            // Get the response
            StringBuffer answer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            writer.close();
            reader.close();
          
            //Output the response
            System.out.println(answer.toString());
          
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().sendPostRequest();
    }
}

Twelve rules for developing more secure Java code


Writing security-conscious Java code can help you avoid security surprises

This article introduces 12 rules for writing security-critical Java code; 12 rules that all Java developers should abide by. If you are charged with managing a gaggle of Java developers, or if your business relies on the security of Java, make sure your developers follow these rules.
These rules haven't been sugar-coated for mass consumption. They get fairly technical and require broad knowledge of Java to understand. Though experienced Java developers will understand all the rules that follow, less experienced Java developers may have a bit of homework to do. Nevertheless, following these rules will make your Java code more secure.
We base these rules on the experience of many people who have generously discussed their experience in building secure Java code. In creating these 12 rules, we've drawn from much experience in hunting down Java security bugs, and on advice and observations from people who write and review security-critical Java code for a living. Each rule is designed to eliminate an unexpected gotcha that you might face.
Of course, security is an elusive goal. Following these rules certainly won't provide any guarantee that your code is completely secure. It is easy to write insecure code that follows these rules. By following these goals, however, you will minimize or eliminate certain kinds of security attacks that you might not have thought of.
Think of these rules as a first step. If you are writing code that may be linked or run in conjunction with untrusted code, then you should definitely consider following these rules.
Every attempt has been made to keep the rules simple enough that you can treat them as a checklist to be followed in mechanical fashion. That way you can save your brainpower for other security issues.

Saturday, June 4, 2011

JAVA BASICS-Interface


An interface defines the contract between service provider and the client without highlighting internal implementation.
i.e Interface describes the services ,what service provider provides and what client get.

The main advantage of interface are :

1. we never high lite our implementation to the outside world,we can achieve security for our implementation.
2. With out effecting outside world,we can enhance our internal implementation. Interface is considered as 100% pure abstract class because we never keep implementation inside interface. And hence all the methods present inside an interface are abstract methods.
For the service provider point of view an interface defines the services provided by that person.
From the client point of view an interface describes what services he required.

Declaring an interface:

interface Interf
{
public void m1();
public void m2();
}
class Bea implements Interf
{
public void m1()
{
System.out.println(“implementation m1”);
}
public void m2()
{
System.out.println(“implementation m2”);
}
public static void main(String arg[])
{
Interf i=new Interf();
i.m1();
}
}
  • If you want to provide implementation for any interface method ,it must be declared as public .
  • The first concrete class which implements an interface must provide implementation for all the interface methods other wise the class must declared as abstract.
  • We can declare an interface (top level) with <default> and public,abstract,strictfp modifiers.
Interface methods Declarations:
All the interface methods by default abstract and public (either we are specify or not specify) not concrete method.
Examples:
Void m1();
public void m1();
abstract void m1();
public abstract void m1();
All the above are same .
Hence the above four methods declaration are identical.
An interface method never be declared as native ,strictfp,private ,static, synchronized and protected.

Interface variables Declarations:
All the interface variable are by default public ,static and final.
Hence the following variable declaration inside an interface are identical.

interface interf
{
int x=10;
public int x=10;
public static final int x=10;
final int x=10;
static int x=0;
}
Hence an interface we never declared as private ,protected and transient.

All the interface variables must perform initialization at the time of declaration.
Hence the following code will not compile.

interface Interf
{
int x;
}
Inside implement classes we are not allowed to change the value of interface variable violation leads to compile time error.
Class Sample implement Interf
{
public static void main(String arg[])
{
x=20; //compile time error
}
}
A class can extend only one class at a time .But can interface can extend any number interfaces.
A class can implement any number of interfaces at a time.But interface never implement another interface.

Naming conflicts inside interface:
Case 1:
interface Left
{
public void m1();
}
interface Right
{
public void m1();
}
class Central implement Left,Right
{
public static void main(String arg[])
{
public void m1()
{
}
}
If two interfaces have the two are more same methods ,then only one method implementation is enough from both interfaces.

Case 2:
The interface having same method name but different arguments.
Interface Inter
{
public void m1();
public void m1(int x);
}

case 3:
Same method name,same arguments but different written types.
Interface Left
{
public void m1();
}
Interface Right
{
public int m1();
}

class Central implement Left,Right
{
public static void main(String arg[])
{
public void m1() // error
{
}
public int m1() // error
{
}
}
}
In the above class same method signature m1 is not allow .violation leads to compile time error.

Exceptional case :

We can’t provide implementation at a time for two or more interfaces having methods with same signature but different return type .

Variable Naming conflicts:
interface Left
{
int x=10;
}
interface Right
{
int x=100;
}
class Central implement Left,Right
{
public static void Main(String arg[]
)
{
System.out.println(x); // reference to x is ambiguous both variables
System.out.println(Right.x);
System.out.println(Left.x);
}
}
we can resolve variable naming conflicts using interface name.(i.e instead of x we have to specify left.x or right.x).

Tag Interface Marker/Ability Interface:

If an interface is marked for some ability such type of interfaces are called maker interfaces or tag interface or ability interface.
Example: Comparable,Serializable,Clonable
If an interface doesn’t contain any method ,it is usually marker interface.Even though interface contains some methods still we can use the term marker interface if this interface is marked for some ability.
Example: Comparable(contains method compareTo())
Adapter classes doesn’t contain concrete methods ,contain only empty implementation of the methods.

Difference between abstract class and interface:

Interfaces provides more security and high performance when compare to abstract classes.
Abstract class may contain concrete methods but an interface never contain any concrete method.

How to Redirect Servlet Call to Another URL

To redirect a call from a servlet to some other url, use the sendRedirect() method of the HttpServletResponse object that is passed to the service() method. The sendRedirect() method takes the new destination url as a string parameter.

package org.best.example;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExampleServlet extends HttpServlet {
  
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */

    protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        //Redirect call to another url
        response.sendRedirect("http://www.java.com");
    }
  
}