예제 #1
0
        public SparqlModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider permissionsProvider)
        {
            this.RequiresBrightstarStorePermission(permissionsProvider, get:StorePermissions.Read, post:StorePermissions.Read);
            _brightstar = brightstarService;

            Get["/{storeName}/sparql"] = parameters =>
                {
                    try
                    {
                        var requestObject = BindSparqlRequestObject();
                        return ProcessQuery(parameters["storeName"], requestObject);
                    }
                    catch (RdfParseException)
                    {
                        return HttpStatusCode.BadRequest;
                    }
                };
            Post["/{storeName}/sparql"] = parameters =>
                {
                    try
                    {
                        var requestObject = BindSparqlRequestObject();
                        return ProcessQuery(parameters["storeName"], requestObject);
                    }
                    catch (RdfParseException)
                    {
                        return HttpStatusCode.BadRequest;
                    }
                };
            Get["/{storeName}/commits/{commitId}/sparql"] = ProcessCommitPointQuery;
            Post["/{storeName}/commits/{commitId}/sparql"] = ProcessCommitPointQuery;
        }
        private static Response RequiresAuthorization(NancyContext context, AbstractStorePermissionsProvider permissionsProvider, StorePermissions get, StorePermissions post, StorePermissions delete)
        {
            var permissionRequired = StorePermissions.None;
            
            switch (context.Request.Method.ToUpperInvariant())
            {
                case "GET":
                case "HEAD":
                    permissionRequired = get;
                    break;

                case "POST":
                    permissionRequired = post;
                    break;

                case "DELETE":
                    permissionRequired = delete;
                    break;
            }

            if (permissionRequired == StorePermissions.None) return HttpStatusCode.Unauthorized;

            var storeName = context.Parameters["storeName"];
            if (!permissionsProvider.HasStorePermission(context.CurrentUser, storeName, permissionRequired))
            {
                return HttpStatusCode.Unauthorized;
            }
            return null;
        }
예제 #3
0
        public TransactionsModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider storePermissionsProvider)
        {
            this.RequiresBrightstarStorePermission(storePermissionsProvider, get:StorePermissions.ViewHistory);

            Get["/{storeName}/transactions"] = parameters =>
                {
                    var transactionsRequest = this.Bind<TransactionsRequestObject>();
                    ViewBag.Title = transactionsRequest.StoreName + " - Transactions";
                    if (transactionsRequest.Take <= 0) transactionsRequest.Take = DefaultPageSize;
                    var transactions = brightstarService.GetTransactions(transactionsRequest.StoreName,
                                                                                 transactionsRequest.Skip,
                                                                                 transactionsRequest.Take + 1);
                    return Negotiate.WithPagedList(transactionsRequest,
                                                   transactions.Select(MakeResponseObject),
                                                   transactionsRequest.Skip, transactionsRequest.Take, DefaultPageSize,
                                                   "transactions");
                };

            Get["/{storeName}/transactions/byjob/{jobId}"] = parameters =>
                {
                    Guid jobId;
                    if (!Guid.TryParse(parameters["jobId"], out jobId))
                    {
                        return HttpStatusCode.NotFound;
                    }
                    var storeName = parameters["storeName"];
                    ViewBag.Title = storeName + " - Transaction - Job " + jobId;
                    var txn = brightstarService.GetTransaction(parameters["storeName"], jobId);
                    return txn == null ? HttpStatusCode.NotFound : MakeResponseObject(txn);
                };
        }
예제 #4
0
        public StoreModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider storePermissionsProvider)
        {
            this.RequiresBrightstarStorePermission(storePermissionsProvider, get:StorePermissions.Read, delete:StorePermissions.Admin);

            Get["/{storeName}"] = parameters =>
            {
                var storeName = parameters["storeName"];
                ViewBag.Title = storeName;

                if (!brightstarService.DoesStoreExist(storeName)) return HttpStatusCode.NotFound;
                if (Request.Method.ToUpperInvariant() == "HEAD")
                {
                    IEnumerable < ICommitPointInfo > commitPoints = brightstarService.GetCommitPoints(storeName, 0, 1);
                    var commit = commitPoints.First();
                    return
                        Negotiate.WithHeader("Last-Modified", commit.CommitTime.ToUniversalTime().ToString("r"))
                            .WithStatusCode(HttpStatusCode.OK)
                            .WithModel(new StoreResponseModel(parameters["storeName"]));
                }
                return new StoreResponseModel(parameters["storeName"]);
            };

            Delete["/{storeName}"] = parameters =>
                {
                    var storeName = parameters["storeName"];
                    ViewBag.Title = "Deleted - " + storeName;
                    if (brightstarService.DoesStoreExist(storeName))
                    {
                        brightstarService.DeleteStore(storeName);
                    }
                    return Negotiate.WithMediaRangeModel(new MediaRange("text/html"), 
                                                         new StoreDeletedModel {StoreName = storeName});
                };
        }
 private static Response RequiresPermissionData(NancyContext context,
                                                AbstractStorePermissionsProvider permissionsProvider)
 {
     var storeName = context.Parameters["storeName"];
     context.ViewBag["BrightstarStorePermissions"] = permissionsProvider.GetStorePermissions(context.CurrentUser,
                                                                                            storeName);
     return null;
 }
예제 #6
0
 public FakeNancyBootstrapper(IBrightstarService brightstarService,
                              AbstractStorePermissionsProvider storePermissionsProvider,
     AbstractSystemPermissionsProvider systemPermissionsProvider)
 {
     _brightstarService = brightstarService;
     _storePermissionsProvider = storePermissionsProvider;
     _systemPermissionsProvider = systemPermissionsProvider;
 }
        public BrightstarBootstrapper()
        {
            var config = ConfigurationManager.GetSection("brightstarService") as BrightstarServiceConfiguration;
            if (config == null) throw new ConfigurationErrorsException(Strings.NoServiceConfiguration);

            _brightstarService = BrightstarService.GetClient(config.ConnectionString);
            _storePermissionsProvider = config.StorePermissionsProvider;
            _systemPermissionsProvider = config.SystemPermissionsProvider;
        }
 public LatestStatisticsModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider storePermissionsProvider)
 {
     this.RequiresBrightstarStorePermission(storePermissionsProvider, get:StorePermissions.Read);
     Get["/{storeName}/statistics/latest"] = parameters =>
         {
             var latest = brightstarService.GetStatistics(parameters["storeName"]);
             if (latest == null) return HttpStatusCode.NotFound;
             return MakeResponseModel(latest);
         };
 }
 /// <summary>
 /// Creates a new bootstrapper with store and system access goverened by the specified providers.
 /// </summary>
 /// <param name="brightstarService">The connection to the BrightstarDB stores</param>
 /// <param name="storePermissionsProvider">The store permissions provider to be used by the service</param>
 /// <param name="systemPermissionsProvider">The system permissions provider to be used by the service</param>
 /// <param name="rootPath">The path to the directory containing the service Views and assets folder</param>
 public BrightstarBootstrapper(IBrightstarService brightstarService,
                               AbstractStorePermissionsProvider storePermissionsProvider,
                               AbstractSystemPermissionsProvider systemPermissionsProvider,
     string rootPath = null)
 {
     _brightstarService = brightstarService;
     _storePermissionsProvider = storePermissionsProvider;
     _systemPermissionsProvider = systemPermissionsProvider;
     _rootPathProvider = (rootPath == null ? new DefaultRootPathProvider() : new FixedRootPathProvider(rootPath) as IRootPathProvider);
     //_rootPathProvider = new FixedRootPathProvider(rootPath);
 }
예제 #10
0
        /// <summary>
        /// Create a new bootstrapper that initializes itself from the brightstarService section
        /// of the application (or web) configuration file.
        /// </summary>
        /// <exception cref="ConfigurationErrorsException">Raised if the brightstarService configuration
        /// section does not exist in the application configuration file, or if the configuration is
        /// invalid.</exception>
        public BrightstarBootstrapper()
        {
            var config = ConfigurationManager.GetSection("brightstarService") as BrightstarServiceConfiguration;
            if (config == null) throw new ConfigurationErrorsException(Strings.NoServiceConfiguration);

            _brightstarService = BrightstarService.GetClient(config.ConnectionString);
            _storePermissionsProvider = config.StorePermissionsProvider ??
                                        new FallbackStorePermissionsProvider(StorePermissions.All);
            _systemPermissionsProvider = config.SystemPermissionsProvider ??
                                         new FallbackSystemPermissionsProvider(SystemPermissions.All);
            _authenticationProviders = config.AuthenticationProviders ??
                                       new Collection<IAuthenticationProvider> {new NullAuthenticationProvider()};
        }
예제 #11
0
        public CommitPointsModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider permissionsProvider)
        {
            this.RequiresBrightstarStorePermission(permissionsProvider, get:StorePermissions.ViewHistory, post:StorePermissions.Admin);

            Get["/{storeName}/commits"] = parameters =>
                {
                    int skip = Request.Query["skip"].TryParse<int>(0);
                    int take = Request.Query["take"].TryParse<int>(DefaultPageSize);
                    DateTime timestamp = Request.Query["timestamp"].TryParse<DateTime>();
                    DateTime earliest = Request.Query["earliest"].TryParse<DateTime>();
                    DateTime latest = Request.Query["latest"].TryParse<DateTime>();

                    var request = this.Bind<CommitPointsRequestModel>();
                    ViewBag.Title = request.StoreName + " - Commit History";
                    
                    if (timestamp != default(DateTime))
                    {
                        // Request for a single commit point
                        var commitPoint = brightstarService.GetCommitPoint(parameters["storeName"], timestamp);
                        return commitPoint == null ? HttpStatusCode.NotFound : MakeResponseObject(commitPoint);
                    }
                    if (earliest != default(DateTime) && latest != default(DateTime))
                    {
                        IEnumerable<ICommitPointInfo> results =
                            brightstarService.GetCommitPoints(parameters["storeName"], latest, earliest, skip, take + 1);
                        var resourceUri = String.Format("commits?latest={0}&earliest={1}", latest.ToString("s"), earliest.ToString("s"));
                        return Negotiate.WithPagedList(request, results.Select(MakeResponseObject), skip, take, DefaultPageSize, resourceUri);
                    }
                    IEnumerable<ICommitPointInfo> commitPointInfos = brightstarService.GetCommitPoints(parameters["storeName"], skip, take + 1);
                    return Negotiate.WithPagedList(request, commitPointInfos.Select(MakeResponseObject), skip, take, DefaultPageSize, "commits");
                };

            Post["/{storeName}/commits"] = parameters =>
                {
                    var commitPoint = this.Bind<CommitPointResponseModel>();
                    if (commitPoint == null ||
                        String.IsNullOrEmpty(commitPoint.StoreName) ||
                        !commitPoint.StoreName.Equals(parameters["storeName"]))
                    {
                        return HttpStatusCode.BadRequest;
                    }

                    var commitPointInfo = brightstarService.GetCommitPoint(parameters["storeName"], commitPoint.Id);
                    if (commitPointInfo == null) return HttpStatusCode.BadRequest;

                    brightstarService.RevertToCommitPoint(parameters["storeName"], commitPointInfo);
                    return HttpStatusCode.OK;
                };
        }
예제 #12
0
        public StatisticsModule(IBrightstarService brightstarService, AbstractStorePermissionsProvider storePermissionsProvider)
        {
            this.RequiresBrightstarStorePermission(storePermissionsProvider, get:StorePermissions.ViewHistory);
            Get["/{storeName}/statistics"] = parameters =>
                {
                    var request = this.Bind<StatisticsRequestObject>();
                    var resourceUri = "statistics" + CreateQueryString(request);

                    // Set defaults
                    if (!request.Latest.HasValue) {  request.Latest = DateTime.MaxValue; }
                    if (!request.Earliest.HasValue) { request.Earliest = DateTime.MinValue; }

                    // Execute
                    var stats = brightstarService.GetStatistics(
                        request.StoreName, request.Latest.Value, request.Earliest.Value,
                        request.Skip, DefaultPageSize + 1);

                    return Negotiate.WithPagedList(request, stats.Select(MakeResponseModel), request.Skip, DefaultPageSize,
                                                   DefaultPageSize, resourceUri);
                };
        }
예제 #13
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));
                };
        }
예제 #14
0
        /// <summary>
        /// Creates a new bootstrapper with store and system access goverened by the specified providers.
        /// </summary>
        /// <param name="brightstarService">The connection to the BrightstarDB stores</param>
        /// <param name="authenticationProviders">An enumeration of the authentication providers to be used by the service</param>
        /// <param name="storePermissionsProvider">The store permissions provider to be used by the service</param>
        /// <param name="systemPermissionsProvider">The system permissions provider to be used by the service</param>
        /// <param name="rootPath">The path to the directory containing the service Views and assets folder</param>
        /// <exception cref="ArgumentNullException">Raised if any of the arguments to the method other than <paramref name="rootPath"/> are Null.</exception>
        public BrightstarBootstrapper(IBrightstarService brightstarService,
                                      IEnumerable<IAuthenticationProvider> authenticationProviders,
                                      AbstractStorePermissionsProvider storePermissionsProvider,
                                      AbstractSystemPermissionsProvider systemPermissionsProvider,
                                      string rootPath = null)
        {
            if (brightstarService == null) throw new ArgumentNullException("brightstarService");
            if (authenticationProviders == null) throw new ArgumentNullException("authenticationProviders");
            if (storePermissionsProvider == null) throw new ArgumentNullException("storePermissionsProvider");
            if (systemPermissionsProvider == null) throw new ArgumentNullException("systemPermissionsProvider");

            _brightstarService = brightstarService;
            _authenticationProviders = authenticationProviders;
            _storePermissionsProvider = storePermissionsProvider;
            _systemPermissionsProvider = systemPermissionsProvider;
            _rootPathProvider = (rootPath == null
                                     ? new DefaultRootPathProvider()
                                     : new FixedRootPathProvider(rootPath) as IRootPathProvider);
        }
예제 #15
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;
                    }

                };
        }
예제 #16
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;
            };

        }
예제 #17
0
 public CombiningStorePermissionsProvider(AbstractStorePermissionsProvider first, AbstractStorePermissionsProvider second)
 {
     _first  = first;
     _second = second;
 }
 /// <summary>
 /// Extension method to request that the NancyContext ViewBag gets populate
 /// with the store permissions during the Before module pipeline.
 /// </summary>
 /// <param name="module">The module requesting permission data</param>
 public static void RequiresBrightstarStorePermissionData(this NancyModule module, AbstractStorePermissionsProvider permissionsProvider)
 {
     module.Before.AddItemToEndOfPipeline(ctx=>RequiresPermissionData(ctx,permissionsProvider));
 }
 public static void RequiresBrightstarStorePermission(this NancyModule module,
     AbstractStorePermissionsProvider permissionsProvider, StorePermissions get = StorePermissions.None, StorePermissions post = StorePermissions.None, StorePermissions delete = StorePermissions.None)
 {
     module.Before.AddItemToEndOfPipeline(ctx => RequiresAuthorization(ctx, permissionsProvider, get, post, delete));
 }
 public CombiningStorePermissionsProvider(AbstractStorePermissionsProvider first, AbstractStorePermissionsProvider second)
 {
     _first = first;
     _second = second;
 }
예제 #21
0
        /// <summary>
        /// Creates a new bootstrapper with store access governed by the specified provider and default
        /// system access permissions (full control to authenticated users, no control to anonymous users)
        /// </summary>
        /// <param name="brightstarService"></param>
        /// <param name="authenticationProviders">An enumeration of the authentication providers to be used by the service</param>
        /// <param name="storePermissionsProvider"></param>
        public BrightstarBootstrapper(IBrightstarService brightstarService,
            IEnumerable<IAuthenticationProvider> authenticationProviders, AbstractStorePermissionsProvider storePermissionsProvider)
            : this(brightstarService, authenticationProviders, storePermissionsProvider, new FallbackSystemPermissionsProvider(SystemPermissions.All))
        {

        }
        /// <summary>
        /// Creates a new bootstrapper with store access governed by the specified provider and default
        /// system access permissions (full control to authenticated users, no control to anonymous users)
        /// </summary>
        /// <param name="brightstarService"></param>
        /// <param name="storePermissionsProvider"></param>
        public BrightstarBootstrapper(IBrightstarService brightstarService,
                                      AbstractStorePermissionsProvider storePermissionsProvider)
            : this(brightstarService, storePermissionsProvider, new FallbackSystemPermissionsProvider(SystemPermissions.All))
        {

        }