FileDocCategorySizeDatePackage
MappedHttp.javaAPI DocExample3108Mon May 20 00:24:28 BST 2002com.ronsoft.books.nio.channels

MappedHttp

public class MappedHttp extends Object
Dummy HTTP server using MappedByteBuffers. Given a filename on the command line, pretend to be a web server and generate an HTTP response containing the file content preceded by appropriate headers. The data is sent with a gathering write. Created: April 2002
author
Ron Hitchens (ron@ronsoft.com)
version
$Id: MappedHttp.java,v 1.3 2002/05/20 07:24:29 ron Exp $

Fields Summary
private static final String
OUTPUT_FILE
private static final String
LINE_SEP
private static final String
SERVER_ID
private static final String
HTTP_HDR
private static final String
HTTP_404_HDR
private static final String
MSG_404
Constructors Summary
Methods Summary
private static byte[]bytes(java.lang.String string)

		return (string.getBytes ("US-ASCII"));
	
public static voidmain(java.lang.String[] argv)


	      
		 
	
		if (argv.length < 1) {
			System.err.println ("Usage: filename");
			return;
		}

		String file = argv [0];
		ByteBuffer header = ByteBuffer.wrap (bytes (HTTP_HDR));
		ByteBuffer dynhdrs = ByteBuffer.allocate (128);
		ByteBuffer [] gather = { header, dynhdrs, null };
		String contentType = "unknown/unknown";
		long contentLength = -1;

		try {
			FileInputStream fis = new FileInputStream (file);
			FileChannel fc = fis.getChannel();
			MappedByteBuffer filedata =
				fc.map (MapMode.READ_ONLY, 0, fc.size());

			gather [2] = filedata;

			contentLength = fc.size();
			contentType = URLConnection.guessContentTypeFromName (file);
		} catch (IOException e) {
			// file could not be opened, report problem
			ByteBuffer buf = ByteBuffer.allocate (128);
			String msg = MSG_404 + e + LINE_SEP;

			buf.put (bytes (msg));
			buf.flip();

			// use the HTTP error response
			gather [0] = ByteBuffer.wrap (bytes (HTTP_404_HDR));
			gather [2] = buf;

			contentLength = msg.length();
			contentType = "text/plain";
		}

		StringBuffer sb = new StringBuffer();
		sb.append ("Content-Length: " + contentLength);
		sb.append (LINE_SEP);
		sb.append ("Content-Type: ").append (contentType);
		sb.append (LINE_SEP).append (LINE_SEP);

		dynhdrs.put (bytes (sb.toString()));
		dynhdrs.flip();

		FileOutputStream fos = new FileOutputStream (OUTPUT_FILE);
		FileChannel out = fos.getChannel();

		// all the buffers have been prepared, write 'em out
		while (out.write (gather) > 0) {
			// empty body, loop until all buffers empty
		}

		out.close();

		System.out.println ("output written to " + OUTPUT_FILE);