modtime
an example compileAndGo script using Java
and illustrating the use of JNIDirect

This compileAndGo Java program is a simple wrapper for the unix stat system call. It’s simple because it uses Patrick Beard’s JNIDirect.jar, which contains magic that automatically writes and compiles JNI C code for you.

1 Z% ./modtime .
2005-07-29T17:07:05
3 Z% 

Here’s the modtime script.

#!/usr/bin/env compileAndGo
# See http://Yost.com/computers/compileAndGo
language  = java
classPath = $commandDir/JNIDirect.jar
verbose   = 2
!#

// See http://JNIDirect.org
// Look, Ma, no JNI!

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.nio.ByteBuffer;

public class modtime {
  public static void main(String args[]) {
    if (args.length != 1) {
      System.err.println("Usage: modtime file");
      System.exit(2);
    }
    String path = args[0];
    Posix_stat stat_buf;
    try {
      stat_buf = new Posix_stat(path);
      long size = stat_buf.size();
      System.out.println("size = " + size);
      long lastModified = stat_buf.lastModified();
      Date modtime = new Date(lastModified);
      final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
      System.out.println(dateFormat.format(modtime));
    } catch (IOException ex) {
      System.err.println("modtime: " + path + ": No such file or directory");
      System.exit(1);
    }
  }
}

class Posix_stat {

  Posix_stat(String path) throws IOException {
    buf = new $stat$();
    int err = stat((path + '\0').getBytes(), buf._bytes);
    if (err < 0) {
      throw new IOException();
    }
  }
  
  final $stat$ buf;

  long lastModified() {
    return buf._buffer.getInt(buf.$offsetof$st_mtime()) * 1000L;
  }

  long size() {
    return buf._buffer.getLong(buf.$offsetof$st_size());
  }

  static {
    //System.getProperties().setProperty("jnidirect.cache_libraries", "true");
    jnidirect.Linker.link(Posix_stat.class);
  }

  static native int stat(/* const char * */ byte[] path,
                         /* struct stat  */ byte[] stat_buf);
}

class $stat$ {
  static native int $sizeof$();
  static native int $offsetof$st_mtime();
  static native int $offsetof$st_size();
  static {
    jnidirect.Linker.struct($stat$.class, new String[] { "<sys/stat.h>" });
  }

  byte[] _bytes;
  ByteBuffer _buffer;

  $stat$() {
    _bytes = new byte[$sizeof$()];
    _buffer = ByteBuffer.wrap(_bytes);
  }
}


http://Yost.com/computers/compileAndGo/modtime.html - this page
2005-07-29 Created
2005-08-04 Modified for later JNIDirect version
2005-11-06 End the header with !# per compileAndGo 5.0