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
32 public class ContentExchange extends CachedExchange
33 {
34 int _contentLength = 1024;
35 String _encoding = "utf-8";
36 ByteArrayOutputStream _responseContent;
37
38 File _fileForUpload;
39
40 public ContentExchange()
41 {
42 super(false);
43 }
44
45
46 public ContentExchange(boolean cacheFields)
47 {
48 super(cacheFields);
49 }
50
51
52 public String getResponseContent() throws UnsupportedEncodingException
53 {
54 if (_responseContent != null)
55 {
56 return _responseContent.toString(_encoding);
57 }
58 return null;
59 }
60
61
62 protected void onResponseHeader(Buffer name, Buffer value) throws IOException
63 {
64 super.onResponseHeader(name,value);
65 int header = HttpHeaders.CACHE.getOrdinal(value);
66 switch (header)
67 {
68 case HttpHeaders.CONTENT_LENGTH_ORDINAL:
69 _contentLength = BufferUtil.toInt(value);
70 break;
71 case HttpHeaders.CONTENT_TYPE_ORDINAL:
72
73 String mime = StringUtil.asciiToLowerCase(value.toString());
74 int i = mime.indexOf("charset=");
75 if (i > 0)
76 {
77 mime = mime.substring(i + 8);
78 i = mime.indexOf(';');
79 if (i > 0)
80 mime = mime.substring(0,i);
81 }
82 if (mime != null && mime.length() > 0)
83 _encoding = mime;
84 break;
85 }
86 }
87
88 protected void onResponseContent(Buffer content) throws IOException
89 {
90 super.onResponseContent( content );
91 if (_responseContent == null)
92 _responseContent = new ByteArrayOutputStream(_contentLength);
93 content.writeTo(_responseContent);
94 }
95
96 protected void onRetry() throws IOException
97 {
98 if ( _fileForUpload != null )
99 {
100 _requestContent = null;
101 _requestContentSource = getInputStream();
102 }
103 else if ( _requestContentSource != null )
104 {
105 throw new IOException("Unsupported Retry attempt, no registered file for upload.");
106 }
107
108 super.onRetry();
109 }
110
111 private InputStream getInputStream() throws IOException
112 {
113 return new FileInputStream( _fileForUpload );
114 }
115
116 public File getFileForUpload()
117 {
118 return _fileForUpload;
119 }
120
121 public void setFileForUpload(File fileForUpload) throws IOException
122 {
123 this._fileForUpload = fileForUpload;
124 _requestContentSource = getInputStream();
125 }
126 }