comparison src/goodjava/webserver/Response.java @ 1402:27efb1fcbcb5

move luan.lib to goodjava
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 17 Sep 2019 01:35:01 -0400
parents src/luan/lib/webserver/Response.java@643cf1c37723
children ef9d96aeb541
comparison
equal deleted inserted replaced
1401:ef1620aa99cb 1402:27efb1fcbcb5
1 package goodjava.webserver;
2
3 import java.io.InputStream;
4 import java.io.PrintWriter;
5 import java.util.Map;
6 import java.util.LinkedHashMap;
7 import java.util.Collections;
8 import java.util.List;
9
10
11 public class Response {
12 public final String protocol = "HTTP/1.1";
13 public volatile Status status = Status.OK;
14 public final Map<String,Object> headers = Collections.synchronizedMap(new LinkedHashMap<String,Object>());
15 {
16 headers.put("server","Goodjava");
17 }
18 private static final Body empty = new Body(0,new InputStream(){
19 public int read() { return -1; }
20 });
21 public volatile Body body = empty;
22
23 public static class Body {
24 public final long length;
25 public final InputStream content;
26
27 public Body(long length,InputStream content) {
28 this.length = length;
29 this.content = content;
30 }
31 }
32
33
34 public void addHeader(String name,String value) {
35 Util.add(headers,name,value);
36 }
37
38 public void setCookie(String name,String value,Map<String,String> attributes) {
39 StringBuilder buf = new StringBuilder();
40 buf.append( Util.urlEncode(name) );
41 buf.append( '=' );
42 buf.append( Util.urlEncode(value) );
43 for( Map.Entry<String,String> entry : attributes.entrySet() ) {
44 buf.append( "; " );
45 buf.append( entry.getKey() );
46 buf.append( '=' );
47 buf.append( entry.getValue() );
48 }
49 addHeader( "Set-Cookie", buf.toString() );
50 }
51
52
53 public String toHeaderString() {
54 StringBuilder sb = new StringBuilder();
55 sb.append( protocol )
56 .append( ' ' ).append( status.code )
57 .append( ' ' ).append( status.reason )
58 .append( "\r\n" )
59 ;
60 for( Map.Entry<String,Object> entry : headers.entrySet() ) {
61 String name = entry.getKey();
62 Object value = entry.getValue();
63 if( value instanceof List ) {
64 for( Object v : (List)value ) {
65 sb.append( name ).append( ": " ).append( v ).append( "\r\n" );
66 }
67 } else {
68 sb.append( name ).append( ": " ).append( value ).append( "\r\n" );
69 }
70 }
71 sb.append( "\r\n" );
72 return sb.toString();
73 }
74
75
76 public static Response errorResponse(Status status,String text) {
77 Response response = new Response();
78 response.status = status;
79 response.headers.put( "content-type", "text/plain; charset=utf-8" );
80 PrintWriter writer = new PrintWriter( new ResponseOutputStream(response) );
81 writer.write( text );
82 writer.close();
83 return response;
84 }
85 }