1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
|
//-----------------------------------------------------------------------
// <copyright file="CachedDirectWebResponse.cs" company="Outercurve Foundation">
// Copyright (c) Outercurve Foundation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Messaging {
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using System.Text;
/// <summary>
/// Cached details on the response from a direct web request to a remote party.
/// </summary>
[ContractVerification(true)]
[DebuggerDisplay("{Status} {ContentType.MediaType}, length: {ResponseStream.Length}")]
internal class CachedDirectWebResponse : IncomingWebResponse {
/// <summary>
/// A seekable, repeatable response stream.
/// </summary>
private MemoryStream responseStream;
/// <summary>
/// Initializes a new instance of the <see cref="CachedDirectWebResponse"/> class.
/// </summary>
internal CachedDirectWebResponse() {
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedDirectWebResponse"/> class.
/// </summary>
/// <param name="requestUri">The request URI.</param>
/// <param name="response">The response.</param>
/// <param name="maximumBytesToRead">The maximum bytes to read.</param>
internal CachedDirectWebResponse(Uri requestUri, HttpWebResponse response, int maximumBytesToRead)
: base(requestUri, response) {
Requires.NotNull(requestUri, "requestUri");
Requires.NotNull(response, "response");
this.responseStream = CacheNetworkStreamAndClose(response, maximumBytesToRead);
// BUGBUG: if the response was exactly maximumBytesToRead, we'll incorrectly believe it was truncated.
this.ResponseTruncated = this.responseStream.Length == maximumBytesToRead;
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedDirectWebResponse"/> class.
/// </summary>
/// <param name="requestUri">The request URI.</param>
/// <param name="responseUri">The final URI to respond to the request.</param>
/// <param name="headers">The headers.</param>
/// <param name="statusCode">The status code.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="contentEncoding">The content encoding.</param>
/// <param name="responseStream">The response stream.</param>
internal CachedDirectWebResponse(Uri requestUri, Uri responseUri, WebHeaderCollection headers, HttpStatusCode statusCode, string contentType, string contentEncoding, MemoryStream responseStream)
: base(requestUri, responseUri, headers, statusCode, contentType, contentEncoding) {
Requires.NotNull(requestUri, "requestUri");
Requires.NotNull(responseStream, "responseStream");
this.responseStream = responseStream;
}
/// <summary>
/// Gets a value indicating whether the cached response stream was
/// truncated to a maximum allowable length.
/// </summary>
public bool ResponseTruncated { get; private set; }
/// <summary>
/// Gets the body of the HTTP response.
/// </summary>
public override Stream ResponseStream {
get { return this.responseStream; }
}
/// <summary>
/// Gets or sets the cached response stream.
/// </summary>
internal MemoryStream CachedResponseStream {
get { return this.responseStream; }
set { this.responseStream = value; }
}
/// <summary>
/// Creates a text reader for the response stream.
/// </summary>
/// <returns>The text reader, initialized for the proper encoding.</returns>
public override StreamReader GetResponseReader() {
this.ResponseStream.Seek(0, SeekOrigin.Begin);
string contentEncoding = this.Headers[HttpResponseHeader.ContentEncoding];
Encoding encoding = null;
if (!string.IsNullOrEmpty(contentEncoding)) {
try {
encoding = Encoding.GetEncoding(contentEncoding);
} catch (ArgumentException ex) {
Logger.Messaging.ErrorFormat("Encoding.GetEncoding(\"{0}\") threw ArgumentException: {1}", contentEncoding, ex);
}
}
return encoding != null ? new StreamReader(this.ResponseStream, encoding) : new StreamReader(this.ResponseStream);
}
/// <summary>
/// Gets the body of the response as a string.
/// </summary>
/// <returns>The entire body of the response.</returns>
internal string GetResponseString() {
if (this.ResponseStream != null) {
string value = this.GetResponseReader().ReadToEnd();
this.ResponseStream.Seek(0, SeekOrigin.Begin);
return value;
} else {
return null;
}
}
/// <summary>
/// Gets an offline snapshot version of this instance.
/// </summary>
/// <param name="maximumBytesToCache">The maximum bytes from the response stream to cache.</param>
/// <returns>A snapshot version of this instance.</returns>
/// <remarks>
/// If this instance is a <see cref="NetworkDirectWebResponse"/> creating a snapshot
/// will automatically close and dispose of the underlying response stream.
/// If this instance is a <see cref="CachedDirectWebResponse"/>, the result will
/// be the self same instance.
/// </remarks>
internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) {
return this;
}
/// <summary>
/// Sets the response to some string, encoded as UTF-8.
/// </summary>
/// <param name="body">The string to set the response to.</param>
internal void SetResponse(string body) {
if (body == null) {
this.responseStream = null;
return;
}
Encoding encoding = Encoding.UTF8;
this.Headers[HttpResponseHeader.ContentEncoding] = encoding.HeaderName;
this.responseStream = new MemoryStream();
StreamWriter writer = new StreamWriter(this.ResponseStream, encoding);
writer.Write(body);
writer.Flush();
this.ResponseStream.Seek(0, SeekOrigin.Begin);
}
/// <summary>
/// Caches the network stream and closes it if it is open.
/// </summary>
/// <param name="response">The response whose stream is to be cloned.</param>
/// <param name="maximumBytesToRead">The maximum bytes to cache.</param>
/// <returns>The seekable Stream instance that contains a copy of what was returned in the HTTP response.</returns>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Assume(System.Boolean,System.String,System.String)", Justification = "No localization required.")]
private static MemoryStream CacheNetworkStreamAndClose(HttpWebResponse response, int maximumBytesToRead) {
Requires.NotNull(response, "response");
Contract.Ensures(Contract.Result<MemoryStream>() != null);
// Now read and cache the network stream
Stream networkStream = response.GetResponseStream();
MemoryStream cachedStream = new MemoryStream(response.ContentLength < 0 ? 4 * 1024 : Math.Min((int)response.ContentLength, maximumBytesToRead));
try {
Contract.Assume(networkStream.CanRead, "HttpWebResponse.GetResponseStream() always returns a readable stream."); // CC missing
Contract.Assume(cachedStream.CanWrite, "This is a MemoryStream -- it's always writable."); // CC missing
networkStream.CopyTo(cachedStream);
cachedStream.Seek(0, SeekOrigin.Begin);
networkStream.Dispose();
response.Close();
return cachedStream;
} catch {
cachedStream.Dispose();
throw;
}
}
}
}
|