blob: 0a10d796f8a109ffa5385d0a166da5586471d62e [file] [log] [blame]
Jake Farrell6f1e9922011-04-13 21:09:02 +00001//
2// THttpHandler.cs
3//
4// Authors:
5// Fredrik Hedberg <fhedberg@availo.com>
6//
7// Distributed under the Apache Public License
8//
9
10using System;
11using System.Web;
Roger Meier212022c2011-09-02 21:45:44 +000012using System.Net;
13using System.IO;
Jake Farrell6f1e9922011-04-13 21:09:02 +000014
15using Thrift.Protocol;
16
17namespace Thrift.Transport
18{
19 public class THttpHandler : IHttpHandler
20 {
21 protected TProcessor processor;
22
23 protected TProtocolFactory inputProtocolFactory;
24 protected TProtocolFactory outputProtocolFactory;
25
Roger Meier212022c2011-09-02 21:45:44 +000026 protected const string contentType = "application/x-thrift";
27 protected System.Text.Encoding encoding = System.Text.Encoding.UTF8;
28
Jake Farrell6f1e9922011-04-13 21:09:02 +000029 public THttpHandler(TProcessor processor)
30 : this(processor, new TBinaryProtocol.Factory())
31 {
32
33 }
34
35 public THttpHandler(TProcessor processor, TProtocolFactory protocolFactory)
36 : this(processor, protocolFactory, protocolFactory)
37 {
38
39 }
40
41 public THttpHandler(TProcessor processor, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory)
42 {
43 this.processor = processor;
44 this.inputProtocolFactory = inputProtocolFactory;
45 this.outputProtocolFactory = outputProtocolFactory;
46 }
47
Roger Meier212022c2011-09-02 21:45:44 +000048 public void ProcessRequest(HttpListenerContext context)
49 {
50 context.Response.ContentType = contentType;
51 context.Response.ContentEncoding = encoding;
52 ProcessRequest(context.Request.InputStream, context.Response.OutputStream);
53 }
54
Jake Farrell6f1e9922011-04-13 21:09:02 +000055 public void ProcessRequest(HttpContext context)
56 {
Roger Meier212022c2011-09-02 21:45:44 +000057 context.Response.ContentType = contentType;
58 context.Response.ContentEncoding = encoding;
59 ProcessRequest(context.Request.InputStream, context.Response.OutputStream);
60 }
Jake Farrell6f1e9922011-04-13 21:09:02 +000061
Roger Meier212022c2011-09-02 21:45:44 +000062 public void ProcessRequest(Stream input, Stream output)
63 {
64 TTransport transport = new TStreamTransport(input,output);
Jake Farrell6f1e9922011-04-13 21:09:02 +000065
66 TProtocol inputProtocol = null;
67 TProtocol outputProtocol = null;
68
69 try
70 {
71 inputProtocol = inputProtocolFactory.GetProtocol(transport);
72 outputProtocol = outputProtocolFactory.GetProtocol(transport);
73
74 while (processor.Process(inputProtocol, outputProtocol)) { }
75 }
76 catch (TTransportException)
77 {
78 // Client died, just move on
79 }
80 catch (TApplicationException tx)
81 {
82 Console.Error.Write(tx);
83 }
84 catch (Exception x)
85 {
86 Console.Error.Write(x);
87 }
88
89 transport.Close();
90 }
91
92 public bool IsReusable
93 {
94 get { return true; }
95 }
96 }
97}