Friday, June 17, 2011

How to append content to file in Java

FileWritter, a character stream to write characters to file. By default, it will replace all the existing content with new content, however, when you specified a true (boolean) value as the second argument in FileWritter constructor, it will keep the existing content and append the new content in the end of the file.

package org.best.example.file;
 
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
 
public class AppendToFileExample 
{
    public static void main( String[] args )
    { 
     try{
      String data = " This content will append to the end of the file";
 
      File file =new File("javaio-appendfile.txt");
 
      //if file doesnt exists, then create it
      if(!file.exists()){
       file.createNewFile();
      }
 
      //true = append file
      FileWriter fileWritter = new FileWriter(file.getName(),true);
             BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
             bufferWritter.write(data);
             bufferWritter.close();
 
         System.out.println("Done");
 
     }catch(IOException e){
      e.printStackTrace();
     }
    }
}

Thursday, June 16, 2011

How to Use HashMap in Java

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.
The following constructors are defined:
HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
The first form constructs a default hash map. The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments. The meaning of capacity and fill ratio is the same as for HashSet, described earlier.
HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.
The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.

package org.best.example;

import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}

Output from this program is shown here:

Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Todd Hall: 99.22
Jane Baker: 1378.0
John Doe's current balance: 4434.34
The program begins by creating a hash map and then adds the mapping of names to balances. Next, the contents of the map are displayed by using a set-view, obtained by calling entrySet(). The keys and values are displayed by calling the getKey() and getValue() methods that are defined by Map.Entry. Pay close attention to how the deposit is made into John Doe's account. The put() method automatically replaces any preexisting value that is associated with the specified key with the new value. Thus, after John Doe's account is updated, the hash map will still contain just one "John Doe" account.

Twelve rules for developing more secure Java code-Rule 11


Rule 11: Don't compare classes by name

 Sometimes you want to compare the classes of two objects to see whether they are the same; or you want to see whether an object has a particular class. When you do this, be aware that there can be multiple classes with the same name in a JVM. It is a mistake to compare classes by name since different classes can have the same name. A better method is to compare class objects for equality directly. For example, given two objects, A and B, if you want to see whether they are the same class, use this code:
if(a.getClass() == b.getClass()){
        // objects have the same class
}else{
        // objects have different classes
}
You should also be on the lookout for cases of less direct by-name
comparisons. Suppose, for example, you want to see whether an object
has the class "Foo." Here is the wrong way to do it:

if(obj.getClass().getName().equals("Foo"))   // Wrong!
        // objects class is named Foo
}else{
        // object's class has some other name
}
Here's a better way to do it:
if(obj.getClass() == this.getClassLoader().loadClass("Foo")){
        // object's class is equal to the class that this class calls "Foo"
}else{
        // object's class is not equal to the class that
   // this class calls "Foo"
}

 Do note the legalistic comments in the last example. Whenever you use class names, you open yourself up to mix-and-match attacks, as described in Rule 7. You should also know that the Java language forces you to use class names all the time: in variable declarations, instanceof expressions, and exception-catching blocks. Only the designers of Java can prevent mix-and-match attacks, but you can avoid making the problem worse by avoiding by-name class comparisons.

Wednesday, June 15, 2011

Twelve rules for developing more secure Java code-Rule 10


Rule 10: Make your classes nondeserializeable

This rule is even more important than the previous one. Even if your class isn't serializeable, it may still be deserializeable. An adversary can create a sequence of bytes that happens to deserialize to an instance of your class. This is dangerous, since you do not have control over what state the deserialized object is in. You can think of deserialization as another kind of public constructor for your object; unfortunately it's a kind of constructor that is difficult for you to control.
You can prevent this kind of attack by making it impossible to deserialize a byte stream into an instance of your class. You can do this by declaring the readObject method:

private final void readObject(ObjectInputStream in)

throws java.io.IOException {
        throw new java.io.IOException("Class cannot be deserialized");
}
  
As above, this method is declared final to prevent the adversary from overriding it.

How to Convert byte[ ] array to String

Making a byte array to String conversion in Java is very simple since one of the String class constructors takes an array of bytes as argument. We simply create the object with our array as argument to convert the byte array to a String, and then print out the value.

package org.best.example;

public class Main {
 
    /*
     * This method converts an byte array to a String object.
     */

 
    public void convertByteArrayToString() {
     
        byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
     
        String value = new String(byteArray);
     
        System.out.println(value);
    }
 
 
    /**
     * @param args the command line arguments
     */

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



Tuesday, June 14, 2011

Twelve rules for developing more secure Java code-Rule 9


Rule 9: Make your classes nonserializeable

Serialization is dangerous because it allows adversaries to get their hands on the internal state of your objects. An adversary can serialize one of your objects into a byte array that can be read. This allows the adversary to inspect the full internal state of your object, including any fields you marked private, and including the internal state of any objects you reference.
To prevent this, you can make your object impossible to serialize. To achieve this goal, declare the writeObject method: 

private final void writeObject(ObjectOutputStream out)
throws java.io.IOException {
        throw new java.io.IOException("Object cannot be serialized");
}

 This method is declared final so that a subclass defined by the adversary cannot override it.

How to Parse XML using Java

Step 2- SAX Parser XML is Same

package org.best.example;
 
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
public class ReadXMLFileSAX {
 
 public static void main(String argv[]) {
 
  try {
 
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser saxParser = factory.newSAXParser();
 
     DefaultHandler handler = new DefaultHandler() {
 
     boolean bfname = false;
     boolean blname = false;
     boolean bnname = false;
     boolean bsalary = false;
 
     public void startElement(String uri, String localName,
        String qName, Attributes attributes)
        throws SAXException {
 
        System.out.println("Start Element :" + qName);
 
        if (qName.equalsIgnoreCase("FIRSTNAME")) {
           bfname = true;
        }
 
        if (qName.equalsIgnoreCase("LASTNAME")) {
           blname = true;
        }
 
        if (qName.equalsIgnoreCase("NICKNAME")) {
           bnname = true;
        }
 
        if (qName.equalsIgnoreCase("SALARY")) {
           bsalary = true;
        }
 
     }
 
     public void endElement(String uri, String localName,
          String qName)
          throws SAXException {
 
          System.out.println("End Element :" + qName);
 
     }
 
     public void characters(char ch[], int start, int length)
         throws SAXException {
 
         if (bfname) {
            System.out.println("First Name : "
                + new String(ch, start, length));
            bfname = false;
          }
 
          if (blname) {
              System.out.println("Last Name : "
                  + new String(ch, start, length));
              blname = false;
           }
 
          if (bnname) {
              System.out.println("Nick Name : "
                  + new String(ch, start, length));
              bnname = false;
           }
 
          if (bsalary) {
              System.out.println("Salary : "
                  + new String(ch, start, length));
              bsalary = false;
           }
 
        }
 
      };
 
      saxParser.parse("c:\\file.xml", handler);
 
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 
}