public void TestBypassRemoteError_no_response_stream()
        {
            using (HttpServer proxyServer = new HttpServer(80))
                using (HttpServer targetServer = new HttpServer(8080))
                {
                    proxyServer.AddHandler("/", new MyHandler("dummy"));             // dummy
                    BypassHttpHandler bypasser = new BypassHttpHandler("http://localhost:8080");
                    proxyServer.AddDefaultHandler(bypasser);
                    proxyServer.Start();

                    targetServer.AddHandler("/bypass/", new ErrorHttpHandler(502, null));
                    targetServer.Start();

                    WebClient agent = new WebClient();
                    try
                    {
                        agent.DownloadData("http://localhost:80/bypass/");
                    }
                    catch (WebException e)
                    {
                        Assert.AreEqual(HttpStatusCode.BadGateway,
                                        ((HttpWebResponse)e.Response).StatusCode);
                        using (StreamReader r = new StreamReader(e.Response.GetResponseStream()))
                        {
                            string json = r.ReadToEnd();
                            Assert.AreEqual("", json);
                        }
                        return;
                    }

                    Assert.Fail("Expected exception is not thrown");
                }
        }
        public void TestBypassException_pathWithQueryString()
        {
            using (HttpServer proxyServer = new HttpServer(80))
            {
                proxyServer.AddHandler("/", new MyHandler("dummy"));                 // dummy
                BypassHttpHandler bypasser = new BypassHttpHandler("http://localhost:8080");
                bypasser.AddExceptPrefix("/bypass/");
                proxyServer.AddDefaultHandler(bypasser);
                proxyServer.Start();

                WebClient agent = new WebClient();
                try
                {
                    agent.DownloadData("http://localhost:80/bypass?abc=123");
                }
                catch (WebException e)
                {
                    Assert.AreEqual(WebExceptionStatus.ProtocolError, e.Status);
                    using (StreamReader r = new StreamReader(e.Response.GetResponseStream()))
                    {
                        string        json = r.ReadToEnd();
                        CloudResponse resp = fastJSON.JSON.Instance.ToObject <CloudResponse>(json);
                        Assert.AreEqual(-1, resp.api_ret_code);
                        Assert.AreEqual(403, resp.status);
                        Assert.AreEqual("Station does not support this REST API; only Cloud does",
                                        resp.api_ret_message);
                    }
                    return;
                }

                Assert.Fail("Expected exception is not thrown");
            }
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                logger.Info("============== Starting Waveface Station =================");
                ConfigThreadPool();

                AppDomain.CurrentDomain.UnhandledException +=
                    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                Environment.CurrentDirectory = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location);

                logger.Debug("Initialize Waveface Service");
                InitStationId();
                InitResourceBasePath();

                fastJSON.JSON.Instance.UseUTCDateTime = true;

                functionServer = new HttpServer(9981);                 // TODO: remove hard code
                stationTimer   = new StationTimer(functionServer);

                logger.Debug("Add cloud forwarders to function server");
                BypassHttpHandler cloudForwarder = new BypassHttpHandler(CloudServer.BaseUrl);
                cloudForwarder.AddExceptPrefix("/" + CloudServer.DEF_BASE_PATH + "/auth/");
                cloudForwarder.AddExceptPrefix("/" + CloudServer.DEF_BASE_PATH + "/users/");
                cloudForwarder.AddExceptPrefix("/" + CloudServer.DEF_BASE_PATH + "/groups/");
                cloudForwarder.AddExceptPrefix("/" + CloudServer.DEF_BASE_PATH + "/stations/");
                functionServer.AddDefaultHandler(cloudForwarder);

                logger.Debug("Add handlers to function server");
                functionServer.AddHandler("/", new DummyHandler());
                functionServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/attachments/view/",
                                          new AttachmentViewHandler(stationId));

                AttachmentUploadHandler attachmentHandler = new AttachmentUploadHandler();
                AttachmentUploadMonitor attachmentMonitor = new AttachmentUploadMonitor();
                ImagePostProcessing     imgProc           = new ImagePostProcessing();
                imgProc.ThumbnailUpstreamed += attachmentMonitor.OnThumbnailUpstreamed;

                attachmentHandler.ImageAttachmentSaved     += imgProc.HandleImageAttachmentSaved;
                attachmentHandler.ImageAttachmentCompleted += imgProc.HandleImageAttachmentCompleted;
                attachmentHandler.ThumbnailUpstreamed      += attachmentMonitor.OnThumbnailUpstreamed;


                CloudStorageSync cloudSync = new CloudStorageSync();
                attachmentHandler.AttachmentSaved  += cloudSync.HandleAttachmentSaved;
                attachmentHandler.ProcessSucceeded += attachmentMonitor.OnProcessSucceeded;

                functionServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/attachments/upload/",
                                          attachmentHandler);

                functionServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/resourceDir/get/",
                                          new ResouceDirGetHandler(resourceBasePath));

                functionServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/resourceDir/set/",
                                          new ResouceDirSetHandler());

                functionServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/attachments/get/",
                                          new AttachmentGetHandler());



                functionServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/availability/ping/",
                                          new PingHandler());

                //if (Wammer.Utility.AutoRun.Exists("WavefaceStation"))
                //{
                logger.Debug("Start function server");
                functionServer.Start();
                stationTimer.Start();
                //}

                logger.Debug("Add handlers to management server");
                managementServer = new HttpServer(9989);
                AddDriverHandler addDriverHandler = new AddDriverHandler(stationId, resourceBasePath);
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/online/", new StationOnlineHandler(functionServer, stationTimer));
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/offline/", new StationOfflineHandler(functionServer, stationTimer));
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/drivers/add/", addDriverHandler);
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/drivers/list/", new ListDriverHandler());
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/drivers/remove/", new RemoveOwnerHandler(stationId));
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/station/status/get/", new StatusGetHandler());
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/cloudstorage/list", new ListCloudStorageHandler());
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/cloudstorage/dropbox/oauth/", new DropBoxOAuthHandler());
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/cloudstorage/dropbox/connect/", new DropBoxConnectHandler());
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/cloudstorage/dropbox/update/", new DropBoxUpdateHandler());
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/cloudstorage/dropbox/disconnect/", new DropboxDisconnectHandler());
                managementServer.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/availability/ping/", new PingHandler());

                addDriverHandler.DriverAdded += new EventHandler <DriverAddedEvtArgs>(addDriverHandler_DriverAdded);
                logger.Debug("Start management server");
                managementServer.Start();

                logger.Info("Waveface station is started");
            }
            catch (Exception ex)
            {
                logger.Error("Unknown exception", ex);
                throw;
            }
        }