Initial commit.
[jagi.git] / src / jagi / Utils.java
CommitLineData
49ccd711
FT
1package jagi;
2
3import java.util.*;
4import java.io.*;
5import java.nio.*;
6import java.nio.channels.*;
7
8public class Utils {
9 public static final java.nio.charset.Charset UTF8 = java.nio.charset.Charset.forName("UTF-8");
10 public static final java.nio.charset.Charset LATIN1 = java.nio.charset.Charset.forName("ISO-8859-1");
11 public static final java.nio.charset.Charset ASCII = java.nio.charset.Charset.forName("US-ASCII");
12
13 public static int read(ReadableByteChannel ch) throws IOException {
14 ByteBuffer buf = ByteBuffer.allocate(1);
15 while(true) {
16 int rv = ch.read(buf);
17 if(rv < 0)
18 return(-1);
19 else if(rv == 1)
20 return(buf.get(0) & 0xff);
21 else if(rv > 1)
22 throw(new AssertionError());
23 }
24 }
25
26 public static ByteBuffer readall(ReadableByteChannel ch, ByteBuffer dst) throws IOException {
27 while(dst.remaining() > 0)
28 ch.read(dst);
29 return(dst);
30 }
31
32 public static void writeall(WritableByteChannel ch, ByteBuffer src) throws IOException {
33 while(src.remaining() > 0)
34 ch.write(src);
35 }
36
37 public static void transfer(WritableByteChannel dst, ReadableByteChannel src) throws IOException {
38 ByteBuffer buf = ByteBuffer.allocate(65536);
39 while(true) {
40 buf.clear();
41 if(src.read(buf) < 0)
42 break;
43 buf.flip();
44 while(buf.remaining() > 0)
45 dst.write(buf);
46 }
47 }
48
49 public static String htmlquote(CharSequence text) {
50 StringBuilder buf = new StringBuilder();
51 for(int i = 0; i < text.length(); i++) {
52 char c = text.charAt(i);
53 switch(c) {
54 case '&': buf.append("&amp;"); break;
55 case '<': buf.append("&lt;"); break;
56 case '>': buf.append("&gt;"); break;
57 case '"': buf.append("&quot;"); break;
58 default: buf.append(c); break;
59 }
60 }
61 return(buf.toString());
62 }
63
64 public static Map<Object, Object> simpleerror(int code, CharSequence title, CharSequence msg) {
65 StringBuilder buf = new StringBuilder();
66 buf.append("<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n");
67 buf.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n");
68 buf.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en-US\">\n");
69 buf.append("<head>\n");
70 buf.append("<title>" + title + "</title>\n");
71 buf.append("</head>\n");
72 buf.append("<body>\n");
73 buf.append("<h1>" + title + "</h1>\n");
74 buf.append("<p>" + htmlquote(msg) + "</p>\n");
75 buf.append("</body>\n");
76 buf.append("</html>\n");
77 ByteBuffer out = ASCII.encode(CharBuffer.wrap(buf));
78 Map<Object, Object> resp = new HashMap<>();
79 resp.put("http.status", code + " " + title);
80 resp.put("http.Content-Type", "text/html; charset=us-ascii");
81 resp.put("http.Content-Length", Integer.toString(out.remaining()));
82 resp.put("jagi.output", out);
83 return(resp);
84 }
85}