File: DiscoveryClientProtocol.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (386 lines) | stat: -rw-r--r-- 10,798 bytes parent folder | download | duplicates (3)
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// 
// System.Web.Services.Protocols.DiscoveryClientProtocol.cs
//
// Author:
//   Dave Bettin (javabettin@yahoo.com)
//   Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Dave Bettin, 2002
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Collections;
using System.IO;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Net;
using System.Text.RegularExpressions;
#if !MOBILE
using System.Web.Services.Description;
#endif

namespace System.Web.Services.Discovery {
	public class DiscoveryClientProtocol : HttpWebClientProtocol {

		#region Fields

		private IList additionalInformation = new ArrayList ();
		private DiscoveryClientDocumentCollection documents = new DiscoveryClientDocumentCollection();
		private DiscoveryExceptionDictionary errors = new DiscoveryExceptionDictionary();
		private DiscoveryClientReferenceCollection references = new DiscoveryClientReferenceCollection();

		#endregion // Fields

		#region Constructors

		public DiscoveryClientProtocol () 
		{
		}
		
		#endregion // Constructors

		#region Properties

		public IList AdditionalInformation {
			get { return additionalInformation; }
		}
		
		public DiscoveryClientDocumentCollection Documents {
			get { return documents; }
		}
		
		public DiscoveryExceptionDictionary Errors {
			get { return errors; }
		}

		public DiscoveryClientReferenceCollection References {
			get { return references; }
		}		
		
		#endregion // Properties

		#region Methods

		public DiscoveryDocument Discover (string url)
		{
			Stream stream = Download (ref url);
			XmlTextReader reader = new XmlTextReader (url, stream);
			reader.XmlResolver = null;
			if (!DiscoveryDocument.CanRead (reader)) 
				throw new InvalidOperationException ("The url '" + url + "' does not point to a valid discovery document");
				
			DiscoveryDocument doc = DiscoveryDocument.Read (reader);
			reader.Close ();
			documents.Add (url, doc);
			AddDiscoReferences (doc);
			return doc;
		}

		public DiscoveryDocument DiscoverAny (string url)
		{
			try
			{
				string contentType = null;
				Stream stream = Download (ref url, ref contentType);
	
				if (contentType.IndexOf ("text/html") != -1)
				{
					// Look for an alternate url
					
					StreamReader sr = new StreamReader (stream);
					string str = sr.ReadToEnd ();
					
					string rex = "link\\s*rel\\s*=\\s*[\"']?alternate[\"']?\\s*";
					rex += "type\\s*=\\s*[\"']?text/xml[\"']?\\s*href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^']*)'|(?<1>\\S+))";
					Regex rob = new Regex (rex, RegexOptions.IgnoreCase);
					Match m = rob.Match (str);
					if (!m.Success) 
						throw new InvalidOperationException ("The HTML document does not contain Web service discovery information");
					
					if (url.StartsWith ("/"))
					{
						Uri uri = new Uri (url);
						url = uri.GetLeftPart (UriPartial.Authority) + m.Groups[1];
					}
					else
					{
						int i = url.LastIndexOf ('/');
						if (i == -1)
							throw new InvalidOperationException ("The HTML document does not contain Web service discovery information");

						Uri tmp = new Uri (url);
						tmp = new Uri (tmp, m.Groups [1].ToString ());
						url = tmp.ToString ();
					}
					stream = Download (ref url);
				}
				
				XmlTextReader reader = new XmlTextReader (url, stream);
				reader.XmlResolver = null;
				reader.MoveToContent ();
				DiscoveryDocument doc;
				DiscoveryReference refe = null;
				
				if (DiscoveryDocument.CanRead (reader))
				{
					doc = DiscoveryDocument.Read (reader);
					documents.Add (url, doc);
					refe = new DiscoveryDocumentReference ();
					AddDiscoReferences (doc);
				}
#if !MOBILE
				else if (ServiceDescription.CanRead (reader))
				{
					ServiceDescription wsdl = ServiceDescription.Read (reader);
					documents.Add (url, wsdl);
					doc = new DiscoveryDocument ();
					refe = new ContractReference ();
					doc.References.Add (refe);
					refe.Url = url;
					((ContractReference)refe).ResolveInternal (this, wsdl);
				}
#endif
				else
				{
					XmlSchema schema = XmlSchema.Read (reader, null);
					documents.Add (url, schema);
					doc = new DiscoveryDocument ();
					refe = new SchemaReference ();
					refe.Url = url;
					((SchemaReference)refe).ResolveInternal (this, schema);
					doc.References.Add (refe);
				}
				
				refe.ClientProtocol = this;
				refe.Url = url;
				references.Add (url, refe);
					
				reader.Close ();
				return doc;
			}
			catch (DiscoveryException ex) {
				throw ex.Exception;
			}
		}
		
		void AddDiscoReferences (DiscoveryDocument doc)
		{
			foreach (DiscoveryReference re in doc.References)
			{
				re.ClientProtocol = this;
				references.Add (re.Url, re);
			}
			
			if (doc.AdditionalInfo != null) {
				foreach (object info in doc.AdditionalInfo)
					additionalInformation.Add (info);
			}
		}
		
		public Stream Download (ref string url)
		{
			string contentType = null;
			return Download (ref url, ref contentType);
		}
		
		public Stream Download (ref string url, ref string contentType)
		{
			if (url.StartsWith ("http://") || url.StartsWith ("https://"))
			{
				WebRequest request = GetWebRequest (new Uri(url));
				WebResponse resp = request.GetResponse ();
				contentType = resp.ContentType;
				return resp.GetResponseStream ();
			}
			else if (url.StartsWith ("file://"))
			{
				WebRequest request = WebRequest.Create (new Uri (url));
				WebResponse resp = request.GetResponse ();
				contentType = resp.ContentType;
				return resp.GetResponseStream ();
			}
			else
			{
				string ext = Path.GetExtension (url).ToLower();
				if (ext == ".wsdl" || ext == ".xsd")
				{
					contentType = "text/xml";
					return new FileStream (url, FileMode.Open, FileAccess.Read);
				}
				else
					throw new InvalidOperationException ("Unrecognized file type '" + url + "'. Extension must be one of .wsdl or .xsd");
			}
		}

		[System.Runtime.InteropServices.ComVisible (false)]
		[Obsolete ("This method will be removed from a future version. The method call is no longer required for resource discovery", false)]
		public void LoadExternals ()
		{
		}

		public DiscoveryClientResultCollection ReadAll (string topLevelFilename)
		{
			StreamReader sr = new StreamReader (topLevelFilename);
			XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
			DiscoveryClientResultsFile resfile = (DiscoveryClientResultsFile) ser.Deserialize (sr);
			sr.Close ();
			
			string basePath = Path.GetDirectoryName (topLevelFilename);
			
			foreach (DiscoveryClientResult dcr in resfile.Results)
			{
				Type type = Type.GetType (dcr.ReferenceTypeName);
				DiscoveryReference dr = (DiscoveryReference) Activator.CreateInstance (type);
				dr.Url = dcr.Url;
				FileStream fs = new FileStream (Path.Combine (basePath, dcr.Filename), FileMode.Open, FileAccess.Read);
				Documents.Add (dr.Url, dr.ReadDocument (fs));
				fs.Close ();
				References.Add (dr.Url, dr);
			}
			return resfile.Results;
		}

		public void ResolveAll ()
		{
			ArrayList list = new ArrayList (References.Values);
			foreach (DiscoveryReference re in list)
			{
				try
				{
					if (re is DiscoveryDocumentReference)
						((DiscoveryDocumentReference)re).ResolveAll ();
					else
						re.Resolve ();
				}
				catch (DiscoveryException ex)
				{
					Errors [ex.Url] = ex.Exception;	
				}
				catch (Exception ex)
				{
					Errors [re.Url] = ex;	
				}
			}
		}
		
		public void ResolveOneLevel ()
		{
			ArrayList list = new ArrayList (References.Values);
			foreach (DiscoveryReference re in list)
				re.Resolve ();
		}
		
		public DiscoveryClientResultCollection WriteAll (string directory, string topLevelFilename)
		{
			DiscoveryClientResultsFile resfile = new DiscoveryClientResultsFile();
			
			foreach (DiscoveryReference re in References.Values)
			{
				object doc = Documents [re.Url];
				if (doc == null) continue;
				
				string fileName = FindValidName (resfile, re.DefaultFilename);
				resfile.Results.Add (new DiscoveryClientResult (re.GetType(), re.Url, fileName));
				
				string filepath = Path.Combine (directory, fileName);
				FileStream fs = new FileStream (filepath, FileMode.Create, FileAccess.Write);
				re.WriteDocument (doc, fs);
				fs.Close ();
			}
			
			StreamWriter sw = new StreamWriter (Path.Combine (directory, topLevelFilename));
			XmlSerializer ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
			ser.Serialize (sw, resfile);
			sw.Close ();
			return resfile.Results;
		}
		
		string FindValidName (DiscoveryClientResultsFile resfile, string baseName)
		{
			string name = baseName;
			int id = 0;
			bool found;
			do
			{
				found = false;
				foreach (DiscoveryClientResult res in resfile.Results)
				{
					if (name == res.Filename) {
						found = true; break;
					}
				}
				if (found)
					name = Path.GetFileNameWithoutExtension (baseName) + (++id) + Path.GetExtension (baseName);
			}
			while (found);
			
			return name;
		}
		
		#endregion // Methods
		
		#region Classes
		
		public sealed class DiscoveryClientResultsFile {
			
			#region Fields
			
			private DiscoveryClientResultCollection results;

			#endregion // Fields

			#region Contructors
			
			public DiscoveryClientResultsFile () 
			{
				results = new DiscoveryClientResultCollection ();
			}
		
			#endregion // Constructors
			
			#region Properties
		
			public DiscoveryClientResultCollection Results {				
				get { return results; }
			}
			
			#endregion // Properties
		}
		
		#endregion // Classes
	}
		
	internal class DiscoveryException : Exception
	{
		public string Url;
		public Exception Exception;
		
		public DiscoveryException (string url, Exception origin)
		{
			Url = url;
			Exception = origin;
		}
	}
}