20-CS-694 Advanced Programming Techniques Spring 2012
Networking - Content Handler

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

     Previous     x_tar.java     Tar.java      All lectures

Content Handler for x-tar Files

This is the content handler. It merely lists the files that are packed into a tar file with sizes and dates. Its class file x_tar.class is placed in directory contenthandlers/application where contenthanders is in the classpath. The names x_tar and application are mandatory and represent the content type application/x-tar (java does not allow file names to contain hypens so underscore is used instead). See notes on the previous slide for more details.
package contenthandlers.application;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;

public class x_tar extends ContentHandler {
   static int
      RECORDLEN = 512,
      NAMEOFF = 0,
      NAMELEN = 100,
      SIZEOFF = 124,
      SIZELEN = 12,
      MTIMEOFF = 136,
      MTIMELEN = 12;
   public Object getContent (URLConnection url) throws IOException {
      InputStream is = url.getInputStream();
      StringBuffer output = new StringBuffer("Tape Archive Listing:\n\n");
      byte header[] = new byte[RECORDLEN];
      int count = 0;
      while ((is.read(header) == RECORDLEN) && (header[NAMEOFF] != 0)) {
         String name = new String (header, NAMEOFF, NAMELEN,  "8859_1").trim();
         String s = new String(header, SIZEOFF, SIZELEN, "8859_1").trim();
         int size = Integer.parseInt(s, 8);
         s = new String(header, MTIMEOFF, MTIMELEN, "8859_1").trim();
         long l = Integer.parseInt(s, 8);
         Date mtime = new Date(l*1000);
         count += is.skip(size) + RECORDLEN;
         if (count % RECORDLEN != 0)
            count += is.skip(RECORDLEN - count % RECORDLEN);
      if (count == 0) output.append("Not a valid TAR file\n");

      return output.toString();