Add separate handling of response status.
[jrw.git] / src / jrw / Request.java
1 package jrw;
2
3 import java.util.*;
4
5 public class Request {
6     public final Map<Object, Object> env;
7     public final Map<Object, Object> resp = new HashMap<>();
8     public String status = "200 OK";
9     public Object body = null;
10
11     public Request(Map<Object, Object> env) {
12         this.env = env;
13     }
14
15     public String ihead(String name, String def) {
16         StringBuilder buf = new StringBuilder();
17         buf.append("HTTP_");
18         for(int i = 0; i < name.length(); i++) {
19             char c = name.charAt(i);
20             if(c == '-')
21                 buf.append('_');
22             else if((c >= 'a') && (c <= 'z'))
23                 buf.append((char)(c + ('A' - 'a')));
24             else
25                 buf.append(c);
26         }
27         Object ret = env.get(buf.toString());
28         if(ret instanceof String)
29             return((String)ret);
30         return(def);
31     }
32
33     @SuppressWarnings("unchecked")
34     public Request ohead(String name, Object val, boolean repl) {
35         name = "http." + name;
36         if(repl) {
37             resp.put(name, val);
38         } else {
39             Object cur = resp.get(name);
40             if(cur == null)
41                 resp.put(name, val);
42             else if(cur instanceof Collection)
43                 ((Collection)cur).add(val);
44             else
45                 resp.put(name, new ArrayList<Object>(Arrays.asList(cur, val)));
46         }
47         return(this);
48     }
49
50     public Request status(String status) {this.status = status; return(this);}
51     public Request body(Object body) {this.body = body; return(this);}
52
53     public Map<Object, Object> response() {
54         resp.put("http.status", status);
55         resp.put("jagi.output", body);
56         return(resp);
57     }
58 }