Dynamically compile a Java source file and execute a method on it

You can use the package sun.tools.javac located in JDK/lib/tools.jar. Make sure you add this Jar file to your classpath!

When your invoke compile, you pass a String array containing the file to compile, and optionally also other compile options, eg. new String[] { “-classpath”, “c:mylibs”, “Test.java” }.

Main.java:

import java.lang.reflect.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
      sun.tools.javac.Main compiler = 
             new sun.tools.javac.Main(baos, "javac"); 
      boolean compileOk = compiler.compile(new String[] {"Test.java"}); 
 
      System.out.println("Compiled ok? " + compileOk);
 
      if (compileOk) {
         Class c = Class.forName("Test");
         // create a new instance of Test
         Object o = c.newInstance();
  
         // invoke a method on it
         Method m = c.getMethod("method", new Class[] { });
         m.invoke(o, new Object[] { });
      }
      else {
         System.out.println("Error compiling");
      }
   }
}

Test.java:

public class Test
{
   public void method() {
      System.out.println("Method in class Test executed!");
   }
}

Running Main outputs:

Compiled ok? true
Method in class Test executed!

Creating Java Threads

A thread allows you to do more things at once. It’s like a family sitting at the dinner table with in the middle one big pot of spaghetti (CPU). Every member of the family would be a thread and everybody gets its turn to eat some.

For Sun’s definition, check here: What is a thread?

There are several ways to create a thread. The following are a couple of examples that will each perform the same two tasks: 1) ask for first and last name of user with System.in 2) calculate the sum of all numbers from 1 to 123456789. While the program is waiting for input from the user, it is meanwhile performing the calculation.

Method 1

Extend from Thread class, define a public void run() method (the starting point of a thread) and call start on an instance of that class:

ThreadExample1.java:

import java.io.*;
 
public class ThreadExample1
{
   public static void main(String []args) {
      // create instance of thread1 and 2
      UserInputThread thread1   = new UserInputThread();
      CalculationThread thread2 = new CalculationThread();
 
      // start up the threads, start is defined in the
      // Thread class and the VM will call the run() method
      thread1.start();
      thread2.start();      
   }
}
 
// Thread 1: ask for user input
class UserInputThread extends Thread
{
   public void run() {
      try {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         System.out.println("What is your first name?");
         String firstName = br.readLine();
         System.out.println("What is your last name?");
         String lastName  = br.readLine();
 
         System.out.println("Hi " + firstName + " " + lastName);
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}
 
// Thread 2: perform some calculation
class CalculationThread extends Thread
{
   public void run() {
      int n = 123456789;
      long total = 0;
      for (int i=1; i<n; i++) {
         total += i;
      }
      System.out.println("Total of summing up numbers from 1 to " + n + " = " + total);
   }
}

Method 2

Mark the class you want as a thread with the interface Runnable, define a public void run() method (the starting point of a thread), pass the Runnable class to a new instance of a Thread and call start on it:

ThreadExample2.java:

import java.io.*;
 
public class ThreadExample2
{
   public static void main(String []args) {
      // create an instance of each class, both implement
      // the interface Runnable 
      Runnable thread1 = new UserInputThread();
      Runnable thread2 = new CalculationThread();
 
      // create instances of Thread and pass the Runnable 
      // objects.  Starting up the threads will cause the
      // VM to call run()
      new Thread(thread1).start(); 
      new Thread(thread2).start();
   }
}
 
// Thread 1: ask for user input
class UserInputThread implements Runnable
{
   public void run() {
      try {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         System.out.println("What is your first name?");
         String firstName = br.readLine();
         System.out.println("What is your last name?");
         String lastName  = br.readLine();
 
         System.out.println("Hi " + firstName + " " + lastName);
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}
 
// Thread 2: perform some calculation
class CalculationThread implements Runnable
{
   public void run() {
      int n = 123456789;
      long total = 0;
      for (int i=1; i<n; i++) {
         total += i;
      }
      System.out.println("Total of summing up numbers from 1 to " + n + " = " + total);
   }
}

Method 3

Compact, anonymous instance:

ThreadExample3.java:

import java.io.*;
 
public class ThreadExample3
{
   public static void main(String []args) {
      // create thread 1, override run() and start it
      new Thread() {
         public void run() {
            try {
               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
               System.out.println("What is your first name?");
               String firstName = br.readLine();
               System.out.println("What is your last name?");
               String lastName  = br.readLine();
 
               System.out.println("Hi " + firstName + " " + lastName);
            }
            catch(IOException e) {
               e.printStackTrace();
            }
         }
      }.start();
 
      // create thread 2, override run() and start it
      new Thread() {
         public void run() {
            int n = 123456789;
            long total = 0;
            for (int i=1; i<n; i++) {
               total += i;
            }
            System.out.println("Total of summing up numbers from 1 to " + n + " = " + total);
         }
      }.start();
   }
}

Timeout on a network connection

If you didn’t know that there is a method available, you’d probably think of using a timer thread that closes the connection when it times out. There is an easier way to handle network timeouts. You can have better
control over your socket communications using socket options. And, to make developer’s life easy, there is this useful option called SO_TIMEOUT.

import java.net.*;
import java.io.*;
 
public class Main
{
   public static void main(String args[]) throws Exception {
      if (args.length != 3) {
         System.err.println("Usage: java Main <URL> <PORT> <TIMEOUT>");
         System.exit(1);
      }
  
      Socket s = new Socket(args[0], Integer.parseInt(args[1]));
 
      // set a timeout (in milliseconds)
      s.setSoTimeout(Integer.parseInt(args[2]));
 
      BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
      DataOutputStream dos = new DataOutputStream(s.getOutputStream());
 
      // get the homepage (/) by sending a GET command to the HTTP port
      dos.writeBytes("GET / HTTP/1.0rnrn");
 
      // read response, when timeout occurs, InterruptedIOException is thrown
      try {
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch(InterruptedIOException e) {
         System.out.println("Timed out after " + args[2] + " milliseconds.");
      }
      finally {
         br.close();
      }
   }
}

Now try to run it with different values for timeout:

C:> java Main www.yahoo.com 80 10
Timed out after 10 milliseconds.
 
C:> java Main www.esus.com 80 1000
 
[snip: yahoo home]

Pinging a host in Java

Why can’t I write ping in Java?
Ping requires ICMP packets. These packets can only be created via a socket of the SOCK_RAW type. Currently, Java only allows SOCK_STREAM (TCP) and SOCK_DGRAM (UDP) sockets. It seems unlikely that this will be added very soon, since many Unix versions only allow SOCK_RAW sockets to be created by root, and winsock does not address ICMP packets (win32 includes an unsupported and undocumented ICMP.DLL).

For a full discussion of socket types, see Stevens’ book (in the bibliography).

Rolling your own SecurityManager

If you look in the source code for FileOutputStream, you’ll notice that, before a file is created and written to, a check is performed to see whether it is allowed to do so.

java.io.FileOutputStream.java:

    public FileOutputStream(String name, boolean append)
        throws FileNotFoundException
    {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkWrite(name);
	}
      . . .

If no SecurityManager is installed, System.getSecurityManager will return null and no security checks will be performed. We can see that happening by just creating an application that writes to a file.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String []args) throws Exception {
      FileOutputStream fos = new FileOutputStream("testfile.txt");
      fos.write("hey".getBytes());
      fos.close();
      System.out.println("testfile.txt successfully written!");
   }
}

Running this code with java Main will write the file testfile.txt. If you run this code with java -Djava.security.manager Main, notice that an exception is thrown:

 Exception in thread "main" java.security.AccessControlException: access denied (
java.io.FilePermission testfile.txt write)
        at java.security.AccessControlContext.checkPermission(AccessControlConte
xt.java:195)
        at java.security.AccessController.checkPermission(AccessController.java:
403)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
        at java.lang.SecurityManager.checkWrite(SecurityManager.java:958)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:96)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:62)
        at Main.main(Main.java:5)

We could write our own SecurityManager that allows to write to testfile.txt and restricts everything else to the security sandbox.

MySecurityManager.java:

import java.io.*;
 
public class MySecurityManager extends SecurityManager {
   public void checkWrite(String file) {
      if (!file.equals("testfile.txt")) {
         throw new SecurityException("Only allowed to write to file testfile.txt.");
      }
   }
}

Now we can use our new security manager by either specifying it at command line:

C:> java -Djava.security.manager=MySecurityManager Main
testfile.txt successfully written!

or by doing so programmatically:

import java.io.*;
 
public class Main {
   public static void main(String []args) throws Exception {
      System.setSecurityManager(new MySecurityManager()); 
 
      FileOutputStream fos = new FileOutputStream("testfile.txt");
      fos.write("hey".getBytes());
      fos.close();
      System.out.println("testfile.txt successfully written!");
   }
}

Running:

C:> java Main
testfile.txt successfully written!

A custom security manager can be useful in JDK1.1 applications. However, it becomes a real pain (lots of programming) when you want to specify security restrictions based on who is running the code or where the code is coming from.

From JDK1.2, you can use policy files to customize the security manager in a fine-grained fashion. Let’s use the original program:
Main.java:

import java.io.*;
 
public class Main {
   public static void main(String []args) throws Exception {
      FileOutputStream fos = new FileOutputStream("testfile.txt");
      fos.write("hey".getBytes());
      fos.close();
      System.out.println("testfile.txt successfully written!");
   }
}

and write a policy file that allows writing to only the file testfile.txt:
mypolicy.txt

grant {
   permission java.io.FilePermission "testfile.txt", "write";
};

Run the code and specify the policy file to be used at runtime:

C:> java -Djava.security.policy=mypolicy.txt -Djava.security.manager Main
testfile.txt successfully written!

Install the free Bouncy Castle JCE Provider

Bouncy Castle is a free provider for JCE. These following steps will explain how to add this security provider.

  1. Download the latest release for your JDK version at http://www.bouncycastle.org/latest_releases.html
  2. Extract the zip file in your home directory
  3. BouncyCastle doens’t come with a JAR file. In order to add it to the bootclasspath, create one:
         c:jce-jdk12-107classes> jar cvf bouncycastle.jar *
         c:jce-jdk12-107classes> copy bouncycastle.jar c:jdk1.2.2jrelibext
    
  4. Go to your JAVA_HOME/jre/lib/security directory and edit the file java.security. Look at the configuration, in my case it says something like:
       security.provider.1=sun.security.provider.Sun
       security.provider.2=com.sun.crypto.provider.SunJCE
    

    Add the line security.provider.3=org.bouncycastle.jce.provider.BouncyCastleProvider

  5. Run one of the examples to see if it is working (eg. How do I crypt/decrypt a message with the Blowfish algorithm?)

Update:

This information is outdated. Now, you can download JAR versions for your JDK version.

For 1.3.1, I downloaded jce-jdk13-118.jar and bcprov-jdk13-118.jar and added them to my classpath (you can also put them in jdk1.3.1/jre/lib/ext and NOT add them to your classpath).

You can add a static provider to jdk1.3.1/jre/lib/security/java.security as described above or you can do this programmatically in your code:

...
   java.security.Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
   Security.addProvider(provider);