예제 #1
0
        protected void ExecuteUpdate(string requestPath)
        {
            var updateExpression = File.ReadAllText(requestPath);

#if PORTABLE
            var result = _service.ExecuteUpdate(_storeName, updateExpression);
#else
            var result = _service.ExecuteUpdate(_storeName, updateExpression, true);
#endif
            Assert.IsTrue(result.JobCompletedOk, "SPARQL Update failed for update from file path {0} : {1} : {2}", requestPath, result.StatusMessage, result.ExceptionInfo);
        }
        public SparqlUpdateModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider permissionsProvider)
        {
            this.RequiresBrightstarStorePermission(permissionsProvider, get: StorePermissions.SparqlUpdate, post: StorePermissions.SparqlUpdate);

            Get["/{storeName}/update"] = parameters =>
            {
                var requestObject = this.Bind <SparqlUpdateRequestObject>();
                ViewBag.Title = requestObject.StoreName + " - SPARQL Update";
                return
                    (Negotiate.WithAllowedMediaRange(Html)
                     .WithModel(requestObject)
                     .WithView("SparqlUpdate"));
            };

            Post["/{storeName}/update"] = parameters =>
            {
                var requestObject = this.Bind <SparqlUpdateRequestObject>();
                ViewBag.Title = requestObject.StoreName + " - SPARQL Update";
                if (SparqlRequest.Matches(Request.Headers.ContentType))
                {
                    using (var reader = new StreamReader(Request.Body))
                    {
                        requestObject.Update = reader.ReadToEnd();
                    }
                }

                if (!parameters["storeName"].HasValue)
                {
                    return(HttpStatusCode.BadRequest);
                }
                if (string.IsNullOrWhiteSpace(requestObject.Update))
                {
                    return(HttpStatusCode.BadRequest);
                }

                IJobInfo jobInfo = brightstarService.ExecuteUpdate(parameters["storeName"], requestObject.Update, true);
                if (jobInfo.JobCompletedOk)
                {
                    return(jobInfo.MakeResponseObject(requestObject.StoreName));
                }
                return
                    (Negotiate.WithStatusCode(HttpStatusCode.BadRequest)
                     .WithModel(jobInfo.MakeResponseObject(requestObject.StoreName)));
            };
        }
예제 #3
0
        public void TestDeleteFromGraph()
        {
            var storeName = CreateStore("TestDeleteFromGraph");

            _client.ExecuteUpdate(storeName,
                                  @"PREFIX foaf:  <http://xmlns.com/foaf/0.1/>
INSERT DATA {
  GRAPH <http://example/addresses> {
    <http://example/william> a foaf:Person .
    <http://example/william> foaf:givenName ""William"" .
    <http://example/william> foaf:mbox <mailto:bill@example> .

    <http://example/fred> a foaf:Person .
    <http://example/fred> foaf:givenName ""Fred"" .
    <http://example/fred> foaf:mbox  <mailto:fred@example> .
  }
}");
            var results    = _client.ExecuteQuery(storeName, "PREFIX foaf:  <http://xmlns.com/foaf/0.1/> SELECT ?p FROM <http://example/addresses> WHERE { ?p a foaf:Person }");
            var resultsDoc = XDocument.Load(results);

            Assert.AreEqual(2, resultsDoc.SparqlResultRows().Count());

            results = _client.ExecuteQuery(storeName,
                                           "PREFIX foaf:  <http://xmlns.com/foaf/0.1/> SELECT ?person ?property ?value FROM <http://example/addresses> WHERE { ?person ?property ?value ; foaf:givenName 'Fred' } ");
            resultsDoc = XDocument.Load(results);
            Assert.AreEqual(3, resultsDoc.SparqlResultRows().Count());

            _client.ExecuteUpdate(storeName,
                                  @"PREFIX foaf:  <http://xmlns.com/foaf/0.1/>
WITH <http://example/addresses>
DELETE { ?person ?property ?value } 
WHERE { ?person ?property ?value ; foaf:givenName 'Fred' } ");

            results    = _client.ExecuteQuery(storeName, "PREFIX foaf:  <http://xmlns.com/foaf/0.1/> SELECT ?p FROM <http://example/addresses> WHERE { ?p a foaf:Person }");
            resultsDoc = XDocument.Load(results);
            Assert.AreEqual(1, resultsDoc.SparqlResultRows().Count());
            var row = resultsDoc.SparqlResultRows().First();

            Assert.AreEqual(new Uri("http://example/william"), row.GetColumnValue("p"));
        }
예제 #4
0
        public SparqlUpdateModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider permissionsProvider)
        {
            this.RequiresBrightstarStorePermission(permissionsProvider, get:StorePermissions.SparqlUpdate, post:StorePermissions.SparqlUpdate);

            Get["/{storeName}/update"] = parameters =>
                {
                    var requestObject = this.Bind<SparqlUpdateRequestObject>();
                    ViewBag.Title = requestObject.StoreName + " - SPARQL Update";
                    return
                        Negotiate.WithAllowedMediaRange(Html)
                                 .WithModel(requestObject)
                                 .WithView("SparqlUpdate");
                };

            Post["/{storeName}/update"] = parameters =>
                {
                    var requestObject = this.Bind<SparqlUpdateRequestObject>();
                    ViewBag.Title = requestObject.StoreName + " - SPARQL Update";
                    if (SparqlRequest.Matches(Request.Headers.ContentType))
                    {
                        using (var reader = new StreamReader(Request.Body))
                        {
                            requestObject.Update = reader.ReadToEnd();
                        }
                    }

                    if (!parameters["storeName"].HasValue) return HttpStatusCode.BadRequest;
                    if (string.IsNullOrWhiteSpace(requestObject.Update)) return HttpStatusCode.BadRequest;

                    IJobInfo jobInfo = brightstarService.ExecuteUpdate(parameters["storeName"], requestObject.Update, true);
                    if (jobInfo.JobCompletedOk)
                    {
                        return jobInfo.MakeResponseObject(requestObject.StoreName);
                    }
                    return
                        Negotiate.WithStatusCode(HttpStatusCode.BadRequest)
                                 .WithModel(jobInfo.MakeResponseObject(requestObject.StoreName));
                };
        }
예제 #5
0
        private void ExecuteUpdate(string storeName, string updateExpression)
        {
            IJobInfo jobInfo = _client.ExecuteUpdate(storeName, updateExpression);

            TestHelper.AssertJobCompletesSuccessfully(_client, storeName, jobInfo);
        }
예제 #6
0
        public JobsModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider permissionsProvider)
        {
            this.RequiresBrightstarStorePermissionData(permissionsProvider);

            Get["/{storeName}/jobs"] = parameters =>
                {
                    var jobsRequestObject = this.Bind<JobsRequestModel>();
                    ViewBag.Title = jobsRequestObject.StoreName + " - Jobs";
                    if (jobsRequestObject == null || jobsRequestObject.StoreName == null)
                    {
                        return HttpStatusCode.BadRequest;
                    }
                    if (jobsRequestObject.Take <= 0) jobsRequestObject.Take = DefaultPageSize;
                    var jobs = brightstarService.GetJobInfo(jobsRequestObject.StoreName, jobsRequestObject.Skip,
                                                            jobsRequestObject.Take + 1);
                    return Negotiate.WithPagedList(jobsRequestObject,
                                                   jobs.Select(j=>j.MakeResponseObject(jobsRequestObject.StoreName)),
                                                   jobsRequestObject.Skip, jobsRequestObject.Take, DefaultPageSize,
                                                   "jobs");
                };

            Get["/{storeName}/jobs/{jobId}"] = parameters =>
                {
                    var request = this.Bind<JobRequestModel>();
                    if (request == null ||
                        request.StoreName == null ||
                        request.JobId == null)
                    {
                        return HttpStatusCode.BadRequest;
                    }
                    ViewBag.Title = request.StoreName + " - Job - " + request.JobId;
                    var job = brightstarService.GetJobInfo(request.StoreName, request.JobId);
                    if (job == null) return HttpStatusCode.NotFound;
                    var responseDto = job.MakeResponseObject(request.StoreName);
                    return responseDto;
                };

            Post["/{storeName}/jobs"] = parameters =>
                {
                    var jobRequestObject = this.Bind<JobRequestObject>();
                    ViewBag.Title = jobRequestObject.StoreName + "- Jobs";
                    // Validate
                    if (jobRequestObject == null) return HttpStatusCode.BadRequest;
                    if (String.IsNullOrWhiteSpace(jobRequestObject.JobType)) return HttpStatusCode.BadRequest;

                    var storeName = parameters["storeName"];
                    var label = jobRequestObject.Label;
                    try
                    {
                        IJobInfo queuedJobInfo;
                        switch (jobRequestObject.JobType.ToLowerInvariant())
                        {
                            case "consolidate":
                                AssertPermission(StorePermissions.Admin);
                                queuedJobInfo = brightstarService.ConsolidateStore(storeName, label);
                                break;

                            case "createsnapshot":
                                AssertPermission(StorePermissions.Admin);
                                PersistenceType persistenceType;

                                // Validate TargetStoreName and PersistenceType parameters
                                if (!jobRequestObject.JobParameters.ContainsKey("TargetStoreName") ||
                                    String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["TargetStoreName"]) ||
                                    !jobRequestObject.JobParameters.ContainsKey("PersistenceType") ||
                                    !Enum.TryParse(jobRequestObject.JobParameters["PersistenceType"],
                                                   out persistenceType))
                                {
                                    return HttpStatusCode.BadRequest;
                                }
                                // Extract optional commit point parameter
                                ICommitPointInfo commitPoint = null;
                                if (jobRequestObject.JobParameters.ContainsKey("CommitId"))
                                {
                                    ulong commitId;
                                    if (!UInt64.TryParse(jobRequestObject.JobParameters["CommitId"], out commitId))
                                    {
                                        return HttpStatusCode.BadRequest;
                                    }
                                    commitPoint = brightstarService.GetCommitPoint(storeName, commitId);
                                    if (commitPoint == null)
                                    {
                                        return HttpStatusCode.BadRequest;
                                    }
                                }

                                // Execute
                                queuedJobInfo = brightstarService.CreateSnapshot(
                                    storeName, jobRequestObject.JobParameters["TargetStoreName"],
                                    persistenceType, commitPoint, label);
                                break;

                            case "export":
                                AssertPermission(StorePermissions.Export);
                                if (!jobRequestObject.JobParameters.ContainsKey("FileName") ||
                                    String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["FileName"]))
                                {
                                    return HttpStatusCode.BadRequest;
                                }
                                RdfFormat format = jobRequestObject.JobParameters.ContainsKey("Format")
                                                       ? RdfFormat.GetResultsFormat(
                                                           jobRequestObject.JobParameters["Format"])
                                                       : RdfFormat.NQuads;

                                queuedJobInfo = brightstarService.StartExport(
                                    storeName,
                                    jobRequestObject.JobParameters["FileName"],
                                    jobRequestObject.JobParameters.ContainsKey("GraphUri") ? jobRequestObject.JobParameters["GraphUri"] : null,
                                    format,
                                    label);
                                break;

                            case "import":
                                AssertPermission(StorePermissions.TransactionUpdate);
                                if (!jobRequestObject.JobParameters.ContainsKey("FileName") ||
                                    String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["FileName"]))
                                {
                                    return HttpStatusCode.BadRequest;
                                }
                                RdfFormat importFormat = null;
                                if (jobRequestObject.JobParameters.ContainsKey("ImportFormat"))
                                {
                                    importFormat = RdfFormat.GetResultsFormat(jobRequestObject.JobParameters["ImportFormat"]);
                                    if (importFormat == null) return HttpStatusCode.BadRequest;
                                }
                                queuedJobInfo = brightstarService.StartImport(
                                    storeName,
                                    jobRequestObject.JobParameters["FileName"],
                                    jobRequestObject.JobParameters.ContainsKey("DefaultGraphUri") ? jobRequestObject.JobParameters["DefaultGraphUri"] : Constants.DefaultGraphUri,
                                    label, 
                                    importFormat);
                                break;

                            case "repeattransaction":
                                AssertPermission(StorePermissions.Admin);
                                if (!jobRequestObject.JobParameters.ContainsKey("JobId") ||
                                    String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["JobId"]))
                                {
                                    return HttpStatusCode.BadRequest;
                                }
                                Guid jobId;
                                if (!Guid.TryParse(jobRequestObject.JobParameters["JobId"], out jobId))
                                {
                                    return HttpStatusCode.BadRequest;
                                }
                                var transaction = brightstarService.GetTransaction(storeName, jobId);
                                if (transaction == null)
                                {
                                    return HttpStatusCode.BadRequest;
                                }
                                queuedJobInfo = brightstarService.ReExecuteTransaction(storeName, transaction, label);
                                break;

                            case "sparqlupdate":
                                AssertPermission(StorePermissions.SparqlUpdate);
                                if (!jobRequestObject.JobParameters.ContainsKey("UpdateExpression") ||
                                    String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["UpdateExpression"]))
                                {
                                    return HttpStatusCode.BadRequest;
                                }
                                queuedJobInfo = brightstarService.ExecuteUpdate(
                                    storeName,
                                    jobRequestObject.JobParameters["UpdateExpression"],
                                    false,
                                    label);
                                break;

                            case "transaction":
                                AssertPermission(StorePermissions.TransactionUpdate);
                                var preconditions = jobRequestObject.JobParameters.ContainsKey("Preconditions")
                                                        ? jobRequestObject.JobParameters["Preconditions"]
                                                        : null;
                                var nonexistence =
                                    jobRequestObject.JobParameters.ContainsKey("NonexistencePreconditions")
                                        ? jobRequestObject.JobParameters["NonexistencePreconditions"]
                                        : null;
                                var deletePatterns = jobRequestObject.JobParameters.ContainsKey("Deletes")
                                                         ? jobRequestObject.JobParameters["Deletes"]
                                                         : null;
                                var insertTriples = jobRequestObject.JobParameters.ContainsKey("Inserts")
                                                        ? jobRequestObject.JobParameters["Inserts"]
                                                        : null;
                                var defaultGraphUri =
                                    jobRequestObject.JobParameters.ContainsKey("DefaultGraphUri") &&
                                    !String.IsNullOrEmpty(jobRequestObject.JobParameters["DefaultGraphUri"])
                                        ? jobRequestObject.JobParameters["DefaultGraphUri"]
                                        : null;

                                queuedJobInfo = brightstarService.ExecuteTransaction(
                                    storeName, new UpdateTransactionData
                                        {
                                            ExistencePreconditions = preconditions,
                                            NonexistencePreconditions = nonexistence,
                                            DeletePatterns = deletePatterns,
                                            InsertData = insertTriples,
                                            DefaultGraphUri = defaultGraphUri
                                        },
                                    false,
                                    label);
                                break;

                            case "updatestats":
                                AssertPermission(StorePermissions.Admin);
                                queuedJobInfo = brightstarService.UpdateStatistics(storeName, label);
                                break;

                            default:
                                return HttpStatusCode.BadRequest;
                        }

                        var jobUri = (string) storeName + "/jobs/" + queuedJobInfo.JobId;
                        return Negotiate.WithModel(new JobResponseModel
                            {
                                JobId = queuedJobInfo.JobId,
                                Label = queuedJobInfo.Label,
                                StatusMessage = queuedJobInfo.StatusMessage,
                                JobStatus = queuedJobInfo.GetJobStatusString(),
                                ExceptionInfo = queuedJobInfo.ExceptionInfo,
                                QueuedTime = queuedJobInfo.QueuedTime,
                                StartTime = queuedJobInfo.StartTime,
                                EndTime = queuedJobInfo.EndTime
                            })
                            .WithHeader("Location", jobUri)
                            .WithStatusCode(HttpStatusCode.Created);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        return HttpStatusCode.Unauthorized;
                    }

                };
        }
예제 #7
0
        public GraphsModule(IBrightstarService brightstarService,
            AbstractStorePermissionsProvider storePermissionsProvider)
        {
            this.RequiresBrightstarStorePermission(storePermissionsProvider, get:StorePermissions.Read, put:StorePermissions.SparqlUpdate, post:StorePermissions.SparqlUpdate, delete:StorePermissions.SparqlUpdate);


            Get["/{storeName}/graphs"] = parameters =>
            {
                if (!brightstarService.DoesStoreExist(parameters["storeName"])) return HttpStatusCode.NotFound;
                Uri graphUri;
                if (Request.Query["default"] == null && Request.Query["graph"] == null)
                {
                    // Get with no default or graph parameter returns a list of graphs
                    // This is not part of the SPARQL 1.1 Graph Store protocol, but a useful extension
                    // The returned value is a SPARQL results set with a single variable named "graphUri"
                    // Acceptable media types are the supported SPARQL results set formats
                    return
                        Negotiate.WithModel(
                            new GraphListModel(brightstarService.ListNamedGraphs(parameters["storeName"])));
                }
                if (!TryGetGraphUri(out graphUri))
                {
                    // Will get here if the value of the graph parameter is parsed as a relative URI
                    return HttpStatusCode.BadRequest;
                }
                try
                {
                    // Return the serialized content of the graph
                    return SerializeGraph(brightstarService, parameters["storeName"], graphUri.ToString());
                }
                catch (BrightstarStoreNotModifiedException)
                {
                    return HttpStatusCode.NotModified;
                }
            };

            Put["/{storeName}/graphs"] = parameters =>
            {
                var storeParam = parameters["storeName"];
                var store = storeParam.Value as string;
                Uri graphUri;
                if (!brightstarService.DoesStoreExist(store)) return HttpStatusCode.NotFound;
                if (!TryGetGraphUri(out graphUri))
                {
                    return HttpStatusCode.BadRequest;
                }
                var graphUriStr = graphUri.ToString();
                bool isNewGraph = !graphUriStr.Equals(Constants.DefaultGraphUri) &&
                                  !(brightstarService.ListNamedGraphs(store).Any(x => x.Equals(graphUriStr)));

                try
                {
                    var rdfFormat = GetRequestBodyFormat();
                    if (rdfFormat == null) return HttpStatusCode.NotAcceptable;
                    var rdfPayload = ParseBody(rdfFormat);
                    var sparqlUpdate = graphUri.ToString().Equals(Constants.DefaultGraphUri) ?
                        String.Format(UpdateDefaultGraph, rdfPayload) :
                        String.Format(UpdateNamedGraph, graphUri, rdfPayload);

                    var job = brightstarService.ExecuteUpdate(store, sparqlUpdate, true, "Update Graph " + graphUri);
                    return job.JobCompletedOk
                        ? (isNewGraph ? HttpStatusCode.Created : HttpStatusCode.NoContent)
                        : HttpStatusCode.InternalServerError;
                }
                catch (RdfException)
                {
                    return HttpStatusCode.BadRequest;
                }
            };

            Post["/{storeName}/graphs"] = parameters =>
            {
                var storeParam = parameters["storeName"];
                var store = storeParam.Value as string;
                Uri graphUri;
                if (!brightstarService.DoesStoreExist(store)) return HttpStatusCode.NotFound;
                if (!TryGetGraphUri(out graphUri))
                {
                    return HttpStatusCode.BadRequest;
                }
                var graphUriStr = graphUri.ToString();
                var isNewGraph = !graphUriStr.Equals(Constants.DefaultGraphUri) &&
                                 !(brightstarService.ListNamedGraphs(store).Any(x => x.Equals(graphUriStr)));
                try
                {
                    var rdfFormat = GetRequestBodyFormat();
                    if (rdfFormat == null) return HttpStatusCode.NotAcceptable;
                    var rdfPayload = ParseBody(rdfFormat);
                    var sparqlUpdate = graphUri.ToString().Equals(Constants.DefaultGraphUri) ?
                        String.Format(MergeDefaultGraph, rdfPayload) :
                        String.Format(MergeNamedGraph, graphUri, rdfPayload);

                    var job = brightstarService.ExecuteUpdate(store, sparqlUpdate, true, "Update Graph " + graphUri);
                    return job.JobCompletedOk
                        ? (isNewGraph ? HttpStatusCode.Created : HttpStatusCode.NoContent)
                        : HttpStatusCode.InternalServerError;
                }
                catch (RdfException)
                {
                    return HttpStatusCode.BadRequest;
                }
            };

            Delete["{storeName}/graphs"] = parameters =>
            {
                Uri graphUri;
                string sparqlUpdate, jobName;
                var store = parameters["storeName"].Value as string;
                if (!brightstarService.DoesStoreExist(store)) return HttpStatusCode.NotFound;
                if (!TryGetGraphUri(out graphUri)) return HttpStatusCode.BadRequest;
                if (graphUri.ToString().Equals(Constants.DefaultGraphUri))
                {
                    // Clear the default graph
                    sparqlUpdate = DropDefaultGraph;
                    jobName = "Drop Default Graph";
                }
                else
                {
                    var graphId = graphUri.ToString();
                    if (!brightstarService.ListNamedGraphs(store).Contains(graphId))
                    {
                        return HttpStatusCode.NotFound;
                    }
                    // Clear the named graph
                    sparqlUpdate = String.Format(DropNamedGraph, graphId);
                    jobName = "Drop Graph " + graphId;
                }

                var job = brightstarService.ExecuteUpdate(store, sparqlUpdate, true, jobName);
                return job.JobCompletedOk
                    ? HttpStatusCode.NoContent
                    : HttpStatusCode.InternalServerError;
            };

        }
예제 #8
0
        public JobsModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider permissionsProvider)
        {
            this.RequiresBrightstarStorePermissionData(permissionsProvider);

            Get["/{storeName}/jobs"] = parameters =>
            {
                var jobsRequestObject = this.Bind <JobsRequestModel>();
                if (jobsRequestObject == null || jobsRequestObject.StoreName == null)
                {
                    return(HttpStatusCode.BadRequest);
                }
                if (jobsRequestObject.Take <= 0)
                {
                    jobsRequestObject.Take = DefaultPageSize;
                }
                var jobs = brightstarService.GetJobInfo(jobsRequestObject.StoreName, jobsRequestObject.Skip,
                                                        jobsRequestObject.Take + 1);
                return(Negotiate.WithPagedList(jobsRequestObject,
                                               jobs.Select(j => j.MakeResponseObject(jobsRequestObject.StoreName)),
                                               jobsRequestObject.Skip, jobsRequestObject.Take, DefaultPageSize,
                                               "jobs"));
            };

            Get["/{storeName}/jobs/{jobId}"] = parameters =>
            {
                var request = this.Bind <JobRequestModel>();
                if (request == null ||
                    request.StoreName == null ||
                    request.JobId == null)
                {
                    return(HttpStatusCode.BadRequest);
                }
                var job = brightstarService.GetJobInfo(request.StoreName, request.JobId);
                if (job == null)
                {
                    return(HttpStatusCode.NotFound);
                }
                var responseDto = job.MakeResponseObject(request.StoreName);
                return(responseDto);
            };

            Post["/{storeName}/jobs"] = parameters =>
            {
                var jobRequestObject = this.Bind <JobRequestObject>();

                // Validate
                if (jobRequestObject == null)
                {
                    return(HttpStatusCode.BadRequest);
                }
                if (String.IsNullOrWhiteSpace(jobRequestObject.JobType))
                {
                    return(HttpStatusCode.BadRequest);
                }

                var storeName = parameters["storeName"];
                var label     = jobRequestObject.Label;
                try
                {
                    IJobInfo queuedJobInfo;
                    switch (jobRequestObject.JobType.ToLowerInvariant())
                    {
                    case "consolidate":
                        AssertPermission(StorePermissions.Admin);
                        queuedJobInfo = brightstarService.ConsolidateStore(storeName, label);
                        break;

                    case "createsnapshot":
                        AssertPermission(StorePermissions.Admin);
                        PersistenceType persistenceType;

                        // Validate TargetStoreName and PersistenceType parameters
                        if (!jobRequestObject.JobParameters.ContainsKey("TargetStoreName") ||
                            String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["TargetStoreName"]) ||
                            !jobRequestObject.JobParameters.ContainsKey("PersistenceType") ||
                            !Enum.TryParse(jobRequestObject.JobParameters["PersistenceType"],
                                           out persistenceType))
                        {
                            return(HttpStatusCode.BadRequest);
                        }
                        // Extract optional commit point parameter
                        ICommitPointInfo commitPoint = null;
                        if (jobRequestObject.JobParameters.ContainsKey("CommitId"))
                        {
                            ulong commitId;
                            if (!UInt64.TryParse(jobRequestObject.JobParameters["CommitId"], out commitId))
                            {
                                return(HttpStatusCode.BadRequest);
                            }
                            commitPoint = brightstarService.GetCommitPoint(storeName, commitId);
                            if (commitPoint == null)
                            {
                                return(HttpStatusCode.BadRequest);
                            }
                        }

                        // Execute
                        queuedJobInfo = brightstarService.CreateSnapshot(
                            storeName, jobRequestObject.JobParameters["TargetStoreName"],
                            persistenceType, commitPoint, label);
                        break;

                    case "export":
                        AssertPermission(StorePermissions.Export);
                        if (!jobRequestObject.JobParameters.ContainsKey("FileName") ||
                            String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["FileName"]))
                        {
                            return(HttpStatusCode.BadRequest);
                        }
                        RdfFormat format = jobRequestObject.JobParameters.ContainsKey("Format")
                                                       ? RdfFormat.GetResultsFormat(
                            jobRequestObject.JobParameters["Format"])
                                                       : RdfFormat.NQuads;

                        queuedJobInfo = brightstarService.StartExport(
                            storeName,
                            jobRequestObject.JobParameters["FileName"],
                            jobRequestObject.JobParameters.ContainsKey("GraphUri") ? jobRequestObject.JobParameters["GraphUri"] : null,
                            format,
                            label);
                        break;

                    case "import":
                        AssertPermission(StorePermissions.TransactionUpdate);
                        if (!jobRequestObject.JobParameters.ContainsKey("FileName") ||
                            String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["FileName"]))
                        {
                            return(HttpStatusCode.BadRequest);
                        }
                        queuedJobInfo = brightstarService.StartImport(
                            storeName,
                            jobRequestObject.JobParameters["FileName"],
                            jobRequestObject.JobParameters.ContainsKey("DefaultGraphUri") ? jobRequestObject.JobParameters["DefaultGraphUri"] : Constants.DefaultGraphUri,
                            label);
                        break;

                    case "repeattransaction":
                        AssertPermission(StorePermissions.Admin);
                        if (!jobRequestObject.JobParameters.ContainsKey("JobId") ||
                            String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["JobId"]))
                        {
                            return(HttpStatusCode.BadRequest);
                        }
                        Guid jobId;
                        if (!Guid.TryParse(jobRequestObject.JobParameters["JobId"], out jobId))
                        {
                            return(HttpStatusCode.BadRequest);
                        }
                        var transaction = brightstarService.GetTransaction(storeName, jobId);
                        if (transaction == null)
                        {
                            return(HttpStatusCode.BadRequest);
                        }
                        queuedJobInfo = brightstarService.ReExecuteTransaction(storeName, transaction, label);
                        break;

                    case "sparqlupdate":
                        AssertPermission(StorePermissions.SparqlUpdate);
                        if (!jobRequestObject.JobParameters.ContainsKey("UpdateExpression") ||
                            String.IsNullOrWhiteSpace(jobRequestObject.JobParameters["UpdateExpression"]))
                        {
                            return(HttpStatusCode.BadRequest);
                        }
                        queuedJobInfo = brightstarService.ExecuteUpdate(
                            storeName,
                            jobRequestObject.JobParameters["UpdateExpression"],
                            false,
                            label);
                        break;

                    case "transaction":
                        AssertPermission(StorePermissions.TransactionUpdate);
                        var preconditions = jobRequestObject.JobParameters.ContainsKey("Preconditions")
                                                        ? jobRequestObject.JobParameters["Preconditions"]
                                                        : null;
                        var nonexistence =
                            jobRequestObject.JobParameters.ContainsKey("NonexistencePreconditions")
                                        ? jobRequestObject.JobParameters["NonexistencePreconditions"]
                                        : null;
                        var deletePatterns = jobRequestObject.JobParameters.ContainsKey("Deletes")
                                                         ? jobRequestObject.JobParameters["Deletes"]
                                                         : null;
                        var insertTriples = jobRequestObject.JobParameters.ContainsKey("Inserts")
                                                        ? jobRequestObject.JobParameters["Inserts"]
                                                        : null;
                        var defaultGraphUri =
                            jobRequestObject.JobParameters.ContainsKey("DefaultGraphUri") &&
                            !String.IsNullOrEmpty(jobRequestObject.JobParameters["DefaultGraphUri"])
                                        ? jobRequestObject.JobParameters["DefaultGraphUri"]
                                        : null;

                        queuedJobInfo = brightstarService.ExecuteTransaction(
                            storeName, new UpdateTransactionData
                        {
                            ExistencePreconditions    = preconditions,
                            NonexistencePreconditions = nonexistence,
                            DeletePatterns            = deletePatterns,
                            InsertData      = insertTriples,
                            DefaultGraphUri = defaultGraphUri
                        },
                            false,
                            label);
                        break;

                    case "updatestats":
                        AssertPermission(StorePermissions.Admin);
                        queuedJobInfo = brightstarService.UpdateStatistics(storeName, label);
                        break;

                    default:
                        return(HttpStatusCode.BadRequest);
                    }

                    var jobUri = (string)storeName + "/jobs/" + queuedJobInfo.JobId;
                    return(Negotiate.WithModel(new JobResponseModel
                    {
                        JobId = queuedJobInfo.JobId,
                        Label = queuedJobInfo.Label,
                        StatusMessage = queuedJobInfo.StatusMessage,
                        JobStatus = queuedJobInfo.GetJobStatusString(),
                        ExceptionInfo = queuedJobInfo.ExceptionInfo,
                        QueuedTime = queuedJobInfo.QueuedTime,
                        StartTime = queuedJobInfo.StartTime,
                        EndTime = queuedJobInfo.EndTime
                    })
                           .WithHeader("Location", jobUri)
                           .WithStatusCode(HttpStatusCode.Created));
                }
                catch (UnauthorizedAccessException)
                {
                    return(HttpStatusCode.Unauthorized);
                }
            };
        }
예제 #9
0
        public GraphsModule(IBrightstarService brightstarService,
                            AbstractStorePermissionsProvider storePermissionsProvider)
        {
            this.RequiresBrightstarStorePermission(storePermissionsProvider, get: StorePermissions.Read, put: StorePermissions.SparqlUpdate, post: StorePermissions.SparqlUpdate, delete: StorePermissions.SparqlUpdate);


            Get["/{storeName}/graphs"] = parameters =>
            {
                if (!brightstarService.DoesStoreExist(parameters["storeName"]))
                {
                    return(HttpStatusCode.NotFound);
                }
                Uri graphUri;
                if (Request.Query["default"] == null && Request.Query["graph"] == null)
                {
                    // Get with no default or graph parameter returns a list of graphs
                    // This is not part of the SPARQL 1.1 Graph Store protocol, but a useful extension
                    // The returned value is a SPARQL results set with a single variable named "graphUri"
                    // Acceptable media types are the supported SPARQL results set formats
                    return
                        (Negotiate.WithModel(
                             new GraphListModel(brightstarService.ListNamedGraphs(parameters["storeName"]))));
                }
                if (!TryGetGraphUri(out graphUri))
                {
                    // Will get here if the value of the graph parameter is parsed as a relative URI
                    return(HttpStatusCode.BadRequest);
                }
                try
                {
                    // Return the serialized content of the graph
                    return(SerializeGraph(brightstarService, parameters["storeName"], graphUri.ToString()));
                }
                catch (BrightstarStoreNotModifiedException)
                {
                    return(HttpStatusCode.NotModified);
                }
            };

            Put["/{storeName}/graphs"] = parameters =>
            {
                var storeParam = parameters["storeName"];
                var store      = storeParam.Value as string;
                Uri graphUri;
                if (!brightstarService.DoesStoreExist(store))
                {
                    return(HttpStatusCode.NotFound);
                }
                if (!TryGetGraphUri(out graphUri))
                {
                    return(HttpStatusCode.BadRequest);
                }
                var  graphUriStr = graphUri.ToString();
                bool isNewGraph  = !graphUriStr.Equals(Constants.DefaultGraphUri) &&
                                   !(brightstarService.ListNamedGraphs(store).Any(x => x.Equals(graphUriStr)));

                try
                {
                    var rdfFormat = GetRequestBodyFormat();
                    if (rdfFormat == null)
                    {
                        return(HttpStatusCode.NotAcceptable);
                    }
                    var rdfPayload   = ParseBody(rdfFormat);
                    var sparqlUpdate = graphUri.ToString().Equals(Constants.DefaultGraphUri) ?
                                       String.Format(UpdateDefaultGraph, rdfPayload) :
                                       String.Format(UpdateNamedGraph, graphUri, rdfPayload);

                    var job = brightstarService.ExecuteUpdate(store, sparqlUpdate, true, "Update Graph " + graphUri);
                    return(job.JobCompletedOk
                        ? (isNewGraph ? HttpStatusCode.Created : HttpStatusCode.NoContent)
                        : HttpStatusCode.InternalServerError);
                }
                catch (RdfException)
                {
                    return(HttpStatusCode.BadRequest);
                }
            };

            Post["/{storeName}/graphs"] = parameters =>
            {
                var storeParam = parameters["storeName"];
                var store      = storeParam.Value as string;
                Uri graphUri;
                if (!brightstarService.DoesStoreExist(store))
                {
                    return(HttpStatusCode.NotFound);
                }
                if (!TryGetGraphUri(out graphUri))
                {
                    return(HttpStatusCode.BadRequest);
                }
                var graphUriStr = graphUri.ToString();
                var isNewGraph  = !graphUriStr.Equals(Constants.DefaultGraphUri) &&
                                  !(brightstarService.ListNamedGraphs(store).Any(x => x.Equals(graphUriStr)));
                try
                {
                    var rdfFormat = GetRequestBodyFormat();
                    if (rdfFormat == null)
                    {
                        return(HttpStatusCode.NotAcceptable);
                    }
                    var rdfPayload   = ParseBody(rdfFormat);
                    var sparqlUpdate = graphUri.ToString().Equals(Constants.DefaultGraphUri) ?
                                       String.Format(MergeDefaultGraph, rdfPayload) :
                                       String.Format(MergeNamedGraph, graphUri, rdfPayload);

                    var job = brightstarService.ExecuteUpdate(store, sparqlUpdate, true, "Update Graph " + graphUri);
                    return(job.JobCompletedOk
                        ? (isNewGraph ? HttpStatusCode.Created : HttpStatusCode.NoContent)
                        : HttpStatusCode.InternalServerError);
                }
                catch (RdfException)
                {
                    return(HttpStatusCode.BadRequest);
                }
            };

            Delete["{storeName}/graphs"] = parameters =>
            {
                Uri    graphUri;
                string sparqlUpdate, jobName;
                var    store = parameters["storeName"].Value as string;
                if (!brightstarService.DoesStoreExist(store))
                {
                    return(HttpStatusCode.NotFound);
                }
                if (!TryGetGraphUri(out graphUri))
                {
                    return(HttpStatusCode.BadRequest);
                }
                if (graphUri.ToString().Equals(Constants.DefaultGraphUri))
                {
                    // Clear the default graph
                    sparqlUpdate = DropDefaultGraph;
                    jobName      = "Drop Default Graph";
                }
                else
                {
                    var graphId = graphUri.ToString();
                    if (!brightstarService.ListNamedGraphs(store).Contains(graphId))
                    {
                        return(HttpStatusCode.NotFound);
                    }
                    // Clear the named graph
                    sparqlUpdate = String.Format(DropNamedGraph, graphId);
                    jobName      = "Drop Graph " + graphId;
                }

                var job = brightstarService.ExecuteUpdate(store, sparqlUpdate, true, jobName);
                return(job.JobCompletedOk
                    ? HttpStatusCode.NoContent
                    : HttpStatusCode.InternalServerError);
            };
        }