lørdag den 24. oktober 2009

The simplest possible "wget"/"curl" downloader in Java to bootstrap a new Java environment

Occasionally you have to work or deploy code on a server where you are severely limited in what you can and may do. If so, you may not have access to a browser so you can download files, or a gzip implementation so you can unpack files or a compiler so you can add programs that can do those things you need. I am frequently in this position as my job is to run Java program on AS/400 machines.

Plenty of Java programs exist which can help with all this, but you still need to download them in the first place. You may have access to an ftp program but these days that is often not enough as things tend to be accessible for browsers only. I have not found an out-of-the-box way to get Java to run code from the net in a telnet connection which doesn't have a GUI so the hen-and-egg-problem is getting to download a program which allow you to download programs.

Fortunately most telnet programs allow for pasting in information, so a Java program that will fit on a single editor screen can easily be saved to a file, and compiled with javac to running code. So save the following snippet as "Get.java":

=======================================
      import java.io.*;
import java.net.URL;

public class Get {
public static void main(String[] args) throws Exception {
System.out.println(args[0] + " -> " + args[1]);
InputStream in = new URL(args[0]).openStream();
OutputStream out = new FileOutputStream(args[1]);
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
=======================================

Compile it with:

=======================================
javac Get.java
=======================================

If you have a CLASSPATH variable then put Get.class in the CLASSPATH otherwise you can just run it with:

=======================================
java Get http://www.google.dk google.txt
=======================================

This saves the Google home page in the file "google.txt". You can then download zip-files directly and unzip them with jar. For instance to download and unpack ant so you can use build.xml-files you can use

=======================================
java Get http://mirrors.dotsrc.org/apache/ant/ant-current-bin.zip ant.zip
jar xvf ant.zip
=======================================

If you need to go through a proxy, then do the same configuration as you would do for any other Java program.

1 kommentar:

Thorbjørn Ravn Andersen sagde ...

For OS/400 first create the file in the right code page:

/usr/bin/touch -C 819 Get.java