Monday, June 13, 2011

How to Parse XML using Java

Step 2: Dom Parser
 
package org.best.example;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
 
public class ReadXMLFile {
 
 public static void main(String argv[]) {
 
 try {
 
    File fXmlFile = new File("c:\\file.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
 
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("staff");
    System.out.println("-----------------------");
 
    for (int temp = 0; temp < nList.getLength(); temp++) {
 
       Node nNode = nList.item(temp);     
       if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
          Element eElement = (Element) nNode;
 
          System.out.println("First Name : "  + getTagValue("firstname",eElement));
          System.out.println("Last Name : "  + getTagValue("lastname",eElement));
          System.out.println("Nick Name : "  + getTagValue("nickname",eElement));
          System.out.println("Salary : "  + getTagValue("salary",eElement));
 
        }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
 
 private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0); 
 
    return nValue.getNodeValue();    
 }
 
}

Twelve rules for developing more secure Java code-Rule 8


Rule 8: Make your classes noncloneable

Java's object cloning mechanism can allow an attacker to manufacture new instances of classes you define, without executing any of your constructors. If your class isn't cloneable, the attacker can define a subclass of your class, and make the subclass implement java.lang.Cloneable. This lets an attacker create new instances of your class. The new instances are made by copying the memory images of existing objects; though this is sometimes an acceptable way to make a new object, it often is not.
Rather than worry about this, you're better off making your objects noncloneable. You can do this by defining the following method in each of your classes:

public final void clone() throws java.lang.CloneNotSupportedException {
        throw new java.lang.CloneNotSupportedException();
}

If you want your class to be cloneable, and you've considered the
consequences of that choice, then you can still protect yourself. If you're
defining a clone method yourself, make it final. If you're relying on a
nonfinal clone method in one of your superclasses, then define this
method:

public final void clone() throws java.lang.CloneNotSupportedException {
        super.clone();
}

 This prevents an attacker from redefining your clone method.

Sunday, June 12, 2011

Twelve rules for developing more secure Java code-Rule 7


Rule 7: If you must sign your code, put it all in one archive file

By following this rule, you will help prevent an attacker from carrying out a mix-and-match attack, in which the attacker constructs a new applet or library that links some of your signed classes together with malicious classes, or links together signed classes that you never meant to be used together. By signing a group of classes together, you make such attacks more difficult. Existing code-signing systems do an inadequate job of preventing mix-and-match attacks, so this rule cannot prevent such attacks completely. But using a single archive can't hurt.
Some code-signing systems let you examine other classes to see who signed them. If you're using a code-signing system that allows this, you can put code into the static constructors of your classes to verify that the "surrounding" classes have been signed by the expected person.
This measure doesn't completely prevent mix-and-match attacks, since an adversary can still mix together classes you signed at different times -- for example, by mixing version 1 of Class A with version 2 of Class B. If you're worried about this kind of inter-version mix-and-match attack, you can put each class's "version stamp" in a public final variable, and then have each class check the version stamps of its surrounding classes.

How to Parse XML using Java


Step1:- Parsing XML

if you are a beginner to XML using Java then this is the perfect sample to parse a XML file create Java Objects and manipulate them.

The idea here is to parse the staff.xml file with content as below



<?xml version="1.0"?>
<company>
 <staff>
  <firstname>Amit</firstname>
  <lastname>Mangal</lastname>
  <nickname>Tiger</nickname>
  <salary>100000</salary>
 </staff>
 <staff>
  <firstname>Lalit</firstname>
  <lastname>Aggarwal</lastname>
  <nickname>Lalit</nickname>
  <salary>200000</salary>
 </staff>
</company>

From the parsed content create a list of Staff objects and print it to the console. The output would be something like

Root element :company
-----------------------
First Name : Amit
Last Name : Mangal
Nick Name : Tiger
Salary : 100000
First Name : Lalit
Last Name : Aggarwal
Nick Name : Lalit
Salary : 200000

We will start with a DOM parser to parse the xml file, create Employee value objects and add them to a list. To ensure we parsed the file correctly let's iterate through the list and print the employees data to the console.

Saturday, June 11, 2011

How to Convert String to byte array

This little code example shows a String to byte array conversion. The String class has a method called getBytes which returns an array of bytes. In the example the length of the array is printed out to illustrate that the length of the array is the same as the number of characters in the String.

package org.best.example;

public class Main {
 
    /*
     * This method converts a String to an array of bytes
     */

    public void convertStringToByteArray() {
     
        String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
     
        byte[] theByteArray = stringToConvert.getBytes();
     
        System.out.println(theByteArray.length);
     
    }
 
    /**
     * @param args the command line arguments
     */

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

Twelve rules for developing more secure Java code-Rule 6


Rule 6: Avoid signing your code

 Code that isn't signed will run without any special privileges. And code with no special privileges is much less likely to do damage.
Of course, some of your code might have to acquire and use privileges to perform some dangerous operation. Work hard to minimize the amount of privileged code, and audit the privileged code more carefully than the rest.

Friday, June 10, 2011

How to Call Procedure

package org.best.example;

import java.sql.*;
public class CallableStmt
    {
     public static void main(String args[])
         {
         try
             {
             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection con = DriverManager.getConnection("jdbc:odbc:uma","kworker","kworker");
           
             //calling a stored procedure with no input/output param
             /*
             CREATE PROCEDURE HELLOWORLD
             AS
             SELECT 'HELLOWORLD' AS HELLO
             */
             CallableStatement cs1 = con.prepareCall("{call HelloWorld}");
             ResultSet rs1 = cs1.executeQuery();
             while(rs1.next())
                 {
                 String one = rs1.getString("HELLO");
                 System.out.println(one);
             }
           
           
             //Calling a stored procedure which takes in 2 parameters for addition
             /*
             --EXECUTE ADDITION 10,25,NULL
             ALTER PROCEDURE ADDITION
             @A INT
             , @B INT
             , @C INT OUT
             AS
             SELECT @C = @A + @B
             */
             CallableStatement cs2 = con.prepareCall("{call ADDITION(?,?,?)}");
             cs2.registerOutParameter(3,java.sql.Types.INTEGER);
             cs2.setInt(1,10);
             cs2.setInt(2,25);
             cs2.execute();
             int res = cs2.getInt(3);
             System.out.println(res);
           
             //Another way
             /*
             --create table test(slno int,ques varchar(100),ans text)
             --EXECUTE fetchRec 1
             create procedure fetchRec
             @A int
             as
             select * from test where slno=@A
             */
             CallableStatement cs3 = con.prepareCall("{call fetchRec(?)}");
             cs3.registerOutParameter(1,java.sql.Types.INTEGER);
             cs3.setInt(1,5);
             ResultSet rs3 = cs3.executeQuery();
             while(rs3.next())
                 {
                 String ques = rs3.getString(2);
                 String ans = rs3.getString(3);
                 System.out.println(ques);
                 System.out.println(ans);
             }
           
           
         }
         catch(Exception e)
             {
             e.printStackTrace();
         }
     }
}