Accessing the private members of a class using reflection

Work with the Field class and the method setAccessible introduced in JDK1.2.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      Person person = new Person();
 
      Field field = Person.class.getDeclaredField("name");
      field.setAccessible(true);
 
      field.set(person, "alicia");
 
      System.out.println("Name is now: " + person.getName());
   }
}
 
class Person {
   private String name = "joris";
 
   public String getName() {
      return name;
   }
}

prints out:

alicia

You can disallow setAccessible capability by installing a security manager.

Catching CTRL-C or the unix kill command

Run this program and press CTRL-C! (JDK1.3+)

Main.java:

public class Main {
   public static void main(String[] args) {
      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            cleanup();
         }
      });
 
      while (true) ;
   }
 
   public static void cleanup() {
      System.out.println("Cleaning up...");
   }
}

Converting a String to a Reader

Use the class StringReader and pass it a String as an argument. Then you can use the typical Reader’s methods.

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      StringReader sr = new StringReader("Hello, world!");
 
      try {
         int ch;
         while ((ch = sr.read()) > 0) {
            System.out.println("Read: " + (char) ch);
         }
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}

What is UTF-8?

The standard UTF-8 format is a Unicode encoding that is compatible with ASCII, allowing old programs to work with the new format (text searching, etc). ASCII values are encoded into a single byte. Java has a modified UTF-8 format. Arabic, Greek and Hebrew characters are encoded in two bytes and the rest is encoded in three bytes. The JVM does not recognize longer UTF-8 formats than 3 bytes. There is another exception in Java, ‘u0000′ is encoded in two bytes.

u0000 is encoded in two bytes:
 
        byte 1        byte 2 
        110 00000  |  10 000000
 
range 'u0001' to 'u007f'  (ASCII values) are encoded in one byte:
 
        byte 1
        0 bits 0-6
 
range 'u0080' to 'u07ff' are encoded in two bytes:
 
        byte 1            byte 2
        110 bits 6-10  |  10 bits 0-5
 
range 'u0800' to 'uffff' are encoded in three bytes:
 
        bytes 1             byte 2           byte 3
        1110 bits 12-15  |  10 bits 6-11  |  10 bits 0-5

For example: (I’ll take the example of the RFC – see links).

The Unicode sequence: "Hi Mom <WHITE SMILING FACE>!" with encoding 
 
0048, 0069, 0020, 004D, 006F, 006D, 0020, 263A, 0021 
 
may be encoded as 
 48    69    20    4D    6F    6D    20 E2 98 BA 21

Getting a random floating-point number

Use the Random class in the java.util package. Following example prints out 10 pseudo-randomly selected floating point numbers:

import java.util.*;
 
public class Main 
{  
   public static void main(String args[]) {
      Random r = new Random();   // seed automatically set to System.currentTimeMillis()
      for (int i=0; i<10; i++) {
         float f = r.nextFloat();
         System.out.println(f);
      }
   }
}

(possibly) outputs:

0.2020728
0.9253481
0.60519326
0.9515787
0.013608098
0.739903
0.8019556
0.15060985
0.7387842
0.109374285

You could set the seed manually:

   Random r = new Random(10);
   
   or
  
   Random r = new Random();
   r.setSeed(10);

Getting the IP of the localhost

Following code demonstrates this:

import java.net.*;

public class Main
{
   public static void main(String []args) {
      try {
         InetAddress local = InetAddress.getLocalHost();

         System.out.println ("IP of localhost: " + local.getHostAddress());
      }
      catch(UnknownHostException e) {
         System.out.println(e);
      }
   }
}

displays:

IP of localhost: 212.190.6.190

Checking the last-modified date of a URL file

The getLastModified() Method in the URLConnection connection class allows you to get the Last modified date.

It can be done in the following manner:

...
        String urlpath = new String("http://www.esus.com/respondquestionexample.html");
	url = new URL(urlpath);
	connection = url.openConnection();
        connection.connect();
        System.out.println(urlpath+ " was last modified on "+ new java.util.Date(connection.getLastModified()));
...

The getLastModified() method returns a long value, the number of seconds since the start of the epoch( 1970 ) till the modified date. The output for the above url was “Last Modified on Thu Apr 19 03:01:25 GMT+05:30 2001″

When to use UDP sockets

TCP sockets are connection-oriented and reliable sockets i.e they make sure for data to be successfully transmitted to destination, so if u want to transfer files or some imp. data u need to do it thru TCP

on the contrary, UDP sockets are connection less i.e. data divided into packets can transfer to dest. via any of valid routes and as no acknowledgement is required from destn. it is unreliable data transfer mode so if you are transferring lee useful data like some voice rec. or video streams u can use it.

Creating a digital certificate with keytool

Look at the command-line options of keytool.

For example, to create a public/private key pair and store it in the default keystore (in my case C:Windows.keystore) under the alias mykey:

C:> keytool -genkey -keyalg RSA -alias mykey
Enter keystore password:  esuspass
keytool error: Key pair not generated, alias <mykey> already exists

C:>keytool -genkey -keyalg RSA -alias esuskey
Enter keystore password:  esuspass
What is your first and last name?
  [Unknown]:  Joris Van den Bogaert
What is the name of your organizational unit?
  [Unknown]:  Esus Team
What is the name of your organization?
  [Unknown]:  Esus, Inc.
What is the name of your City or Locality?
  [Unknown]:  Meerbeek
What is the name of your State or Province?
  [Unknown]:
What is the two-letter country code for this unit?
  [Unknown]:  BE
Is <CN=Joris Van den Bogaert, OU=Esus Team, O="Esus, Inc.", L=Meerbeek, ST=Unkno
wn, C=BE> correct?
  [no]:  yes

Encrypting/decrypting a message using a symmetric encryption method (eg. DES)

Eric Young has written an implementation of DES. Here are the source files:

Des.java
DesCrypt.java
DesKey.java
Int32Manipulator.java

The Des.java file has been slightly modified (added a memset method to ensure 8 bytes are used for the key).

Here’s an example on how to use these classes:

public class Main
{
   public static void main(String []args) {
      // key (8 bytes) 
      String key = "12345678";
 
      // encrypt using Eric Young's DES Java implementation
      byte[] de = Des.encrypt(key, "Esus.com, aiming to provide the largest Java directory on the web");
 
      // decrypt 
      String s = Des.decrypt(key, de);
      System.out.println(s);
   }
}