move to from olive to mcs
[mono.git] / mcs / class / System.ServiceModel.Web / System.ServiceModel.Dispatcher / WebMessageFormatter.cs
1 //
2 // WebMessageFormatter.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Specialized;
30 using System.Reflection;
31 using System.Runtime.Serialization;
32 using System.Runtime.Serialization.Json;
33 using System.ServiceModel;
34 using System.ServiceModel.Channels;
35 using System.ServiceModel.Dispatcher;
36 using System.ServiceModel.Web;
37 using System.Text;
38
39 namespace System.ServiceModel.Description
40 {
41         internal abstract class WebMessageFormatter
42         {
43                 OperationDescription operation;
44                 ServiceEndpoint endpoint;
45                 QueryStringConverter converter;
46                 WebHttpBehavior behavior;
47                 UriTemplate template;
48                 WebAttributeInfo info = null;
49
50                 public WebMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
51                 {
52                         this.operation = operation;
53                         this.endpoint = endpoint;
54                         this.converter = converter;
55                         this.behavior = behavior;
56                         ApplyWebAttribute ();
57                 }
58
59                 void ApplyWebAttribute ()
60                 {
61                         MethodInfo mi = operation.SyncMethod ?? operation.BeginMethod;
62
63                         object [] atts = mi.GetCustomAttributes (typeof (WebGetAttribute), false);
64                         if (atts.Length > 0)
65                                 info = ((WebGetAttribute) atts [0]).Info;
66                         atts = mi.GetCustomAttributes (typeof (WebInvokeAttribute), false);
67                         if (atts.Length > 0)
68                                 info = ((WebInvokeAttribute) atts [0]).Info;
69                         if (info == null)
70                                 info = new WebAttributeInfo ();
71
72                         template = info.BuildUriTemplate (Operation, GetMessageDescription (MessageDirection.Input));
73                 }
74
75                 public WebHttpBehavior Behavior {
76                         get { return behavior; }
77                 }
78
79                 public WebAttributeInfo Info {
80                         get { return info; }
81                 }
82
83                 public OperationDescription Operation {
84                         get { return operation; }
85                 }
86
87                 public QueryStringConverter Converter {
88                         get { return converter; }
89                 }
90
91                 public ServiceEndpoint Endpoint {
92                         get { return endpoint; }
93                 }
94
95                 public UriTemplate UriTemplate {
96                         get { return template; }
97                 }
98
99                 protected WebContentFormat ToContentFormat (WebMessageFormat src)
100                 {
101                         switch (src) {
102                         case WebMessageFormat.Xml:
103                                 return WebContentFormat.Xml;
104                         case WebMessageFormat.Json:
105                                 return WebContentFormat.Json;
106                         }
107                         throw new SystemException ("INTERNAL ERROR: should not happen");
108                 }
109
110                 protected void CheckMessageVersion (MessageVersion messageVersion)
111                 {
112                         if (messageVersion == null)
113                                 throw new ArgumentNullException ("messageVersion");
114
115                         if (!MessageVersion.None.Equals (messageVersion))
116                                 throw new ArgumentException ("Only MessageVersion.None is supported");
117                 }
118
119                 protected MessageDescription GetMessageDescription (MessageDirection dir)
120                 {
121                         foreach (MessageDescription md in operation.Messages)
122                                 if (md.Direction == dir)
123                                         return md;
124                         throw new SystemException ("INTERNAL ERROR: no corresponding message description for the specified direction: " + dir);
125                 }
126
127                 internal class RequestClientFormatter : WebClientMessageFormatter
128                 {
129                         public RequestClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
130                                 : base (operation, endpoint, converter, behavior)
131                         {
132                         }
133                 }
134
135                 internal class ReplyClientFormatter : WebClientMessageFormatter
136                 {
137                         public ReplyClientFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
138                                 : base (operation, endpoint, converter, behavior)
139                         {
140                         }
141                 }
142
143                 internal class RequestDispatchFormatter : WebDispatchMessageFormatter
144                 {
145                         public RequestDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
146                                 : base (operation, endpoint, converter, behavior)
147                         {
148                         }
149                 }
150
151                 internal class ReplyDispatchFormatter : WebDispatchMessageFormatter
152                 {
153                         public ReplyDispatchFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
154                                 : base (operation, endpoint, converter, behavior)
155                         {
156                         }
157                 }
158
159                 internal abstract class WebClientMessageFormatter : WebMessageFormatter, IClientMessageFormatter
160                 {
161                         protected WebClientMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
162                                 : base (operation, endpoint, converter, behavior)
163                         {
164                         }
165
166                         public Message SerializeRequest (MessageVersion messageVersion, object [] parameters)
167                         {
168                                 if (parameters == null)
169                                         throw new ArgumentNullException ("parameters");
170                                 CheckMessageVersion (messageVersion);
171
172                                 var c = new NameValueCollection ();
173
174                                 MessageDescription md = GetMessageDescription (MessageDirection.Input);
175
176                                 if (parameters.Length != md.Body.Parts.Count)
177                                         throw new ArgumentException ("Parameter array length does not match the number of message body parts");
178
179                                 for (int i = 0; i < parameters.Length; i++) {
180                                         var p = md.Body.Parts [i];
181                                         string name = p.Name.ToUpperInvariant ();
182                                         if (UriTemplate.PathSegmentVariableNames.Contains (name) ||
183                                             UriTemplate.QueryValueVariableNames.Contains (name))
184                                                 c.Add (name, parameters [i] != null ? Converter.ConvertValueToString (parameters [i], parameters [i].GetType ()) : null);
185                                         else
186                                                 // FIXME: bind as a message part
187                                                 throw new NotImplementedException (String.Format ("parameter {0} is not contained in the URI template {1} {2} {3}", p.Name, UriTemplate, UriTemplate.PathSegmentVariableNames.Count, UriTemplate.QueryValueVariableNames.Count));
188                                 }
189
190                                 Uri to = UriTemplate.BindByName (Endpoint.Address.Uri, c);
191
192                                 Message ret = Message.CreateMessage (messageVersion, (string) null);
193                                 ret.Headers.To = to;
194
195                                 var hp = new HttpRequestMessageProperty ();
196                                 hp.Method = Info.Method;
197                                 // FIXME: set hp.SuppressEntityBody for some cases.
198                                 ret.Properties.Add (HttpRequestMessageProperty.Name, hp);
199
200                                 var wp = new WebBodyFormatMessageProperty (ToContentFormat (Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat));
201                                 ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
202
203                                 return ret;
204                         }
205
206                         public object DeserializeReply (Message message, object [] parameters)
207                         {
208                                 if (parameters == null)
209                                         throw new ArgumentNullException ("parameters");
210                                 CheckMessageVersion (message.Version);
211
212                                 string pname = WebBodyFormatMessageProperty.Name;
213                                 if (!message.Properties.ContainsKey (pname))
214                                         throw new SystemException ("INTERNAL ERROR: it expects WebBodyFormatMessageProperty existence");
215                                 var wp = (WebBodyFormatMessageProperty) message.Properties [pname];
216                                 MessageDescription md = GetMessageDescription (MessageDirection.Output);
217
218                                 XmlObjectSerializer serializer = null;
219                                 switch (wp.Format) {
220                                 case WebContentFormat.Xml:
221                                         serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
222                                         break;
223                                 case WebContentFormat.Json:
224                                         serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
225                                         break;
226                                 case WebContentFormat.Raw:
227                                 default:
228                                         throw new NotImplementedException ();
229                                 }
230
231                                 // FIXME: handle ref/out parameters
232
233                                 return serializer.ReadObject (message.GetReaderAtBodyContents (), false);
234                         }
235                 }
236
237                 internal abstract class WebDispatchMessageFormatter : WebMessageFormatter, IDispatchMessageFormatter
238                 {
239                         protected WebDispatchMessageFormatter (OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
240                                 : base (operation, endpoint, converter, behavior)
241                         {
242                         }
243
244                         public Message SerializeReply (MessageVersion messageVersion, object [] parameters, object result)
245                         {
246                                 try {
247                                         return SerializeReplyCore (messageVersion, parameters, result);
248                                 } finally {
249                                         if (WebOperationContext.Current != null)
250                                                 OperationContext.Current.Extensions.Remove (WebOperationContext.Current);
251                                 }
252                         }
253
254                         Message SerializeReplyCore (MessageVersion messageVersion, object [] parameters, object result)
255                         {
256                                 if (parameters == null)
257                                         throw new ArgumentNullException ("parameters");
258                                 CheckMessageVersion (messageVersion);
259
260                                 MessageDescription md = GetMessageDescription (MessageDirection.Output);
261
262                                 // FIXME: use them.
263                                 // var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> ();
264                                 // XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null);
265                                 // var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> ();
266                                 // XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ());
267
268                                 WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat;
269
270                                 string mediaType = null;
271                                 XmlObjectSerializer serializer = null;
272                                 switch (msgfmt) {
273                                 case WebMessageFormat.Xml:
274                                         serializer = new DataContractSerializer (md.Body.ReturnValue.Type);
275                                         mediaType = "application/xml";
276                                         break;
277                                 case WebMessageFormat.Json:
278                                         serializer = new DataContractJsonSerializer (md.Body.ReturnValue.Type);
279                                         mediaType = "application/json";
280                                         break;
281                                 }
282
283                                 // FIXME: serialize ref/out parameters as well.
284
285                                 Message ret = Message.CreateMessage (MessageVersion.None, null, result, serializer);
286
287                                 // Message properties
288
289                                 var hp = new HttpResponseMessageProperty ();
290                                 // FIXME: get encoding from somewhere
291                                 hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8";
292
293                                 // apply user-customized HTTP results via WebOperationContext.
294                                 WebOperationContext.Current.OutgoingResponse.Apply (hp);
295
296                                 // FIXME: fill some properties if required.
297                                 ret.Properties.Add (HttpResponseMessageProperty.Name, hp);
298
299                                 var wp = new WebBodyFormatMessageProperty (ToContentFormat (msgfmt));
300                                 ret.Properties.Add (WebBodyFormatMessageProperty.Name, wp);
301
302                                 return ret;
303                         }
304
305                         public void DeserializeRequest (Message message, object [] parameters)
306                         {
307                                 if (parameters == null)
308                                         throw new ArgumentNullException ("parameters");
309                                 CheckMessageVersion (message.Version);
310
311                                 OperationContext.Current.Extensions.Add (new WebOperationContext (OperationContext.Current));
312
313                                 IncomingWebRequestContext iwc = WebOperationContext.Current.IncomingRequest;
314
315                                 Uri to = message.Headers.To;
316                                 UriTemplateMatch match = UriTemplate.Match (Endpoint.Address.Uri, to);
317                                 if (match == null)
318                                         // not sure if it could happen
319                                         throw new SystemException (String.Format ("INTERNAL ERROR: UriTemplate does not match with the request: {0} / {1}", UriTemplate, to));
320                                 iwc.UriTemplateMatch = match;
321
322                                 MessageDescription md = GetMessageDescription (MessageDirection.Input);
323
324                                 for (int i = 0; i < parameters.Length; i++) {
325                                         var p = md.Body.Parts [i];
326                                         string name = p.Name.ToUpperInvariant ();
327                                         parameters [i] = match.BoundVariables [name];
328                                 }
329                         }
330                 }
331         }
332 }