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(name);
66 switch (header)
67 {
68 case HttpHeaders.CONTENT_LENGTH_ORDINAL:
69 _contentLength = BufferUtil.toInt(value);
70 break;
71 case HttpHeaders.CONTENT_TYPE_ORDINAL:
72 String mime = StringUtil.asciiToLowerCase(value.toString());
73 int i = mime.indexOf("charset=");
74 if (i > 0)
75 _encoding = mime.substring(i + 8);
76 break;
77 }
78 }
79
80 protected void onResponseContent(Buffer content) throws IOException
81 {
82 super.onResponseContent( content );
83 if (_responseContent == null)
84 _responseContent = new ByteArrayOutputStream(_contentLength);
85 content.writeTo(_responseContent);
86 }
87
88 protected void onRetry() throws IOException
89 {
90 if ( _fileForUpload != null )
91 {
92 _requestContent = null;
93 _requestContentSource = getInputStream();
94 }
95 else if ( _requestContentSource != null )
96 {
97 throw new IOException("Unsupported Retry attempt, no registered file for upload.");
98 }
99
100 super.onRetry();
101 }
102
103 private InputStream getInputStream() throws IOException
104 {
105 return new FileInputStream( _fileForUpload );
106 }
107
108 public File getFileForUpload()
109 {
110 return _fileForUpload;
111 }
112
113 public void setFileForUpload(File fileForUpload) throws IOException
114 {
115 this._fileForUpload = fileForUpload;
116 _requestContentSource = getInputStream();
117 }
118 }