1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.eclipse.jetty.client;
15
16 import java.io.ByteArrayOutputStream;
17 import java.io.File;
18 import java.io.FileInputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.UnsupportedEncodingException;
22
23 import org.eclipse.jetty.http.HttpHeaders;
24 import org.eclipse.jetty.io.Buffer;
25 import org.eclipse.jetty.io.BufferUtil;
26 import org.eclipse.jetty.util.StringUtil;
27
28
29
30
31 public class ContentExchange extends CachedExchange
32 {
33 private int _contentLength = 1024;
34 private String _encoding = "utf-8";
35 private ByteArrayOutputStream _responseContent;
36 private File _fileForUpload;
37
38 public ContentExchange()
39 {
40 super(false);
41 }
42
43 public ContentExchange(boolean cacheFields)
44 {
45 super(cacheFields);
46 }
47
48 public String getResponseContent() throws UnsupportedEncodingException
49 {
50 if (_responseContent != null)
51 return _responseContent.toString(_encoding);
52 return null;
53 }
54
55 public byte[] getResponseContentBytes()
56 {
57 if (_responseContent != null)
58 return _responseContent.toByteArray();
59 return null;
60 }
61
62 @Override
63 protected void onResponseHeader(Buffer name, Buffer value) throws IOException
64 {
65 super.onResponseHeader(name, value);
66 int header = HttpHeaders.CACHE.getOrdinal(name);
67 switch (header)
68 {
69 case HttpHeaders.CONTENT_LENGTH_ORDINAL:
70 _contentLength = BufferUtil.toInt(value);
71 break;
72 case HttpHeaders.CONTENT_TYPE_ORDINAL:
73 String mime = StringUtil.asciiToLowerCase(value.toString());
74 int i = mime.indexOf("charset=");
75 if (i > 0)
76 _encoding = mime.substring(i + 8);
77 break;
78 }
79 }
80
81 @Override
82 protected void onResponseContent(Buffer content) throws IOException
83 {
84 super.onResponseContent(content);
85 if (_responseContent == null)
86 _responseContent = new ByteArrayOutputStream(_contentLength);
87 content.writeTo(_responseContent);
88 }
89
90 @Override
91 protected void onRetry() throws IOException
92 {
93 if (_fileForUpload != null)
94 {
95 setRequestContent(null);
96 setRequestContentSource(getInputStream());
97 }
98 else
99 {
100 InputStream requestContentStream = getRequestContentSource();
101 if (requestContentStream != null)
102 {
103 if (requestContentStream.markSupported())
104 {
105 setRequestContent(null);
106 requestContentStream.reset();
107 }
108 else
109 {
110 throw new IOException("Unsupported retry attempt");
111 }
112 }
113 }
114 super.onRetry();
115 }
116
117 private InputStream getInputStream() throws IOException
118 {
119 return new FileInputStream(_fileForUpload);
120 }
121
122 public File getFileForUpload()
123 {
124 return _fileForUpload;
125 }
126
127 public void setFileForUpload(File fileForUpload) throws IOException
128 {
129 this._fileForUpload = fileForUpload;
130 setRequestContentSource(getInputStream());
131 }
132 }