public bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url);
            if (request.Url.StartsWith (SERVICE_URI)) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Service protocol.");
                try {
                    string commandParams = request.Url.Substring (SERVICE_URI.Length);
                    string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                    string serviceName = commandParamsArray [0];

                    Object service = serviceLocator.GetService (serviceName);
                    byte[] result = null;
                    string methodName = commandParamsArray [1];

                    if (request.Method == "GET") {
                        string[] methodParams = null;
                        if (commandParamsArray.Length > 2) {
                            methodParams = new string[commandParamsArray.Length - 2];
                            for (int i = 2; i < commandParamsArray.Length; i++) {
                                methodParams [i - 2] = commandParamsArray [i];
                            }
                        }
                        result = getInvocationManager (request.Method).InvokeService (service, methodName, methodParams);
                    } else if (request.Method == "POST") {
                        string queryString = null;
                        if (request.QueryString != null && request.QueryString.Length > "json=".Length) {
                            //queryString = ServiceURIHandler.UrlDecode(request.QueryString.Substring("json=".Length));
                            queryString = request.QueryString.Substring ("json=".Length);
                        }
                        result = getInvocationManager (request.Method).InvokeService (service, methodName, queryString);
                    }

                    response.RawContent = result;
                    if (response.RawContent == null) {
                        response.Content = "null";
                        /* SERVICES COULD SEND NULL OBJETS.
                        SystemLogger.Log(SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler...");
                        return false;
                        */
                    }
                    response.ContentType = "application/json";
                    return true;
                } catch (Exception e) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e);
                    response.Content = "Malformed request.";
                    return false;
                }
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Non service protocol. Continue to next handler...");
                return false;
            }
        }
        public bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url);
            if (request.Url.StartsWith (REMOTE_RESOURCE_URI)) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Remote resource protocol.");
                try {
                    string commandParams = request.Url.Substring (REMOTE_RESOURCE_URI.Length);
                    string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                    if (commandParamsArray.Length > 0) {
                        string ioServiceName = commandParamsArray [0];

                        Object unityIOService = serviceLocator.GetService (UNITY_IO_SERVICE_NAME);
                        if (unityIOService != null && ioServiceName != null) {
                            IIo io = (IIo)unityIOService;
                            string parameters = commandParams.Substring (ioServiceName.Length + 1);

                            IORequest ioRequest = new IORequest ();
                            ioRequest.Content = parameters;
                            IOResponse ioResponse = io.InvokeService (ioRequest, ioServiceName);
                            if (ioResponse != null) {
                                response.ContentType = ioResponse.ContentType;
                                response.RawContent = ioResponse.ContentBinary;
                            }
                        }
                    }

                    if (response.RawContent == null) {
                        response.Content = "No content available.";
                        SystemLogger.Log (SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler...");
                        return false;
                    }

                    return true;
                } catch (Exception e) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e);
                    response.Content = "Malformed request.";
                    return false;
                }
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Non remote resource protocol. Continue to next handler...");
                return false;
            }
        }
 public bool Process(HttpServer server, HttpRequest req, HttpResponse resp)
 {
     //server.RequestSession(req);
     StringBuilder sb = new StringBuilder ();
     sb.Append ("<h3>Session</h3>");
     sb.Append ("<p>ID: " + req.Session.ID + "<br>User: "******"<h3>Header</h3>");
     sb.Append ("Method: " + req.Method + "; URL: '" + req.Url + "'; HTTP version " + req.HttpVersion + "<p>");
     foreach (DictionaryEntry ide in req.Header)
         sb.Append (" " + ide.Key + ": " + ide.Value + "<br>");
     sb.Append ("<h3>Cookies</h3>");
     foreach (DictionaryEntry ide in req.Cookies)
         sb.Append (" " + ide.Key + ": " + ide.Value + "<br>");
     sb.Append ("<h3>Query</h3>");
     foreach (DictionaryEntry ide in req.Query)
         sb.Append (" " + ide.Key + ": " + ide.Value + "<br>");
     sb.Append ("<h3>Content</h3>");
     sb.Append (req.Content);
     resp.Content = sb.ToString ();
     return true;
 }
        public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            if (request.Url.StartsWith (DOCUMENTS_URI)) {
                SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## " + this.GetType () + " -> " + request.Url);

                string requestUrl = request.Url;
                if(request.QueryString!=null && request.QueryString.Length>0) {
                    requestUrl = request.Page;
                    SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## " + this.GetType () + " -> removing req params -> " + requestUrl);
                }

                string escapedUrl = Uri.UnescapeDataString(requestUrl);
                // url should be escaped to reach the real filesystem path for the requested file.
                string resourcePath = escapedUrl.Substring (DOCUMENTS_URI.Length);

                // Getting mime type
                string ext = Path.GetExtension (resourcePath.ToLower());
                string mime = (string)MimeTypes [ext];
                if (mime == null)
                    mime = "application/octet-stream";
                response.ContentType = mime;

                // Getting Root Directory for Files in this platform.
                IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance ().GetService ("file");
                DirectoryData rootDir = fileSystemService.GetDirectoryRoot ();
                resourcePath = Path.Combine (rootDir.FullName, resourcePath);

                // Get Resources as Binary Data and Write them to the server response
                response.RawContent = IPhoneUtils.GetInstance ().GetResourceAsBinary (resourcePath, false);
                SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## " + this.GetType () + " -> file extension: " + ext + ", mimetype: " + mime + ", binary data length: " + response.RawContent.Length);

                return true;

            } else {
                return base.Process (server, request, response);
            }
        }
        /// <summary>
        /// Process the specified server, request and response. Overrides CORE ServiceURIHandler superclass
        /// </summary>
        /// <param name="server">Server.</param>
        /// <param name="request">Request.</param>
        /// <param name="response">Response.</param>
        public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            bool isServiceProtocol = request.Url.StartsWith (ServiceURIHandler.SERVICE_URI);

            /* TO BE REMOVED - 5.0.6 [AMOB-30]
            bool isManagedService = IPhoneServiceLocator.consumeManagedService (request.Url);
            SystemLogger.Log (SystemLogger.Module.PLATFORM, " ############## Managed Service? " + isManagedService);
            */

            if (isServiceProtocol) {

                /* TO BE REMOVED - 5.0.6 [AMOB-30]
                if(isManagedService) return base.Process (server, request, response);

                SystemLogger.Log (SystemLogger.Module .PLATFORM, "**** WARNING: Anonymous service call, not managed by Appverse !!!");
                return false;
                */

                return base.Process (server, request, response);
            }

            SystemLogger.Log (SystemLogger.Module .PLATFORM, "Non service protocol. Continue to next handler...");
            return false;
        }
        void SendResponse(ClientInfo ci, HttpRequest req, HttpResponse resp, bool close)
        {
            StringBuilder builder = new StringBuilder ();
            // Create Headers
            builder.Append ("HTTP/1.0 ");
            builder.Append (resp.ReturnCode);
            builder.Append (Responses [resp.ReturnCode]);
            builder.Append ("\r\nDate: ");
            builder.Append (DateTime.Now.ToString ("R"));
            builder.Append ("\r\nServer: UnityEmbedded/1.0 (iOS)");
            //builder.Append ("\r\nConnection: ");
            //builder.Append ((close ? "close" : "Keep-Alive"));

            if (resp.RawContent == null) {
                builder.Append ("\r\nContent-Length: ");
                builder.Append (resp.Content.Length);
            } else {
                builder.Append ("\r\nContent-Length: ");
                builder.Append (resp.RawContent.Length);
            }

            builder.Append ("\r\nContent-Encoding: utf-8");
            builder.Append ("\r\nContent-Type: ");

            builder.Append (resp.ContentType);

            // ADDING CUSTOM HEADERS(new feature)
            if (!CUSTOM_RESPONSE_HEADERS.StartsWith ("$"))
                builder.Append (CUSTOM_RESPONSE_HEADERS);

            if (req.Session != null) {
                builder.Append ("\r\nSet-Cookie: _sessid=");
                builder.Append (req.Session.ID);
                builder.Append ("; path=/");
            }

            foreach (DictionaryEntry de in resp.Header) {
                builder.Append ("\r\n");
                builder.Append (de.Key);
                builder.Append (": ");
                builder.Append (de.Value);
            }
            builder.Append ("\r\n\r\n");

            // Send Header
            ci.Send (builder.ToString ());

            // Send Body
            if (resp.RawContent != null) {
                ci.Send (resp.RawContent);
            } else {
                ci.Send (resp.Content);
            }

            // Close if not persistent connection
            if (close) {
                ci.Close ();
            }
        }
 //static long tTotal;
 protected virtual bool Process(ClientInfo ci, HttpRequest req)
 {
     //long tIn = DateTime.Now.Ticks;
     HttpResponse resp = new HttpResponse ();
     resp.Url = req.Url;
     for (int i = handlers.Count - 1; i >= 0; i--) {
         IHttpHandler handler = (IHttpHandler)handlers [i];
         if (handler.Process (this, req, resp)) {
             SendResponse (ci, req, resp, resp.ReturnCode != 200);
             //tTotal += DateTime.Now.Ticks - tIn;
             //Console.WriteLine ("Total: " + tTotal + " ticks");
             return resp.ReturnCode != 200;
         }
     }
     return true;
 }
        public virtual bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            if (this.appSource == ApplicationSource.FILE) {   // RESOURCES ARE SERVED FROM FILESYSTEM.

                string fn = server.GetFilename (request);
                if (!File.Exists (fn)) {
                    response.ReturnCode = 404;
                    response.Content = "File not found.";
                    SystemLogger.Log (SystemLogger.Module .CORE, "# ResourceHandler. Error getting response content for [" + fn + "]: File Not Found");
                    return true;
                }

                string ext = Path.GetExtension (fn);
                string mime = (string)MimeTypes [ext];
                if (mime == null)
                    mime = "application/octet-stream";
                response.ContentType = mime;

                try {   // Only perform substitutions on HTML files

                    //if (substitute && (mime.StartsWith("text/html"))) //(mime.Substring(0, 5) == "text/")
                    if (mime.StartsWith ("text/html")) { //(mime.Substring(0, 5) == "text/")
                        // Mime type 'text' is substituted
                        response.Content = GetContentFromStreamReader (fn);
                        /*
                        // Do substitutions
                        Regex regex = new Regex(@"\<\%(?<tag>[^>]+)\>");
                        lock (this)
                        {
                            req = request;
                            response.Content = regex.Replace(response.Content, new MatchEvaluator(RegexMatch));
                        }
                        */
                    } else {
                        response.RawContent = GetRawContentFromFileStream (fn);
                    }
                } catch (Exception e) {
                    response.ReturnCode = 500;
                    response.Content = "Error reading file: " + e;
                    SystemLogger.Log (SystemLogger.Module .CORE, "# ResourceHandler. Error getting response content for [" + fn + "]", e);
                    return true;
                }

            } else if (this.appSource == ApplicationSource.DB_FILE) {   // RESOURCES ARE SERVED FROM A PRE_BUILD "DB" FILE.
                // TODO get resources from DB file.

            } else if (this.appSource == ApplicationSource.DB_EMBEDDED) {   // RESOURCES ARE SERVED FROM A PRE_BUILD "DB" FILE.
                // TODO get resources from embedded DB file.

            }

            return true;
        }
        public virtual bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url);
            if (request.Url.StartsWith (SERVICE_URI)) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Service protocol.");

                bool asyncmode = true;  // PLATFORM won't have anymore the sync mode for services.
                int serviceUriLength = SERVICE_URI.Length;

                if(response.Header == null) {
                    response.Header = new Hashtable();
                }

                // Adding Header Cache-Control to "no-cache" to force no caching service requests
                string cacheControlHeader = DEFAULT_CACHE_CONTROL;

                response.ContentType = "application/json";
                IInvocationManager invocationManager = getInvocationManager (request.Method);

                try {
                    string commandParams = request.Url.Substring (serviceUriLength);
                    string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                    string serviceName = commandParamsArray [0];

                    Object service = serviceLocator.GetService (serviceName);
                    byte[] result = null;
                    string methodName = commandParamsArray [1];

                    if (request.Method == "GET" && !asyncmode) {
                        string[] methodParams = null;
                        if (commandParamsArray.Length > 2) {
                            methodParams = new string[commandParamsArray.Length - 2];
                            for (int i = 2; i < commandParamsArray.Length; i++) {
                                methodParams [i - 2] = commandParamsArray [i];
                            }
                        }

                        // Process result synchronously
                        result = this.ProcessGETResult(invocationManager, service, methodName, methodParams);
                    } else if (request.Method == "POST") {
                        if (asyncmode){
                            // Process result asynchronously
                            this.ProcessAsyncPOSTResult(invocationManager, service, methodName, request.QueryString);
                        } else {
                            // Process result synchronously
                            result = this.ProcessPOSTResult(invocationManager, service, methodName, request.QueryString);
                        }
                    }

                    if(asyncmode) {
                        // Return acknowledge
                        response.Content = "{\"result\":\"Processed\"}";
                    } else {
                        response.RawContent = result;
                        if (response.RawContent == null) {
                            response.Content = "null";
                            /* SERVICES COULD SEND NULL OBJETS.
                                SystemLogger.Log(SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler...");
                                return false;
                                */
                        }
                    }

                } catch (Exception e) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e);
                    response.Content = "{\"result\":\"Malformed request\"}";
                }

                if(invocationManager.CacheControlHeader()!=null) {
                    cacheControlHeader = invocationManager.CacheControlHeader();
                }

                if(response.Header.ContainsKey(CACHE_CONTROL_HEADER)) {
                    response.Header[CACHE_CONTROL_HEADER] = cacheControlHeader;
                    SystemLogger.Log (SystemLogger.Module .CORE, "Updated Caching-Control header on response: " + cacheControlHeader);
                } else {
                    response.Header.Add(CACHE_CONTROL_HEADER, cacheControlHeader);
                    SystemLogger.Log (SystemLogger.Module .CORE, "Added Caching-Control header to response: " + cacheControlHeader);
                }

                return true;
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Non service protocol. Continue to next handler...");
                return false;
            }
        }