Bringing up the Windows Display Properties Window

Look at one of the other questions (eg. how do I bring up the dail-up connection window) on how to call the following external program. You can specify the startup tab.

   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0
   result:
            displays the Background tab selected
               
   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1
   result:
            displays the Screen Saver tab selected
               
   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,2
   result:
            displays the Appearance tab selected
               
   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,3
   result:
            displays the Settings tab selected

Using Runnable or extending the Thread class

Java does not support multiple inheritance. If your class already extends from a superclass and want to make it threadable, you will have to use the Runnable interface. In general, it’s good OO practice if you implement Runnable thereby saying your class is a generic Thread, instead of extending it saying “it’s kindof a thread but i want to modify some of the Thread class behavior”. Also, you typically don’t know what’s ahead in your project. If you extend from Thread and your design changes in such a way that you have to extend from another class, you’ll have to do some extra work.

In this example, class A extends from Thread, and class B implements Runnable.

Main.java:

import java.util.*;
import java.io.*;
  
public class Main {   
   public static void main(String[] args) {
 
      // starts object of class extending Thread
      new A().start();
 
      // starts object of class implementing Runnable
      new Thread(new B()).start();
   }
}
 
class A extends Thread {
   public void run() {
      System.out.println("Thread A started (and over)");
   }
}
 
class B implements Runnable {
   public void run() {
      System.out.println("Thread B started (and over)");
   }
}

Rounding up a float or a double

Use the ceil method in the Math class. It rounds up to the next higher integer:

import java.math.*;
                           
public class Main 
{  
   public static void main(String args[]) throws Exception {
      double d1 = 1.3, 
             d2 = 1.8,
             d3 = -1.3, 
             d4 = -1.8;
 
      System.out.println(Math.ceil(d1));
      System.out.println(Math.ceil(d2));
      System.out.println(Math.ceil(d3));
      System.out.println(Math.ceil(d4));
   }
}

outputs:

2.0
2.0
-1.0
-1.0

Converting a BigDecimal to a primitive type

Use the methods doubleValue, floatValue, intValue or longValue.

Main.java:

import java.math.*;
  
public class Main {
   public static void main(String args[]) {
      BigDecimal bd = new BigDecimal("4.9");
 
      int bdInt       = bd.intValue();
      long bdLong     = bd.longValue();
      float bdFloat   = bd.floatValue();
      double bdDouble = bd.doubleValue();
 
      System.out.println("Conversion " + bd + " to:");
      System.out.println("tint:t" + bdInt);
      System.out.println("tlong:t" + bdLong);
      System.out.println("tfloat:t" + bdFloat);
      System.out.println("tdouble:t" + bdDouble);
   } 
}

outputs:

Conversion 4.9 to:
	int:	4
	long:	4
	float:	4.9
	double:	4.9

Reading POP3 email with Java

You can try the optional package JavaMail (check out this category).

If you know the POP commands, you can write a pop client yourself. Here’s an example:

POPEmail.java:

import java.io.*;
import java.net.*;
 
public class POPEmail
{
    private Socket popSocket;
    private String popHost;
    private String username;
    private String password;
    private BufferedReader br;
    private BufferedWriter bw;
       
    private String smtpHost;
    
    public POPEmail(String popHost, String username, String password) throws IOException {
        this.popHost = popHost;
        this.username = username;
        this.password = password;
    }
    
    public void connect() throws IOException {
        popSocket = new Socket(popHost, 110);
        br = new BufferedReader(new InputStreamReader(popSocket.getInputStream()));        
        bw = new BufferedWriter(new OutputStreamWriter(popSocket.getOutputStream()));
        send("USER " + username);
        receive();
        send("PASS " + password);
        String status = receive();
        if (status.startsWith("-ERR"))
            throw new java.io.IOException("ERROR: USER/PASSW WRONG.");
    }
    
    public void disconnect() throws IOException {
        send("QUIT");
        receive();
        popSocket.close();
    }
    
    private void send(String str) throws IOException {
        //System.out.println("Sending: " + str);
        bw.write(str + "rn");
        bw.flush();
    }
    
    private String receive() throws IOException {
        String str = br.readLine();
        //System.out.println("Receiving: " + str);
        return str;
    }
    
    public int getMessageCount() {
        try {
            send("LIST");
            int n = 0;
            String line = receive();
            while (!line.equals(".")) {
                line = receive();
                try {
                    if (!line.equals("."))
                        n = Integer.parseInt(line.substring(0, line.indexOf(" ")));
                }
                catch(NumberFormatException nfe) { }
            }
            
            return n;
        }
        catch(IOException e) { }
        
        return 0;
    }
    
    public EmailMessage getMessage(int messagenumber) throws IOException {
        send("RETR " + messagenumber);
        String status = receive();
        if (status.startsWith("-ERR")) throw new IOException("Message does not exist!");
        else {
            StringBuffer stringMsg = new StringBuffer();
            String line;
            do {
                line = receive();
                stringMsg.append(line + "rn");
            } while (!line.equals("."));
            
            EmailMessage message = new EmailMessage();
            message.parse(stringMsg.toString());
            return message;
        }
    }
}

EmailMessage.java:

import java.util.*;
 
public class EmailMessage implements java.io.Serializable
{
    public String from;
    public String replyTo;
    public String to;
    public String subject;
    public String date;
    public String MIMEVersion;
    public String priority;
    public String contentType;
    public String body;
    
    public EmailMessage() {
        from = replyTo = to = subject = date = 
              MIMEVersion = priority = contentType = body = "";
    }
    
    public void parse(String message) {
        StringTokenizer st = new StringTokenizer(message, "rn");
        while (st.hasMoreElements()) {
            String line = (String) st.nextElement();
            //System.out.println("parsing: " + line);
            
            if (line.startsWith("From:"))
                from = line.substring(6);
            else if (line.startsWith("Reply-To:"))
                replyTo = line.substring(10);
            else if (line.startsWith("To:"))
                to = line.substring(4);
            else if (line.startsWith("Subject:"))
                subject = line.substring(9);
            else if (line.startsWith("Date:"))
                date = line.substring(6);
            else if (line.startsWith("MIME-Version:"))
                MIMEVersion = line.substring(14);
            else if (line.startsWith("X-Priority:"))
                priority = line.substring(12);
            else if (line.startsWith("Content-Type:"))
                contentType = line.substring(14);
            else if (line.trim().equals("")) {  // body
                StringBuffer sb = new StringBuffer();
                while (!line.equals(".")) {
                    sb.append(line);
                    line = (String) st.nextElement();
                }
            }    
        }
    }
    
    public String toString() {
        return "From: " + from + "rn" +
               "To: " + to + "rn" + 
               "Reply-To: " + replyTo + "rn" +
               "Subject: " + subject + "rn";
    }
}

Main.java:

import java.io.*; 
 
public class Main {
   public static void main(String[] args) {
      if (args.length != 3) {
         System.err.println("usage: java Main <POP server> <user> <pass>");
         System.exit(1);
      }
  
      try {
         POPEmail pop = new POPEmail(args[0], args[1], args[2]);
         pop.connect();
         System.out.println("There are " + pop.getMessageCount() + " message(s) waiting...");
         pop.disconnect();
      }
      catch(IOException e) {
         e.printStackTrace();
      }           
   }
}

Determining whether an IP address is a multicast address

A multicast address is an ip address used to denote multiple recepients. They fall in the range 224.0.0.1 to 239.255.255.255. You can use invoke the method isMulticastAddress on an instance of InetAddress to determine whether the specified address falls within that range.

Main.java:

import java.net.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         InetAddress address1 = InetAddress.getByName("205.178.180.16");
         InetAddress address2 = InetAddress.getByName("224.120.50.1");
 
         System.out.println(address1.isMulticastAddress());
         System.out.println(address2.isMulticastAddress());
      }
      catch(UnknownHostException e) {
         System.out.println(e);
      }
   }
}

outputs:

false
true

What is privileged code?

It allows you to temporarily grant permission to code that would normally not have permission to run. Normally, the entire execution stack (all callers) needs to have permission to do a sensitive operation.

With Privileged Code, you can specify in a fine-grained way that only the final class in the execution stack needs permission.

For example, consider the following two classes.

Main.java:

public class Main
{
   public static void main(String []args) {
      LowLevel.executeLowLevelAction();
   }
}

LowLevel.java:

public class LowLevel
{
   public static void executeLowLevelAction() {
      System.out.println(System.getProperty("test"));
   }
}

The Main class just executes the static method executeLowLevelAction that gets the property
test.
Run log:

C:> java -Dtest="Hello, World!" Main
Hello, World!
 
C:> java -Dtest="Hello, World!" -Djava.security.manager Main
Exception in thread "main" java.security.AccessControlException: access denied
java.util.PropertyPermission test read)
        at java.security.AccessControlContext.checkPermission(AccessControlCont
xt.java:195)
        at java.security.AccessController.checkPermission(AccessController.java
403)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
        at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1
43)
        at java.lang.System.getProperty(System.java:539)
        at LowLevel.executeLowLevelAction(LowLevel.java:6)
        at Main.main(Main.java:4)

As you expected, the first run can just get the property test without needing any permissions (as no security manager is installed by default). In the second run, we ask the VM to set up a default SecurityManager which results in an AccessControlException because reading System Property “test” is not allowed.

To grant permission to read this property, we need to write a policy security configuration file. But we really only want the class LowLevel to have permission to read the property. We do not want to grant the calling class Main that permission.

So what we could do is jar the LowLevel class up and write a policy file to grant that jar file additional permissions:

C:> jar cvf LowLevel.jar LowLevel.class
added manifest
adding: LowLevel.class(in = 474) (out= 308)(deflated 35%)

C:> del LowLevel.class

mypolicy:

grant codeBase "file:/c:/LowLevel.jar" {
   Permission java.util.PropertyPermission "test", "read";
};

Run log:

C:> java -Dtest="Hello, World!" -Djava.security.manager 
          -Djava.seurity.policy=mypolicy Main
 
Exception in thread "main" java.security.AccessControlException: access denied
java.util.PropertyPermission test read)
        at java.security.AccessControlContext.checkPermission(AccessControlCont
xt.java:195)
        at java.security.AccessController.checkPermission(AccessController.java
403)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
        at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1
43)
        at java.lang.System.getProperty(System.java:539)
        at LowLevel.executeLowLevelAction(LowLevel.java:6)
        at Main.main(Main.java:4)

AccessControlException!!? How come? Didn’t we grant the permission to LowLevel.jar to read the property “test”? The problem lays in the requirement that every class in the execution stack must have the permission.

The solution is to make the System.getProperty call in a Privileged Block. This could be done as follows.

LowLevel.java:

import java.security.*;
 
public class LowLevel
{
   public static void executeLowLevelAction() {
      String testprop = (String) AccessController.doPrivileged(new PrivilegedAction() {
         public Object run() {
            return System.getProperty("test");
         }
      });
      System.out.println(testprop);
   }
}

Compile and jar it up:

C:> javac LowLevel.java

C:> jar cvf LowLevel.jar LowLevel.class LowLevel$1.class
added manifest
adding: LowLevel.class(in = 603) (out= 384)(deflated 36%)
adding: LowLevel$1.class(in = 449) (out= 307)(deflated 31%)
 
C:> del LowLevel*.class

and run it again:

C:> java -Dtest="Hello, World!" -Djava.security.manager -Djava.sec
urity.policy=mypolicy Main
Hello, World!

Now we get the correct response: allowing only the class LowLevel to run “sensitive” code, no matter who called it, so without worrying about the executing stack.

Difference between the methods update() and doFinal() in Cipher

update() adds data to the Cipher’s internal buffer, then returns all currently completely encoded blocks. If there are any encoded blocks left over, they remain in the Cipher’s buffer until the next call, or a call to doFinal(). This means that if you call update() with a four byte array to encrypt, and the buffer size is eight bytes, you will not receive encoded data on the return (you’ll get a null instead). If your next call to update() passes five bytes of data in, you will get an 8 byte (the block size) array back, containing the four bytes passed in on the previous call, the first four bytes from the current call – the remaining byte from the current call is left in the Cipher’s buffer.

doFinal() on the other hand is much simpler: it encrypts the passed data, pads it out to the necessary length, and then returns it. The Cipher is essentially stateless.

Encrypting/decrypting with the IDEA algorithm

IDEA stands for International Data Encryption Algorithm. It is a patented, commercial algorithm that is fairly new (1990). It is faster than DES and considered more secure. It is used in PGP and SSL.

The IDEA key size is 128 bit and block size 64 bit.

Main.java:

import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      String toEncrypt = "The shorter you live, the longer you're dead!";
 
      System.out.println("Encrypting...");
      byte[] encrypted = encrypt(toEncrypt, "password");
 
      System.out.println("Decrypting...");
      String decrypted = decrypt(encrypted, "password");
    
      System.out.println("Decrypted text: " + decrypted);
   } 
 
   public static byte[] encrypt(String toEncrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance("IDEA");
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // create an instance of cipher
      Cipher cipher = Cipher.getInstance("IDEA");
 
      // initialize the cipher with the key 
      cipher.init(Cipher.ENCRYPT_MODE, sk);
 
      // enctypt!
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
 
      return encrypted;
   }
 
   public static String decrypt(byte[] toDecrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance("IDEA");
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // do the decryption with that key
      Cipher cipher = Cipher.getInstance("IDEA");
      cipher.init(Cipher.DECRYPT_MODE, sk);
      byte[] decrypted = cipher.doFinal(toDecrypt);
 
      return new String(decrypted);
   }
}

(tested with the BouncyCastle JCE provider, http://www.bouncycastle.org)

Get started with JAAS

JAAS stands for Java Authentication and Authorization Service. It allows you to grant permission based on who is executing the code. Previous security models already granted permission based on where the code was coming from and who signed it. JAAS has been added to JDK1.4 and the examples here will use that JDK. If you want to run them with JDK version 1.3, download the optional JAAS package here and put jaas.jar in jdk1.3/jre/lib/ext.

JAAS consists of two components: the authentication component and the authorization component. The Authentication component determines who is attempting to run code. The authorization component determines if that entity has the necessary permissions to run that code.

To find out how to authenticate with JAAS, check out JAAS Authentication.
To find out how to allow or deny access to resources, check out JAAS Declarative Authorization and JAAS Programmatic Authorization.