本文整理汇总了C#中ICouchbaseListenerContext.CreateResponse方法的典型用法代码示例。如果您正苦于以下问题:C# ICouchbaseListenerContext.CreateResponse方法的具体用法?C# ICouchbaseListenerContext.CreateResponse怎么用?C# ICouchbaseListenerContext.CreateResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ICouchbaseListenerContext
的用法示例。
在下文中一共展示了ICouchbaseListenerContext.CreateResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetConfiguration
/// <summary>
/// Gets information about the specified database.
/// </summary>
/// <returns>The response state for further HTTP processing</returns>
/// <param name="context">The context of the Couchbase Lite HTTP request</param>
/// <remarks>
/// http://docs.couchdb.org/en/latest/api/database/common.html#get--db
/// </remarks>
public static ICouchbaseResponseState GetConfiguration(ICouchbaseListenerContext context)
{
return PerformLogicWithDatabase(context, true, db =>
{
int numDocs = db.GetDocumentCount();
long updateSequence = db.GetLastSequenceNumber();
if (numDocs < 0 || updateSequence < 0) {
return context.CreateResponse(StatusCode.DbError);
}
var response = context.CreateResponse();
response.JsonBody = new Body(new Dictionary<string, object> {
{ "db_name", db.Name },
{ "db_uuid", db.PublicUUID() },
{ "doc_count", numDocs },
{ "update_seq", updateSequence },
{ "committed_update_seq", updateSequence },
{ "purge_seq", 0 }, //TODO: Implement
{ "disk_size", db.GetTotalDataSize() },
{ "start_time", db.StartTime * 1000 },
{ "revs_limit", db.GetMaxRevTreeDepth() }
});
return response;
}).AsDefaultState();
}
示例2: RegisterFacebookToken
/// <summary>
/// Verifies and registers a facebook token for use in replication authentication
/// </summary>
/// <returns>The response state for further HTTP processing</returns>
/// <param name="context">The context of the Couchbase Lite HTTP request</param>
public static ICouchbaseResponseState RegisterFacebookToken(ICouchbaseListenerContext context)
{
var response = context.CreateResponse();
var body = context.BodyAs<Dictionary<string, object>>();
string email = body.GetCast<string>("email");
string remoteUrl = body.GetCast<string>("remote_url");
string accessToken = body.GetCast<string>("access_token");
if (email != null && remoteUrl != null && accessToken != null) {
Uri siteUrl;
if (!Uri.TryCreate(remoteUrl, UriKind.Absolute, out siteUrl)) {
response.InternalStatus = StatusCode.BadParam;
response.JsonBody = new Body(new Dictionary<string, object> {
{ "error", "invalid remote_url" }
});
} else if (!FacebookAuthorizer.RegisterAccessToken(accessToken, email, siteUrl)) {
response.InternalStatus = StatusCode.BadParam;
response.JsonBody = new Body(new Dictionary<string, object> {
{ "error", "invalid access_token" }
});
} else {
response.JsonBody = new Body(new Dictionary<string, object> {
{ "ok", "registered" },
{ "email", email }
});
}
} else {
response.InternalStatus = StatusCode.BadParam;
response.JsonBody = new Body(new Dictionary<string, object> {
{ "error", "required fields: access_token, email, remote_url" }
});
}
return response.AsDefaultState();
}
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:40,代码来源:AuthenticationMethods.cs
示例3: QueryDesignDocument
// Performs the actual query logic on a design document
private static CouchbaseLiteResponse QueryDesignDocument(ICouchbaseListenerContext context, IList<object> keys)
{
return DatabaseMethods.PerformLogicWithDatabase(context, true, db =>
{
var view = db.GetView(String.Format("{0}/{1}", context.DesignDocName, context.ViewName));
var status = view.CompileFromDesignDoc();
if(status.IsError) {
return context.CreateResponse(status.Code);
}
var options = context.QueryOptions;
if(options == null) {
return context.CreateResponse(StatusCode.BadRequest);
}
if(keys != null) {
options.Keys = keys;
}
if(options.Stale == IndexUpdateMode.Before || view.LastSequenceIndexed <= 0) {
view.UpdateIndex();
} else if(options.Stale == IndexUpdateMode.After && view.LastSequenceIndexed < db.LastSequenceNumber) {
db.RunAsync(_ => view.UpdateIndex());
}
// Check for conditional GET and set response Etag header:
if(keys == null) {
long eTag = options.IncludeDocs ? db.LastSequenceNumber : view.LastSequenceIndexed;
if(context.CacheWithEtag(eTag.ToString())) {
return context.CreateResponse(StatusCode.NotModified);
}
}
return DatabaseMethods.QueryView(context, db, view, options);
});
}
示例4: Greeting
/// <summary>
/// Returns a JSON structure containing information about the server, including a welcome message and the version of the server.
/// </summary>
/// <returns>The response state for further HTTP processing</returns>
/// <param name="context">The context of the Couchbase Lite HTTP request</param>
/// <remarks>
/// http://docs.couchdb.org/en/latest/api/server/common.html#get--
/// <remarks>
public static ICouchbaseResponseState Greeting(ICouchbaseListenerContext context)
{
var info = new Dictionary<string, object> {
{ "couchdb", "Welcome" }, //for compatibility
{ "CouchbaseLite", "Welcome" },
{ "version", Manager.VersionString },
{ "vendor", new Dictionary<string, object> {
{ "name", "Couchbase Lite (C#)" },
{ "version", Manager.VersionString }
}
}
};
var body = new Body(info);
var couchResponse = context.CreateResponse();
couchResponse.JsonBody = body;
return couchResponse.AsDefaultState();
}
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:26,代码来源:ServerMethods.cs
示例5: RegisterPersonaToken
/// <summary>
/// Verifies and registers a persona token for use in replication authentication
/// </summary>
/// <returns>The response state for further HTTP processing</returns>
/// <param name="context">The context of the Couchbase Lite HTTP request</param>
public static ICouchbaseResponseState RegisterPersonaToken(ICouchbaseListenerContext context)
{
var response = context.CreateResponse();
var body = context.BodyAs<Dictionary<string, object>>();
string email = PersonaAuthorizer.RegisterAssertion(body.GetCast<string>("assertion"));
if (email != null) {
response.JsonBody = new Body(new Dictionary<string, object> {
{ "ok", "registered" },
{ "email", email }
});
} else {
response.InternalStatus = StatusCode.BadParam;
response.JsonBody = new Body(new Dictionary<string, object> {
{ "error", "invalid assertion" }
});
}
return response.AsDefaultState();
}
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:25,代码来源:AuthenticationMethods.cs
示例6: DoAllDocs
//Do an all document request on the database (i.e. fetch all docs given some options)
private static CouchbaseLiteResponse DoAllDocs(ICouchbaseListenerContext context, Database db, QueryOptions options)
{
var iterator = db.GetAllDocs(options);
if (iterator == null) {
return context.CreateResponse(StatusCode.BadJson);
}
var response = context.CreateResponse();
var result = (from row in iterator
select row.AsJSONDictionary()).ToList();
response.JsonBody = new Body(new NonNullDictionary<string, object> {
{ "rows", result },
{ "total_rows", result.Count },
{ "offset", options.Skip },
{ "update_seq", options.UpdateSeq ? (object)db.GetLastSequenceNumber() : null }
});
return response;
}
示例7: QueryView
/// <summary>
/// Queries the specified view using the specified options
/// </summary>
/// <returns>The HTTP response containing the results of the query</returns>
/// <param name="context">The request context</param>
/// <param name="db">The database to run the query in</param>
/// <param name="view">The view to query</param>
/// <param name="options">The options to apply to the query</param>
public static CouchbaseLiteResponse QueryView(ICouchbaseListenerContext context, Database db, View view, QueryOptions options)
{
var result = view.QueryWithOptions(options);
object updateSeq = options.UpdateSeq ? (object)view.LastSequenceIndexed : null;
var mappedResult = new List<object>();
foreach (var row in result) {
row.Database = db;
var dict = row.AsJSONDictionary();
if (context.ContentOptions != DocumentContentOptions.None) {
var doc = dict.Get("doc").AsDictionary<string, object>();
if (doc != null) {
// Add content options:
RevisionInternal rev = new RevisionInternal(doc);
var status = new Status();
rev = DocumentMethods.ApplyOptions(context.ContentOptions, rev, context, db, status);
if (rev != null) {
dict["doc"] = rev.GetProperties();
}
}
}
mappedResult.Add(dict);
}
var body = new Body(new NonNullDictionary<string, object> {
{ "rows", mappedResult },
{ "total_rows", view.TotalRows },
{ "offset", options.Skip },
{ "update_seq", updateSeq }
});
var retVal = context.CreateResponse();
retVal.JsonBody = body;
return retVal;
}
示例8: Purge
/// <summary>
/// A database purge permanently removes the references to deleted documents from the database.
/// </summary>
/// <returns>The response state for further HTTP processing</returns>
/// <param name="context">The context of the Couchbase Lite HTTP request</param>
/// <remarks>
/// http://docs.couchdb.org/en/latest/api/database/misc.html#post--db-_purge
/// </remarks>
public static ICouchbaseResponseState Purge(ICouchbaseListenerContext context)
{
return PerformLogicWithDatabase(context, true, db =>
{
var body = context.BodyAs<Dictionary<string, IList<string>>>();
if(body == null) {
return context.CreateResponse(StatusCode.BadJson);
}
var purgedRevisions = db.Storage.PurgeRevisions(body);
if(purgedRevisions == null) {
return context.CreateResponse(StatusCode.DbError);
}
var responseBody = new Body(new Dictionary<string, object>
{
{ "purged", purgedRevisions }
});
var retVal = context.CreateResponse();
retVal.JsonBody = responseBody;
return retVal;
}).AsDefaultState();
}
示例9: GetChangesPost
public static ICouchbaseResponseState GetChangesPost(ICouchbaseListenerContext context)
{
DBMonitorCouchbaseResponseState responseState = new DBMonitorCouchbaseResponseState();
var responseObject = PerformLogicWithDatabase(context, true, db =>
{
var response = context.CreateResponse();
responseState.Response = response;
var body = context.BodyAs<Dictionary<string, object>>();
ProcessBody(body);
if (body.GetCast<ChangesFeedMode>("feed") < ChangesFeedMode.Continuous) {
if(context.CacheWithEtag(db.GetLastSequenceNumber().ToString())) {
response.InternalStatus = StatusCode.NotModified;
return response;
}
}
var options = ChangesOptions.Default;
responseState.Db = db;
responseState.ContentOptions = body.GetCast<DocumentContentOptions>("content_options");
responseState.ChangesFeedMode = body.GetCast<ChangesFeedMode>("feed");
responseState.ChangesIncludeDocs = body.GetCast<bool>("include_docs");
options.IncludeDocs = responseState.ChangesIncludeDocs;
responseState.ChangesIncludeConflicts = body.GetCast<string>("style") == "all_docs";
options.IncludeConflicts = responseState.ChangesIncludeConflicts;
options.ContentOptions = responseState.ContentOptions;
options.SortBySequence = !options.IncludeConflicts;
options.Limit = body.GetCast<int>("limit", options.Limit);
int since = body.GetCast<int>("since");
string filterName = body.GetCast<string>("filter");
if(filterName != null) {
Status status = new Status();
responseState.ChangesFilter = db.GetFilter(filterName, status);
if(responseState.ChangesFilter == null) {
return context.CreateResponse(status.Code);
}
responseState.FilterParams = context.GetQueryParams();
}
RevisionList changes = db.ChangesSince(since, options, responseState.ChangesFilter, responseState.FilterParams);
if((responseState.ChangesFeedMode >= ChangesFeedMode.Continuous) ||
(responseState.ChangesFeedMode == ChangesFeedMode.LongPoll && changes.Count == 0)) {
// Response is going to stay open (continuous, or hanging GET):
response.Chunked = true;
if(responseState.ChangesFeedMode == ChangesFeedMode.EventSource) {
response["Content-Type"] = "text/event-stream; charset=utf-8";
}
if(responseState.ChangesFeedMode >= ChangesFeedMode.Continuous) {
response.WriteHeaders();
foreach(var rev in changes) {
response.SendContinuousLine(ChangesDictForRev(rev, responseState), context.ChangesFeedMode);
}
}
responseState.SubscribeToDatabase(db);
int heartbeat = body.GetCast<int>("heartbeat", Int32.MinValue);
if(heartbeat != Int32.MinValue) {
if(heartbeat <= 0) {
responseState.IsAsync = false;
return context.CreateResponse(StatusCode.BadParam);
}
heartbeat = Math.Max(heartbeat, (int)MinHeartbeat.TotalMilliseconds);
string heartbeatResponse = context.ChangesFeedMode == ChangesFeedMode.EventSource ? "\n\n" : "\r\n";
responseState.StartHeartbeat(heartbeatResponse, TimeSpan.FromMilliseconds(heartbeat));
}
return context.CreateResponse();
} else {
if(responseState.ChangesIncludeConflicts) {
response.JsonBody = new Body(ResponseBodyForChanges(changes, since, options.Limit, responseState));
} else {
response.JsonBody = new Body(ResponseBodyForChanges(changes, since, responseState));
}
return response;
}
});
responseState.Response = responseObject;
return responseState;
}
示例10: ProcessDocumentChangeOperations
/// <summary>
/// Create and update multiple documents at the same time within a single request.
/// </summary>
/// <returns>The response state for further HTTP processing</returns>
/// <param name="context">The context of the Couchbase Lite HTTP request</param>
/// <remarks>
/// http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_bulk_docs
/// </remarks>
public static ICouchbaseResponseState ProcessDocumentChangeOperations(ICouchbaseListenerContext context)
{
return PerformLogicWithDatabase(context, true, db =>
{
var postBody = context.BodyAs<Dictionary<string, object>>();
if(postBody == null) {
return context.CreateResponse(StatusCode.BadJson);
}
if(!postBody.ContainsKey("docs")) {
return context.CreateResponse(StatusCode.BadParam);
}
var docs = postBody["docs"].AsList<IDictionary<string, object>>();
bool allOrNothing;
postBody.TryGetValue<bool>("all_or_nothing", out allOrNothing);
bool newEdits;
postBody.TryGetValue<bool>("new_edits", out newEdits);
var response = context.CreateResponse();
StatusCode status = StatusCode.Ok;
bool success = db.RunInTransaction(() => {
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>(docs.Count);
var castContext = context as ICouchbaseListenerContext2;
var source = castContext != null && !castContext.IsLoopbackRequest ? castContext.Sender : null;
foreach(var doc in docs) {
string docId = doc.CblID();
RevisionInternal rev = null;
Body body = new Body(doc);
if(!newEdits) {
if(!RevisionInternal.IsValid(body)) {
status = StatusCode.BadParam;
} else {
rev = new RevisionInternal(body);
var history = Database.ParseCouchDBRevisionHistory(doc);
try {
db.ForceInsert(rev, history, source);
} catch(CouchbaseLiteException e) {
status = e.Code;
}
}
} else {
status = DocumentMethods.UpdateDocument(context, db, docId, body, false, allOrNothing, out rev);
}
IDictionary<string, object> result = null;
if((int)status < 300) {
Debug.Assert(rev != null && rev.RevID != null);
if(newEdits) {
result = new Dictionary<string, object>
{
{ "id", rev.DocID },
{ "rev", rev.RevID },
{ "status", (int)status }
};
}
} else if((int)status >= 500) {
return false; // abort the whole thing if something goes badly wrong
} else if(allOrNothing) {
return false; // all_or_nothing backs out if there's any error
} else {
var info = Status.ToHttpStatus(status);
result = new Dictionary<string, object>
{
{ "id", docId },
{ "error", info.Item2 },
{ "status", info.Item1 }
};
}
if(result != null) {
results.Add(result);
}
}
response.JsonBody = new Body(results.Cast<object>().ToList());
return true;
});
if(!success) {
response.InternalStatus = status;
}
return response;
}).AsDefaultState();
}
示例11: UpdateDocument
/// <summary>
/// Creates a new named document, or creates a new revision of the existing document.
/// </summary>
/// <returns>The response state for further HTTP processing</returns>
/// <param name="context">The context of the Couchbase Lite HTTP request</param>
/// <remarks>
/// http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid
/// <remarks>
public static ICouchbaseResponseState UpdateDocument(ICouchbaseListenerContext context)
{
return PerformLogicWithDocumentBody(context, (db, body) =>
{
var response = context.CreateResponse();
string docId = context.DocumentName;
if(context.GetQueryParam<bool>("new_edits", bool.TryParse, true)) {
// Regular PUT:
return UpdateDb(context, db, docId, body, false);
} else {
// PUT with new_edits=false -- forcible insertion of existing revision:
RevisionInternal rev = new RevisionInternal(body);
if(rev == null) {
response.InternalStatus = StatusCode.BadJson;
return response;
}
if(!docId.Equals(rev.GetDocId()) || rev.GetRevId() == null) {
response.InternalStatus = StatusCode.BadId;
return response;
}
var history = Database.ParseCouchDBRevisionHistory(body.GetProperties());
Status status = new Status();
try {
db.ForceInsert(rev, history, null);
} catch(CouchbaseLiteException e) {
status = e.CBLStatus;
}
if(!status.IsError) {
response.JsonBody = new Body(new Dictionary<string, object> {
{ "ok", true },
{ "id", rev.GetDocId() },
{ "rev", rev.GetRevId() }
});
}
response.InternalStatus = status.Code;
return response;
}
}).AsDefaultState();
}
示例12: PerformLogicWithDatabase
/// <summary>
/// Performs the given logic with the specified database
/// </summary>
/// <returns>The result (in terms of response to the client) of the database operation</returns>
/// <param name="context">The Couchbase Lite HTTP context</param>
/// <param name="open">Whether or not to open the database, or just find it</param>
/// <param name="action">The logic to perform on the database</param>
public static CouchbaseLiteResponse PerformLogicWithDatabase(ICouchbaseListenerContext context, bool open,
Func<Database, CouchbaseLiteResponse> action)
{
string dbName = context.DatabaseName;
Database db = context.DbManager.GetDatabaseWithoutOpening(dbName, false);
if (db == null || !db.Exists()) {
return context.CreateResponse(StatusCode.NotFound);
}
if (open) {
bool opened = db.Open();
if (!opened) {
return context.CreateResponse(StatusCode.DbError);
}
}
return action(db);
}
示例13: CheckForAltMethod
// Check for an incorrect request method on a request
private static CouchbaseLiteResponse CheckForAltMethod(ICouchbaseListenerContext context, CouchbaseLiteResponse response)
{
if (response.Status != RouteCollection.EndpointNotFoundStatus) {
return response;
}
var request = context.RequestUrl;
bool hasAltMethod = _Delete.HasLogicForRequest(request) || _Get.HasLogicForRequest(request)
|| _Post.HasLogicForRequest(request) || _Put.HasLogicForRequest(request);
if (hasAltMethod) {
return context.CreateResponse(StatusCode.MethodNotAllowed);
}
return context.CreateResponse(StatusCode.NotFound);
}
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:17,代码来源:CouchbaseLiteRouter.cs
示例14: ProcessResponse
// Attempt to write the response over the wire to the client
private static void ProcessResponse(ICouchbaseListenerContext context, ICouchbaseResponseState responseState)
{
CouchbaseLiteResponse responseObject = CheckForAltMethod(context, responseState.Response);
if (!responseState.IsAsync) {
try {
responseObject.ProcessRequestRanges();
responseObject.WriteHeaders();
responseObject.WriteToContext();
} catch(Exception e) {
Log.E(TAG, "Exception writing response", e);
responseState = context.CreateResponse(StatusCode.Exception).AsDefaultState();
}
} else {
_UnfinishedResponses.Add(responseState);
}
}
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:17,代码来源:CouchbaseLiteRouter.cs
示例15: HandleRequest
/// <summary>
/// The entry point for routing a request received by an CouchbaseLiteServiceListener
/// </summary>
/// <param name="context">The context containing information about the
/// request</param>
public void HandleRequest(ICouchbaseListenerContext context)
{
Log.V(TAG, "Processing {0} request to {1}", context.Method, context.RequestUrl.AbsoluteUri);
var method = context.Method;
if (OnAccessCheck != null) {
Status result = null;
try {
result = OnAccessCheck(method, context.RequestUrl.AbsolutePath);
} catch(Exception e) {
result = new Status(StatusCode.Exception);
Log.E(TAG, "Unhandled non-Couchbase exception in OnAccessCheck", e);
}
if (result.IsError) {
var r = context.CreateResponse(result.Code);
ProcessResponse(context, r.AsDefaultState());
return;
}
}
RestMethod logic = null;
if (method.Equals("GET") || method.Equals("HEAD")) {
logic = _Get.LogicForRequest(context.RequestUrl);
} else if (method.Equals("POST")) {
logic = _Post.LogicForRequest(context.RequestUrl);
} else if (method.Equals("PUT")) {
logic = _Put.LogicForRequest(context.RequestUrl);
} else if (method.Equals("DELETE")) {
logic = _Delete.LogicForRequest(context.RequestUrl);
} else {
logic = NOT_ALLOWED; // Shouldn't happen
}
ICouchbaseResponseState responseState = null;
try {
responseState = logic(context);
} catch(Exception e) {
var ce = e as CouchbaseLiteException;
if (ce != null) {
// This is in place so that a response can be written simply by throwing a couchbase lite exception
// in the routing logic
Log.I(TAG, "Couchbase exception in routing logic, this message can be ignored if intentional", e);
responseState = context.CreateResponse(ce.CBLStatus.Code).AsDefaultState();
} else {
Log.E(TAG, "Unhandled non-Couchbase exception in routing logic", e);
responseState = context.CreateResponse(StatusCode.Exception).AsDefaultState();
}
}
ProcessResponse(context, responseState);
}
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-couchbase-lite-net-couchbase,代码行数:58,代码来源:CouchbaseLiteRouter.cs