1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.esigate.servlet.impl;
17
18 import java.io.IOException;
19
20 import javax.servlet.http.HttpServletResponse;
21
22 import org.apache.http.Header;
23 import org.apache.http.HttpEntity;
24 import org.apache.http.HttpResponse;
25 import org.apache.http.cookie.Cookie;
26 import org.esigate.http.HttpResponseUtils;
27 import org.esigate.http.IncomingRequest;
28 import org.esigate.http.cookie.CookieUtil;
29
30
31
32
33
34
35 public class ResponseSender {
36
37 public void sendResponse(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response)
38 throws IOException {
39 if (response.isCommitted()) {
40 return;
41 }
42 sendHeaders(httpResponse, httpRequest, response);
43 HttpEntity httpEntity = httpResponse.getEntity();
44 if (httpEntity != null) {
45 HttpResponseUtils.writeTo(httpEntity, response.getOutputStream());
46 } else {
47 response.sendError(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine()
48 .getReasonPhrase());
49 }
50 }
51
52 void sendHeaders(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response) {
53 response.setStatus(httpResponse.getStatusLine().getStatusCode());
54 for (Header header : httpResponse.getAllHeaders()) {
55 String name = header.getName();
56 String value = header.getValue();
57 response.addHeader(name, value);
58 }
59
60
61 Cookie[] newCookies = httpRequest.getNewCookies();
62
63 for (Cookie newCooky : newCookies) {
64
65
66
67 if (newCooky != null) {
68 response.addHeader("Set-Cookie", CookieUtil.encodeCookie(newCooky));
69 }
70 }
71 HttpEntity httpEntity = httpResponse.getEntity();
72 if (httpEntity != null) {
73 long contentLength = httpEntity.getContentLength();
74 if (contentLength > -1 && contentLength < Integer.MAX_VALUE) {
75 response.setContentLength((int) contentLength);
76 }
77 Header contentType = httpEntity.getContentType();
78 if (contentType != null) {
79 response.setContentType(contentType.getValue());
80 }
81 Header contentEncoding = httpEntity.getContentEncoding();
82 if (contentEncoding != null) {
83 response.setHeader(contentEncoding.getName(), contentEncoding.getValue());
84 }
85 }
86 }
87
88 }