/// <summary>
        /// Processes Update requests
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public void ProcessUpdateRequest(HttpServerContext context)
        {
            if (this._config.UpdateProcessor == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                return;
            }

            //Try and parse the Form Variables
            FormVariables form = new FormVariables(context);

            if (!form.IsValid)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            if (context.Request.HttpMethod.Equals("OPTIONS"))
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                return;
                //TODO: Support Service Description?
                ////OPTIONS requests always result in the Service Description document
                //IGraph svcDescrip = SparqlServiceDescriber.GetServiceDescription(context, this._config, UriFactory.Create(context.Request.Url.AbsoluteUri), ServiceDescriptionType.Update);
                //HandlerHelper.SendToClient(context, svcDescrip, this._config);
                //return;
            }

            //See if there has been an update submitted
            String updateText = null;

            if (context.Request.ContentType != null)
            {
                if (context.Request.ContentType.Equals(MimeTypesHelper.WWWFormURLEncoded))
                {
                    updateText = form["update"];
                }
                else if (context.Request.ContentType.Equals(MimeTypesHelper.SparqlUpdate))
                {
                    updateText = new StreamReader(context.Request.InputStream).ReadToEnd();
                }
            }
            else
            {
                updateText = form["update"];
            }

            //If no Update sent either show Update Form or give a HTTP 400 response
            if (updateText == null || updateText.Equals(String.Empty))
            {
                if (this._config.ShowUpdateForm)
                {
                    this.ShowUpdateForm(context);
                    return;
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return;
                }
            }

            //Get Other options associated with this update
            List <String> userDefaultGraphs = new List <String>();
            List <String> userNamedGraphs   = new List <String>();

            //Get the USING URIs (if any)
            if (context.Request.QueryString["using-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(context.Request.QueryString.GetValues("using-graph-uri"));
            }
            else if (form["using-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(form.GetValues("using-graph-uri"));
            }
            //Get the USING NAMED URIs (if any)
            if (context.Request.QueryString["using-named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(context.Request.QueryString.GetValues("using-named-graph-uri"));
            }
            else if (form["using-named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(form.GetValues("using-named-graph-uri"));
            }

            try
            {
                //Now we're going to parse the Updates
                SparqlUpdateParser parser = new SparqlUpdateParser();
                parser.ExpressionFactories = this._config.ExpressionFactories;
                SparqlUpdateCommandSet commands = parser.ParseFromString(updateText);

                //TODO: Support Authentication?
                ////Check whether we need to use authentication
                ////If there are no user groups then no authentication is in use so we default to authenticated with no per-action authentication needed
                //bool isAuth = true, requireActionAuth = false;
                //if (this._config.UserGroups.Any())
                //{
                //    //If we have user
                //    isAuth = HandlerHelper.IsAuthenticated(context, this._config.UserGroups);
                //    requireActionAuth = true;
                //}
                //if (!isAuth) return;

                //First check actions to see whether they are all permissible and apply USING/USING NAMED paramaters
                foreach (SparqlUpdateCommand cmd in commands.Commands)
                {
                    //TODO: Support Authentication?
                    ////Authenticate each action
                    //bool actionAuth = true;
                    //if (requireActionAuth) actionAuth = HandlerHelper.IsAuthenticated(context, this._config.UserGroups, this.GetUpdatePermissionAction(cmd));
                    //if (!actionAuth)
                    //{
                    //    throw new SparqlUpdatePermissionException("You are not authorised to perform the " + this.GetUpdatePermissionAction(cmd) + " action");
                    //}

                    //Check whether we need to (and are permitted to) apply USING/USING NAMED parameters
                    if (userDefaultGraphs.Count > 0 || userNamedGraphs.Count > 0)
                    {
                        BaseModificationCommand modify = cmd as BaseModificationCommand;
                        if (modify != null)
                        {
                            if (modify.GraphUri != null || modify.UsingUris.Any() || modify.UsingNamedUris.Any())
                            {
                                //Invalid if a command already has a WITH/USING/USING NAMED
                                throw new SparqlUpdateMalformedException("A command in your update request contains a WITH/USING/USING NAMED clause but you have also specified one/both of the using-graph-uri or using-named-graph-uri parameters which is not permitted by the SPARQL Protocol");
                            }
                            else
                            {
                                //Otherwise go ahead and apply
                                userDefaultGraphs.ForEach(u => modify.AddUsingUri(UriFactory.Create(u)));
                                userNamedGraphs.ForEach(u => modify.AddUsingNamedUri(UriFactory.Create(u)));
                            }
                        }
                    }
                }

                //Then assuming we got here this means all our actions are permitted so now we can process the updates
                this._config.UpdateProcessor.ProcessCommandSet(commands);

                //Flush outstanding changes
                this._config.UpdateProcessor.Flush();
            }
            catch (RdfParseException parseEx)
            {
                HandleUpdateErrors(context, "Parsing Error", updateText, parseEx, (int)HttpStatusCode.BadRequest);
            }
            catch (SparqlUpdatePermissionException permEx)
            {
                HandleUpdateErrors(context, "Permissions Error", updateText, permEx, (int)HttpStatusCode.Forbidden);
            }
            catch (SparqlUpdateMalformedException malEx)
            {
                HandleUpdateErrors(context, "Malformed Update Error", updateText, malEx, (int)HttpStatusCode.BadRequest);
            }
            catch (SparqlUpdateException updateEx)
            {
                HandleUpdateErrors(context, "Update Error", updateText, updateEx);
            }
            catch (RdfException rdfEx)
            {
                HandleUpdateErrors(context, "RDF Error", updateText, rdfEx);
            }
            catch (Exception ex)
            {
                HandleUpdateErrors(context, "Error", updateText, ex);
            }
        }
        //TODO: Support Protocol Requests?
        ///// <summary>
        ///// Processes Protocol requests
        ///// </summary>
        ///// <param name="context">HTTP Context</param>
        //public void ProcessProtocolRequest(HttpListenerContext context)
        //{
        //    if (this._config.ProtocolProcessor == null)
        //    {
        //        context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
        //        return;
        //    }

        //    //Q: Support authentication?
        //    ////Check whether we need to use authentication
        //    //if (!HandlerHelper.IsAuthenticated(context, this._config.UserGroups, context.Request.HttpMethod)) return;

        //    try
        //    {
        //        //Invoke the appropriate method on our protocol processor
        //        switch (context.Request.HttpMethod)
        //        {
        //            case "GET":
        //                this._config.ProtocolProcessor.ProcessGet(context);
        //                break;
        //            case "PUT":
        //                this._config.ProtocolProcessor.ProcessPut(context);
        //                break;
        //            case "POST":
        //                this._config.ProtocolProcessor.ProcessPost(context);
        //                break;
        //            case "DELETE":
        //                this._config.ProtocolProcessor.ProcessDelete(context);
        //                break;
        //            default:
        //                //For any other HTTP Verb we send a 405 Method Not Allowed
        //                context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
        //                break;
        //        }

        //        //Update the Cache as the request may have changed the endpoint
        //        this.UpdateConfig(context);
        //    }
        //    catch (SparqlHttpProtocolUriResolutionException)
        //    {
        //        //If URI Resolution fails we send a 400 Bad Request
        //        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        //    }
        //    catch (SparqlHttpProtocolUriInvalidException)
        //    {
        //        //If URI is invalid we send a 400 Bad Request
        //        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        //    }
        //    catch (NotSupportedException)
        //    {
        //        //If Not Supported we send a 405 Method Not Allowed
        //        context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
        //    }
        //    catch (NotImplementedException)
        //    {
        //        //If Not Implemented we send a 501 Not Implemented
        //        context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
        //    }
        //    catch (RdfWriterSelectionException)
        //    {
        //        //If we can't select a valid Writer when returning content we send a 406 Not Acceptable
        //        context.Response.StatusCode = (int)HttpStatusCode.NotAcceptable;
        //    }
        //    catch (RdfParserSelectionException)
        //    {
        //        //If we can't select a valid Parser when receiving content we send a 415 Unsupported Media Type
        //        context.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType;
        //    }
        //    catch (RdfParseException)
        //    {
        //        //If we can't parse the received content successfully we send a 400 Bad Request
        //        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        //    }
        //    catch (Exception)
        //    {
        //        //For any other error we'll send a 500 Internal Server Error
        //        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        //    }
        //}

        #region Error Handling

        /// <summary>
        /// Handles errors in processing SPARQL Query Requests
        /// </summary>
        /// <param name="context">Context of the HTTP Request</param>
        /// <param name="title">Error title</param>
        /// <param name="query">Sparql Query</param>
        /// <param name="ex">Error</param>
        protected virtual void HandleQueryErrors(HttpServerContext context, String title, String query, Exception ex)
        {
            HandlerHelper.HandleQueryErrors(new ServerContext(context), this._config, title, query, ex);
            context.Response.OutputStream.Flush();
        }
Esempio n. 3
0
 public void SetInfo(HttpServerContext context)
 {
     this.context = context;
 }
        /// <summary>
        /// Processes Query requests
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public void ProcessQueryRequest(HttpServerContext context)
        {
            if (this._config.QueryProcessor == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                return;
            }

            //Try and parse the Form Variables
            FormVariables form = new FormVariables(context);

            if (!form.IsValid)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            if (context.Request.HttpMethod.Equals("OPTIONS"))
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                return;
                //TODO: Support Service Description?
                ////OPTIONS requests always result in the Service Description document
                //IGraph svcDescrip = SparqlServiceDescriber.GetServiceDescription(context, this._config, UriFactory.Create(context.Request.Url.AbsoluteUri), ServiceDescriptionType.Query);
                //HandlerHelper.SendToClient(context, svcDescrip, this._config);
                //return;
            }

            //See if there has been an query submitted
            String queryText = context.Request.QueryString["query"];

            if (queryText == null || queryText.Equals(String.Empty))
            {
                if (context.Request.ContentType != null)
                {
                    if (context.Request.ContentType.Equals(MimeTypesHelper.WWWFormURLEncoded))
                    {
                        queryText = form["query"];
                    }
                    else if (context.Request.ContentType.Equals(MimeTypesHelper.SparqlQuery))
                    {
                        queryText = new StreamReader(context.Request.InputStream).ReadToEnd();
                    }
                }
                else
                {
                    queryText = form["query"];
                }
            }

            //If no Query sent either show Query Form or give a HTTP 400 response
            if (queryText == null || queryText.Equals(String.Empty))
            {
                if (this._config.ShowQueryForm)
                {
                    this.ShowQueryForm(context);
                    return;
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return;
                }
            }

            //Get Other options associated with this query
            List <String> userDefaultGraphs = new List <String>();
            List <String> userNamedGraphs   = new List <String>();
            long          timeout           = 0;
            bool          partialResults    = this._config.DefaultPartialResults;

            //Get the Default Graph URIs (if any)
            if (context.Request.QueryString["default-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(context.Request.QueryString.GetValues("default-graph-uri"));
            }
            else if (form["default-graph-uri"] != null)
            {
                userDefaultGraphs.AddRange(form.GetValues("default-graph-uri"));
            }
            //Get the Named Graph URIs (if any)
            if (context.Request.QueryString["named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(context.Request.QueryString.GetValues("named-graph-uri"));
            }
            else if (form["named-graph-uri"] != null)
            {
                userNamedGraphs.AddRange(form.GetValues("named-graph-uri"));
            }

            //Get Timeout setting (if any)
            if (context.Request.QueryString["timeout"] != null)
            {
                if (!Int64.TryParse(context.Request.QueryString["timeout"], out timeout))
                {
                    timeout = this._config.DefaultTimeout;
                }
            }
            else if (form["timeout"] != null)
            {
                if (!Int64.TryParse(form["timeout"], out timeout))
                {
                    timeout = this._config.DefaultTimeout;
                }
            }
            //Get Partial Results Setting (if any);
            if (context.Request.QueryString["partialResults"] != null)
            {
                if (!Boolean.TryParse(context.Request.QueryString["partialResults"], out partialResults))
                {
                    partialResults = this._config.DefaultPartialResults;
                }
            }
            else if (form["partialResults"] != null)
            {
                if (!Boolean.TryParse(form["partialResults"], out partialResults))
                {
                    partialResults = this._config.DefaultPartialResults;
                }
            }

            try
            {
                //Now we're going to parse the Query
                SparqlQueryParser parser = new SparqlQueryParser(this._config.QuerySyntax);
                parser.ExpressionFactories = this._config.ExpressionFactories;
                parser.QueryOptimiser      = this._config.QueryOptimiser;
                SparqlQuery query = parser.ParseFromString(queryText);
                query.AlgebraOptimisers         = this._config.AlgebraOptimisers;
                query.PropertyFunctionFactories = this._config.PropertyFunctionFactories;

                //TODO: Support Authentication?
                ////Check whether we need to use authentication
                ////If there are no user groups then no authentication is in use so we default to authenticated with no per-action authentication needed
                //bool isAuth = true, requireActionAuth = false;
                //if (this._config.UserGroups.Any())
                //{
                //    //If we have user
                //    isAuth = HandlerHelper.IsAuthenticated(context, this._config.UserGroups);
                //    requireActionAuth = true;
                //}
                //if (!isAuth) return;

                ////Is this user allowed to make this kind of query?
                //if (requireActionAuth) HandlerHelper.IsAuthenticated(context, this._config.UserGroups, this.GetQueryPermissionAction(query));

                //Set the Default Graph URIs (if any)
                if (userDefaultGraphs.Count > 0)
                {
                    //Default Graph Uri specified by default-graph-uri parameter or Web.config settings
                    foreach (String userDefaultGraph in userDefaultGraphs)
                    {
                        if (!userDefaultGraph.Equals(String.Empty))
                        {
                            query.AddDefaultGraph(UriFactory.Create(userDefaultGraph));
                        }
                    }
                }
                else if (!this._config.DefaultGraphURI.Equals(String.Empty))
                {
                    //Only applies if the Query doesn't specify any Default Graph
                    if (!query.DefaultGraphs.Any())
                    {
                        query.AddDefaultGraph(UriFactory.Create(this._config.DefaultGraphURI));
                    }
                }

                //Set the Named Graph URIs (if any)
                if (userNamedGraphs.Count > 0)
                {
                    foreach (String userNamedGraph in userNamedGraphs)
                    {
                        if (!userNamedGraph.Equals(String.Empty))
                        {
                            query.AddNamedGraph(UriFactory.Create(userNamedGraph));
                        }
                    }
                }

                //Set Timeout setting
                if (timeout > 0)
                {
                    query.Timeout = timeout;
                }
                else
                {
                    query.Timeout = this._config.DefaultTimeout;
                }

                //Set Partial Results Setting
                query.PartialResultsOnTimeout = partialResults;

                //Set Describe Algorithm
                query.Describer = this._config.DescribeAlgorithm;

                //Now we can finally make the query and return the results
                Object result = this._config.QueryProcessor.ProcessQuery(query);
                this.ProcessQueryResults(context, result);
            }
            catch (RdfParseException parseEx)
            {
                HandleQueryErrors(context, "Parsing Error", queryText, parseEx, (int)HttpStatusCode.BadRequest);
            }
            catch (RdfQueryTimeoutException timeoutEx)
            {
                HandleQueryErrors(context, "Query Timeout Error", queryText, timeoutEx);
            }
            catch (RdfQueryException queryEx)
            {
                HandleQueryErrors(context, "Query Error", queryText, queryEx);
            }
            catch (RdfWriterSelectionException writerSelEx)
            {
                HandleQueryErrors(context, "Output Selection Error", queryText, writerSelEx, (int)HttpStatusCode.NotAcceptable);
            }
            catch (RdfException rdfEx)
            {
                HandleQueryErrors(context, "RDF Error", queryText, rdfEx);
            }
            catch (Exception ex)
            {
                HandleQueryErrors(context, "Error", queryText, ex);
            }
        }
Esempio n. 5
0
 public void SetData(HttpServerContext context)
 {
     _context = context;
 }
Esempio n. 6
0
 public override void Execute(HttpServerContext context)
 {
     context.Response.Content(_content, _mimeType);
 }
Esempio n. 7
0
        public HttpStatusCode Request(HttpServerContext httpContext)
        {
            var statusCode = HttpStatusCode.NotFound;
            var path       = httpContext.Path;
            // if bin or json
            var bin = path.EndsWith(".bin");

            if (bin == true)
            {
                path = path.Substring(0, path.Length - 4);
            }
            else if (path.EndsWith(".json"))
            {
                path = path.Substring(0, path.Length - 5);
            }
            //
            httpContext.ResponseHeader["Via"] = HttpHandler.hostname;
            //
            if ("/queue/rpush" == path)
            {
                statusCode = this.Push(Action.RPUSH, httpContext, bin);
            }
            else if ("/queue/lpush" == path)
            {
                statusCode = this.Push(Action.LPUSH, httpContext, bin);
            }
            else if ("/queue/pull" == path)
            {
                statusCode = this.Pull(httpContext, bin);
            }
            else if ("/queue/delete" == path)
            {
                statusCode = this.General(new Action(), Action.DELETE, httpContext, bin);
            }
            else if ("/queue/lcancel" == path)
            {
                statusCode = this.General(new Action(), Action.LCANCEL, httpContext, bin);
            }
            else if ("/queue/rcancel" == path)
            {
                statusCode = this.General(new Action(), Action.RCANCEL, httpContext, bin);
            }
            else if ("/queue/count" == path)
            {
                statusCode = this.General(new CountAction(), Action.COUNT, httpContext, bin);
            }
            else if ("/queue/clear" == path)
            {
                statusCode = this.General(new ClearAction(), Action.CLEAR, httpContext, bin);
            }
            else if ("/queue/createqueue" == path)
            {
                statusCode = this.General(new Action(), Action.CREATEQUEUE, httpContext, bin);
            }
            else if ("/queue/deletequeue" == path)
            {
                statusCode = this.General(new Action(), Action.DELETEQUEUE, httpContext, bin);
            }
            else if ("/ajax.js" == path)
            {
                statusCode = this.OutputScript(httpContext, "ajax.js");
            }
            else if ("/control.js" == path)
            {
                statusCode = this.OutputScript(httpContext, "control.js");
            }
            else
            {
                statusCode = this.Home(httpContext);
            }

            return(statusCode);
        }
        /// <summary>
        /// Generates a SPARQL Query Form
        /// </summary>
        /// <param name="context">HTTP Context</param>
        protected virtual void ShowQueryForm(HttpServerContext context)
        {
            //Set Content Type
            context.Response.ContentType = "text/html";

            //Get a HTML Text Writer
            HtmlTextWriter output = new HtmlTextWriter(new StreamWriter(context.Response.OutputStream));

            //Page Header
            output.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            output.RenderBeginTag(HtmlTextWriterTag.Html);
            output.RenderBeginTag(HtmlTextWriterTag.Head);
            output.RenderBeginTag(HtmlTextWriterTag.Title);
            output.WriteEncodedText("SPARQL Query Interface");
            output.RenderEndTag();
            //Add Stylesheet
            if (!this._config.Stylesheet.Equals(String.Empty))
            {
                output.AddAttribute(HtmlTextWriterAttribute.Href, this._config.Stylesheet);
                output.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
                output.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
                output.RenderBeginTag(HtmlTextWriterTag.Link);
                output.RenderEndTag();
            }
            output.RenderEndTag();


            //Header Text
            output.RenderBeginTag(HtmlTextWriterTag.Body);
            output.RenderBeginTag(HtmlTextWriterTag.H3);
            output.WriteEncodedText("SPARQL Query Interface");
            output.RenderEndTag();

            //Query Form
            output.AddAttribute(HtmlTextWriterAttribute.Name, "sparqlQuery");
            output.AddAttribute("method", "get");
            output.AddAttribute("action", context.Request.Url.AbsoluteUri);
            output.RenderBeginTag(HtmlTextWriterTag.Form);

            if (!this._config.IntroductionText.Equals(String.Empty))
            {
                output.RenderBeginTag(HtmlTextWriterTag.P);
                output.Write(this._config.IntroductionText);
                output.RenderEndTag();
            }

            output.WriteEncodedText("Query");
            output.WriteBreak();
            output.AddAttribute(HtmlTextWriterAttribute.Name, "query");
            output.AddAttribute(HtmlTextWriterAttribute.Rows, "15");
            output.AddAttribute(HtmlTextWriterAttribute.Cols, "100");
            int currIndent = output.Indent;

            output.Indent = 0;
            output.RenderBeginTag(HtmlTextWriterTag.Textarea);
            output.Indent = 0;
            if (!this._config.DefaultQuery.Equals(String.Empty))
            {
                output.WriteEncodedText(this._config.DefaultQuery);
            }
            output.RenderEndTag();
            output.Indent = currIndent;
            output.WriteBreak();

            output.WriteEncodedText("Default Graph URI: ");
            output.AddAttribute(HtmlTextWriterAttribute.Name, "default-graph-uri");
            output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
            output.AddAttribute(HtmlTextWriterAttribute.Size, "100");
            output.AddAttribute(HtmlTextWriterAttribute.Value, this._config.DefaultGraphURI);
            output.RenderBeginTag(HtmlTextWriterTag.Input);
            output.RenderEndTag();
            output.WriteBreak();

            if (this._config.SupportsTimeout)
            {
                output.WriteEncodedText("Timeout: ");
                output.AddAttribute(HtmlTextWriterAttribute.Name, "timeout");
                output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
                output.AddAttribute(HtmlTextWriterAttribute.Value, this._config.DefaultTimeout.ToString());
                output.RenderBeginTag(HtmlTextWriterTag.Input);
                output.RenderEndTag();
                output.WriteEncodedText(" Milliseconds");
                output.WriteBreak();
            }

            if (this._config.SupportsPartialResults)
            {
                output.AddAttribute(HtmlTextWriterAttribute.Name, "partialResults");
                output.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox");
                if (this._config.DefaultPartialResults)
                {
                    output.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
                }
                output.AddAttribute(HtmlTextWriterAttribute.Value, "true");
                output.RenderBeginTag(HtmlTextWriterTag.Input);
                output.RenderEndTag();
                output.WriteEncodedText(" Partial Results on Timeout?");
                output.WriteBreak();
            }

            output.AddAttribute(HtmlTextWriterAttribute.Type, "submit");
            output.AddAttribute(HtmlTextWriterAttribute.Value, "Make Query");
            output.RenderBeginTag(HtmlTextWriterTag.Input);
            output.RenderEndTag();

            output.RenderEndTag(); //End Form

            //End of Page
            output.RenderEndTag(); //End Body
            output.RenderEndTag(); //End Html

            output.Flush();
        }
Esempio n. 9
0
        /// <summary>
        /// Erstellt eine neue Instanz eines Prozesszustandes
        /// </summary>
        /// <param name="context">Der Kontext</param>
        /// <param name="configFileName">Der Dateiname der Konfiguration oder null</param>
        /// <returns>Die Instanz des Plugins</returns>
        public override IPlugin Create(HttpServerContext context, string configFileName)
        {
            var plugin = Create <AgentPlugin>(context, configFileName);

            return(plugin);
        }
Esempio n. 10
0
 public HttpState(HttpServerContext context, bool bin)
 {
     this.httpContext = context;
     this.bin         = bin;
 }
Esempio n. 11
0
        private System.Net.HttpStatusCode HttpProcess(HttpServerContext httpContext)
        {
            var nowTick = Adf.UnixTimestampHelper.ToInt64Timestamp();

            //
            var servername = this.serviceContext.ServiceName;
            var hostname   = System.Net.Dns.GetHostName();
            //
            var build = new System.Text.StringBuilder();

            build.AppendLine("<!DOCTYPE html>");
            build.AppendLine("<html>");
            build.AppendLine("<head>");

            build.AppendLine("<style type=\"text/css\">");
            build.AppendLine(".tb1{ background-color:#D5D5D5;}");
            build.AppendLine(".tb1 td{ background-color:#FFF;}");
            build.AppendLine(".tb1 tr.None td{ background-color:#FFF;}");
            build.AppendLine(".tb1 tr.Success td{ background-color:#FFF;}");
            build.AppendLine(".tb1 tr.Failed td{ background-color:#FAEBD7;}");
            build.AppendLine(".tb1 tr.Running td{ background-color:#F5FFFA;}");
            build.AppendLine("img,form{ border:0px;}");
            build.AppendLine("img.button{ cursor:pointer; }");
            build.AppendLine("a { padding-left:5px; }");
            build.AppendLine("</style>");

            build.AppendLine("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">");
            build.AppendLine("<title>" + servername + " Via " + hostname + "</title>");
            build.AppendLine("</head>");
            build.AppendLine("<body>");

            build.AppendLine("<div>");
            build.AppendLine("<span>");
            build.AppendLine("Powered by <a href=\"http://www.aooshi.org/adf?project=" + servername + "\" target=\"_blank\">" + servername + "</a> ");
            build.Append('v');
            build.Append(version.Major);
            build.Append(".");
            build.Append(version.Minor);
            build.Append(".");
            build.Append(version.Build);

            build.AppendLine(" Via " + hostname);
            build.AppendLine("</span></div>");

            build.AppendLine("<table class=\"tb1\" width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"3\">");
            build.AppendLine("<thead>");
            build.AppendLine("<tr>");
            build.AppendLine("<th align=\"left\" width=\"35\">No.</th>");
            build.AppendLine("<th align=\"left\">Node</th>");
            build.AppendLine("<th width=\"120\">Type</th>");
            build.AppendLine("<th width=\"160\">State</th>");
            build.AppendLine("</tr>");
            build.AppendLine("</thead>");
            build.AppendLine("<tbody>");


            build.AppendLine("<tr>");
            build.AppendLine("<td align=\"left\">1.</td>");
            build.AppendLine("<td align=\"left\">" + HAContext.Node1Point + "</td>");
            build.AppendLine("<td align=\"center\">" + this.GetNodeType(1) + "</td>");
            build.AppendLine("<td align=\"center\">" + (HAContext.Connectioned1 ? "connectioned" : "disconnectioned") + "</td>");
            build.AppendLine("</tr>");


            build.AppendLine("<tr>");
            build.AppendLine("<td align=\"left\">2.</td>");
            build.AppendLine("<td align=\"left\">" + HAContext.Node2Point + "</td>");
            build.AppendLine("<td align=\"center\">" + this.GetNodeType(2) + "</td>");
            build.AppendLine("<td align=\"center\">" + (HAContext.Connectioned2 ? "connectioned" : "disconnectioned") + "</td>");
            build.AppendLine("</tr>");


            build.AppendLine("<tr>");
            build.AppendLine("<td align=\"left\">3.</td>");
            build.AppendLine("<td align=\"left\">" + HAContext.Node3Point + "</td>");
            //build.AppendLine("<td align=\"center\">" + (HAContext.MasterNum == 3 ? "master" : "slave") + "</td>");
            build.AppendLine("<td align=\"center\">witness</td>");
            build.AppendLine("<td align=\"center\">" + (HAContext.Connectioned3 ? "connectioned" : "disconnectioned") + "</td>");
            build.AppendLine("</tr>");

            //
            build.AppendLine("<tr>");
            build.Append("<td colspan=\"4\" align=\"left\">MasterKey: " + HAContext.MasterKey);
            build.AppendLine("</td>");
            build.AppendLine("</tr>");

            //
            build.AppendLine("<tr>");
            build.AppendLine("<td colspan=\"4\" align=\"right\">");

            var stateArray = Enum.GetNames(typeof(ServiceState));
            var state      = this.serviceContext.ServiceState.ToString();

            for (int i = 0, l = stateArray.Length; i < l; i++)
            {
                if (i > 0)
                {
                    build.Append(" | ");
                }
                //
                if (state == stateArray[i])
                {
                    build.Append("<strong>" + stateArray[i] + "</strong>");
                }
                else
                {
                    build.Append(stateArray[i]);
                }
            }
            build.AppendLine();
            build.AppendLine("</td>");
            build.AppendLine("</tr>");

            //
            build.AppendLine("</tbody>");
            build.AppendLine("</table>");

            //
            build.AppendLine("</body>");
            build.AppendLine("</html>");

            //
            httpContext.Content = build.ToString();
            httpContext.ResponseHeader["Via"]          = hostname;
            httpContext.ResponseHeader["Content-Type"] = "text/html";

            return(System.Net.HttpStatusCode.OK);
        }
Esempio n. 12
0
 public HttpResourceMapping(HttpServerContext context)
 {
     this.httpConfig = context.ServerConfig ?? throw new ArgumentNullException(nameof(httpConfig));
 }
 public override void Execute(HttpServerContext context)
 {
     context.Response.StatusCode = 301;
     context.Response.AddHeader("Location", _url);
     context.Response.OutputStream.Close();
 }
        /// <summary>
        /// Processes a request
        /// </summary>
        /// <param name="context">Server Context</param>
        public void ProcessRequest(HttpServerContext context)
        {
            //Get the server options
            RdfServerOptions options = context.Server.AppSettings[RdfServerOptions.ServerOptionsKey] as RdfServerOptions;

            if (options == null)
            {
                throw new DotNetRdfConfigurationException("rdfServer Options were not found");
            }

            //Get the configuration graph
            IGraph g = context.Server.Context[RdfServerOptions.DotNetRdfConfigKey] as IGraph;

            if (g == null)
            {
                g = options.LoadConfigurationGraph();
                if (g == null)
                {
                    throw new DotNetRdfConfigurationException("The HTTP Server does not contain a Configuration Graph in its State Information");
                }
                context.Server.Context[RdfServerOptions.DotNetRdfConfigKey] = g;
            }


            //Generate the expected Path and try and load the Configuration using the appropriate Node
            String expectedPath;

            WebConfigurationLoader.FindObject(g, context.Request.Url, out expectedPath);
            INode objNode = g.GetUriNode(new Uri("dotnetrdf:" + expectedPath));

            if (objNode == null)
            {
                throw new DotNetRdfConfigurationException("The Configuration Graph does not contain a URI Node with the expected URI <dotnetrdf:" + expectedPath + ">");
            }
            this._config = new SparqlServerConfiguration(g, objNode);

            //Dispath the request appropriately
            String path = context.Request.Url.AbsolutePath;

            path = path.Substring(path.LastIndexOf('/') + 1);

            switch (path)
            {
            case "query":
                this.ProcessQueryRequest(context);
                break;

            case "update":
                this.ProcessUpdateRequest(context);
                break;

            case "description":
                //TODO: Add Service Description support
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                break;

            default:
                //TODO: Can we easily add Protocol Support or not?
                //this.ProcessProtocolRequest(context);
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                break;
            }
        }
Esempio n. 15
0
        public System.Net.HttpStatusCode HttpProcess(HttpServerContext httpContext)
        {
            var hostname = System.Net.Dns.GetHostName();


            if (httpContext.Path.Equals("/favicon.ico"))
            {
                return(System.Net.HttpStatusCode.NotFound);
            }
            else if (httpContext.Path.Equals("/string-view"))
            {
                this.StringView(httpContext);
                return(System.Net.HttpStatusCode.OK);
            }

            var size    = 100;
            var k       = (httpContext.QueryString["k"] ?? "").Trim();
            var v       = (httpContext.QueryString["v"] ?? "").Trim();
            var expires = Adf.ConvertHelper.ToInt32(httpContext.QueryString["expires"], 60);
            var act     = httpContext.QueryString["act"];

            var msg = "";

            switch (act)
            {
            case "search":
                msg = "Search " + k + " Result:";
                break;

            case "add":
                var add_result = new CacheServer().Add(k, Encoding.UTF8.GetBytes(v), expires);
                if (add_result)
                {
                    msg = "Add " + k + " Result: <font color=\"green\">Success</font>";
                }
                else
                {
                    msg = "Add " + k + " Result: <font color=\"red\">Failure or Exists</font>";
                }
                break;

            case "set":
                var set_result = new CacheServer().Set(k, Encoding.UTF8.GetBytes(v), expires, expires);
                if (set_result == 0)
                {
                    msg = "Set " + k + " Result: <font color=\"red\">Failure</font>";
                }
                else if (set_result == 1)
                {
                    msg = "Set " + k + " Result: <font color=\"green\">Replace success</font>";
                }
                else if (set_result == 2)
                {
                    msg = "Set " + k + " Result: <font color=\"green\">New Cache</font>";
                }
                else if (set_result == 2)
                {
                    msg = "Set " + k + " Result: ";
                }
                break;

            case "del":
                var del_result = new CacheServer().Delete(k);
                if (del_result)
                {
                    msg = "Del " + k + " Result: <font color=\"green\">Success</font>";
                }
                else
                {
                    msg = "Del " + k + " Result: <font color=\"red\">Failure or No Exists</font>";
                };
                break;

            default:
                msg = "Last " + size + " Cache List:";
                break;
            }


            //count
            var count = 0;

            for (int i = 0; i < HASH_POOL_SIZE; i++)
            {
                count += Program.CacheManagers[i].Count;
            }
            //
            var build = new StringBuilder();

            build.AppendLine("<!DOCTYPE html>");
            build.AppendLine("<html>");
            build.AppendLine("<head>");

            build.AppendLine("<style type=\"text/css\">");
            build.AppendLine(".tb1{ background-color:#D5D5D5;}");
            build.AppendLine(".tb1 td{ background-color:#FFF;}");
            build.AppendLine(".tb1 tr.None td{ background-color:#FFF;}");
            build.AppendLine(".tb1 tr.Success td{ background-color:#FFF;}");
            build.AppendLine(".tb1 tr.Failed td{ background-color:#FAEBD7;}");
            build.AppendLine(".tb1 tr.Running td{ background-color:#F5FFFA;}");
            build.AppendLine("img,form{ border:0px;}");
            build.AppendLine("img.button{ cursor:pointer; }");
            build.AppendLine("a { padding-left:5px; }");
            build.AppendLine("</style>");

            build.AppendLine("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">");
            build.AppendLine("<title>" + this.servername + " Via " + hostname + "</title>");
            build.AppendLine("</head>");
            build.AppendLine("<body>");

            build.AppendLine("<div><form action=\"/\">");
            build.AppendLine("<input size=\"15\" type=\"text\" name=\"k\" placeholder=\"key\" value=\"" + k + "\"  />");
            build.AppendLine("<input size=\"15\" type=\"text\" name=\"v\" placeholder=\"value\" value=\"" + v + "\"  />");
            build.AppendLine("<input size=\"15\" type=\"text\" name=\"expires\" placeholder=\"expires seconds\" value=\"" + expires + "\"  />");
            build.AppendLine("<input type=\"hidden\" name=\"act\" value=\"search\"  />");
            build.AppendLine("<input type=\"button\" value=\"Get\" onclick=\"this.form.act.value = 'get'; this.form.submit();\" />");
            build.AppendLine("<input type=\"button\" value=\"Add\" onclick=\"this.form.act.value = 'add'; this.form.submit();\" />");
            build.AppendLine("<input type=\"button\" value=\"Set\" onclick=\"this.form.act.value = 'set'; this.form.submit();\" />");
            build.AppendLine("<input type=\"button\" value=\"Home\" onclick=\"location.href='/';\" />");
            build.AppendLine("<span style=\"float:right;\">");
            build.AppendLine("Powered by <a href=\"http://www.aooshi.org/adf\" target=\"_blank\">Adf.CacheServer</a>");
            build.Append('v');
            build.Append(version.Major);
            build.Append(".");
            build.Append(version.Minor);
            build.Append(".");
            build.Append(version.Build);
            build.AppendLine(" Via " + hostname);
            build.AppendLine(" , Pool Size: <font color=\"green\">" + HASH_POOL_SIZE + "</font>");
            build.AppendLine(" , Caches Totals: <font color=\"green\">" + count + "</font>");
            build.AppendLine("</span></form></div>");

            build.AppendLine("<div>" + msg + "</div>");
            build.AppendLine("<table class=\"tb1\" width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"3\">");
            build.AppendLine("<thead>");
            build.AppendLine("<tr>");
            build.AppendLine("<th align=\"left\">Key</th>");
            build.AppendLine("<th width=\"160\">Bytes</th>");
            build.AppendLine("<th width=\"120\">Expires</th>");
            build.AppendLine("<th width=\"120\">Options</th>");
            build.AppendLine("</tr>");
            build.AppendLine("</thead>");

            List <CacheProperty> propertys = null;

            if (k == "")
            {
                propertys = this.GetPropertys(size);
            }
            else
            {
                var hashCode = HashHelper.GetHashCode(k);
                var property = Program.CacheManagers[hashCode % HASH_POOL_SIZE].GetProperty(k);

                propertys = new List <CacheProperty>();
                if (property.Expires != 0)
                {
                    propertys.Add(property);
                }
            }
            var nowTick      = Environment.TickCount;
            var expireString = "";

            foreach (var p in propertys)
            {
                if (nowTick - p.Expires > -1)
                {
                    expireString = "Expired";
                }
                else
                {
                    try
                    {
                        expireString = ((p.Expires - nowTick) / 1000).ToString();
                    }
                    catch
                    {
                        expireString = "Expired";
                    }
                }

                build.AppendLine("<tbody>");
                build.AppendLine("<tr>");
                //build.AppendLine("<td align=\"left\">" + item.Id + "|"+ item.Expires +"|"+ seconds +"</td>");
                build.AppendLine("<td align=\"left\"><a href=\"string-view?k=" + p.Key + "\" target=\"string-view\">" + p.Key + "</a></td>");
                build.AppendLine("<td align=\"center\">" + Adf.ByteHelper.FormatBytes(p.Size) + "</td>");
                build.AppendLine("<td align=\"center\">" + expireString + "</td>");
                build.AppendLine("<td align=\"center\"><a href=\"?k=" + p.Key + "&act=del\" target=\"_self\">Remove</a></td>");
                build.AppendLine("</tr>");
                build.AppendLine("</tbody>");
            }

            build.AppendLine("</table>");

            build.AppendLine("</body>");
            build.AppendLine("</html>");

            //
            httpContext.Content = build.ToString();
            httpContext.ResponseHeader["Via"]          = hostname;
            httpContext.ResponseHeader["Content-Type"] = "text/html";
            return(System.Net.HttpStatusCode.OK);
        }
 /// <summary>
 /// Handles errors in processing SPARQL Update Requests
 /// </summary>
 /// <param name="context">Context of the HTTP Request</param>
 /// <param name="title">Error title</param>
 /// <param name="update">SPARQL Update</param>
 /// <param name="ex">Error</param>
 /// <param name="statusCode">HTTP Status code to return</param>
 protected virtual void HandleUpdateErrors(HttpServerContext context, String title, String update, Exception ex, int statusCode)
 {
     HandlerHelper.HandleUpdateErrors(new ServerContext(context), this._config, title, update, ex, statusCode);
     context.Response.OutputStream.Flush();
 }
Esempio n. 17
0
 public System.Net.HttpStatusCode HttpProcess(HttpServerContext httpContext)
 {
     return(Program.HttpHandler.Request(httpContext));
 }
        /// <summary>
        /// Generates a SPARQL Update Form
        /// </summary>
        /// <param name="context">HTTP Context</param>
        protected virtual void ShowUpdateForm(HttpServerContext context)
        {
            //Set Content Type
            context.Response.ContentType = "text/html";

            //Get a HTML Text Writer
            HtmlTextWriter output = new HtmlTextWriter(new StreamWriter(context.Response.OutputStream));

            //Page Header
            output.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            output.RenderBeginTag(HtmlTextWriterTag.Html);
            output.RenderBeginTag(HtmlTextWriterTag.Head);
            output.RenderBeginTag(HtmlTextWriterTag.Title);
            output.WriteEncodedText("SPARQL Update Interface");
            output.RenderEndTag();
            //Add Stylesheet
            if (!this._config.Stylesheet.Equals(String.Empty))
            {
                output.AddAttribute(HtmlTextWriterAttribute.Href, this._config.Stylesheet);
                output.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
                output.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
                output.RenderBeginTag(HtmlTextWriterTag.Link);
                output.RenderEndTag();
            }
            output.RenderEndTag();


            //Header Text
            output.RenderBeginTag(HtmlTextWriterTag.Body);
            output.RenderBeginTag(HtmlTextWriterTag.H3);
            output.WriteEncodedText("SPARQL Update Interface");
            output.RenderEndTag();

            //Query Form
            output.AddAttribute(HtmlTextWriterAttribute.Name, "sparqlUpdate");
            output.AddAttribute("method", "post");
            output.AddAttribute("action", context.Request.Url.AbsoluteUri);
            output.AddAttribute("enctype", MimeTypesHelper.WWWFormURLEncoded);
            output.RenderBeginTag(HtmlTextWriterTag.Form);

            if (!this._config.IntroductionText.Equals(String.Empty))
            {
                output.RenderBeginTag(HtmlTextWriterTag.P);
                output.Write(this._config.IntroductionText);
                output.RenderEndTag();
            }

            output.WriteEncodedText("Update");
            output.WriteBreak();
            output.AddAttribute(HtmlTextWriterAttribute.Name, "update");
            output.AddAttribute(HtmlTextWriterAttribute.Rows, "15");
            output.AddAttribute(HtmlTextWriterAttribute.Cols, "100");
            int currIndent = output.Indent;

            output.Indent = 0;
            output.RenderBeginTag(HtmlTextWriterTag.Textarea);
            output.Indent = 0;
            if (!this._config.DefaultUpdate.Equals(String.Empty))
            {
                output.WriteEncodedText(this._config.DefaultUpdate);
            }
            output.RenderEndTag();
            output.Indent = currIndent;
            output.WriteBreak();

            //output.WriteEncodedText("Default Graph URI: ");
            //output.AddAttribute(HtmlTextWriterAttribute.Name, "default-graph-uri");
            //output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
            //output.AddAttribute(HtmlTextWriterAttribute.Size, "100");
            //output.AddAttribute(HtmlTextWriterAttribute.Value, this._config.DefaultGraphURI);
            //output.RenderBeginTag(HtmlTextWriterTag.Input);
            //output.RenderEndTag();
            //output.WriteBreak();

            output.AddAttribute(HtmlTextWriterAttribute.Type, "submit");
            output.AddAttribute(HtmlTextWriterAttribute.Value, "Perform Update");
            output.RenderBeginTag(HtmlTextWriterTag.Input);
            output.RenderEndTag();

            output.RenderEndTag(); //End Form

            //End of Page
            output.RenderEndTag(); //End Body
            output.RenderEndTag(); //End Html

            output.Flush();
        }
Esempio n. 19
0
 public abstract void Execute(HttpServerContext context);
Esempio n. 20
0
        static HttpStatusCode WebCallback(HttpServerContext context)
        {
            context.ContentBuffer = System.IO.File.ReadAllBytes(System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Demo.html"));

            return(HttpStatusCode.OK);
        }
Esempio n. 21
0
 public HttpRequestDispatcher(HttpServerContext serverContext)
 {
     ServerContext = serverContext;
 }