Exemplo n.º 1
0
        //*** GetView ***//

        public async override Task <object> HandleGetViewRequest(string databaseName, string ddocName, string viewName, IDictionary <string, object> parameters)
        {
            var fullSyncDatabase = await GetOrCreateFullSyncDatabase(databaseName);

            // Gets the view depending to its programming language (Javascript / C#)
            Couchbase.Lite.View view;
            if (ddocName != null)
            {
                // Javascript view
                view = CheckAndCreateJavaScriptView(fullSyncDatabase.Database, ddocName, viewName);
            }
            else
            {
                // C# view
                view = fullSyncDatabase.Database.GetView(viewName);
            }
            if (view == null)
            {
                throw new C8oRessourceNotFoundException(C8oExceptionMessage.IllegalArgumentNotFoundFullSyncView(viewName, fullSyncDatabase.DatabaseName));
            }

            // Creates the fullSync query and add parameters to it
            var query = view.CreateQuery();

            AddParametersToQuery(query, parameters);

            var result = query.Run();

            return(result);
        }
Exemplo n.º 2
0
 internal static void SetReplication(FullSyncReplicationParameter replicationParameter, Replication replication, object value)
 {
     Init();
     // Checks if the value type is String and the request parameter type is not
     if (typeof(string).IsAssignableFrom(value.GetType()) && !typeof(string).IsAssignableFrom(replicationParameter.type))
     {
         try
         {
             // Tries to convert the string to the request parameter type
             value = C8oTranslator.StringToObject(value as string, replicationParameter.type);
         }
         catch (Exception e)
         {
             throw new C8oException(C8oExceptionMessage.ParseStringToObject(replicationParameter.type), e);
         }
     }
     // Checks if the type is valid
     if (replicationParameter.type.IsAssignableFrom(value.GetType()))
     {
         // No reasons to fail
         Action <Replication, object> setReplicationOp = null;
         if (fullSyncReplicationParameters.TryGetValue(replicationParameter, out setReplicationOp))
         {
             setReplicationOp(replication, value);
         }
     }
     else
     {
         throw new ArgumentException(C8oExceptionMessage.InvalidArgumentInvalidParameterType(replicationParameter.name, "" + replicationParameter.type, "" + value.GetType()));
     }
 }
Exemplo n.º 3
0
        //*** Local cache ***//

        public override async Task <C8oLocalCacheResponse> GetResponseFromLocalCache(string c8oCallRequestIdentifier)
        {
            C8oFullSyncDatabase fullSyncDatabase = await GetOrCreateFullSyncDatabase(C8o.LOCAL_CACHE_DATABASE_NAME);

            Document localCacheDocument = fullSyncDatabase.Database.GetExistingDocument(c8oCallRequestIdentifier);

            if (localCacheDocument == null)
            {
                throw new C8oUnavailableLocalCacheException(C8oExceptionMessage.MissingLocalCacheResponseDocument());
            }

            IDictionary <string, object> properties = localCacheDocument.Properties;

            string response;
            string responseType;
            long   expirationDate;

            if (!C8oUtils.TryGetParameterObjectValue <String>(properties, C8o.LOCAL_CACHE_DOCUMENT_KEY_RESPONSE, out response) ||
                !C8oUtils.TryGetParameterObjectValue <String>(properties, C8o.LOCAL_CACHE_DOCUMENT_KEY_RESPONSE_TYPE, out responseType))
            {
                throw new C8oUnavailableLocalCacheException(C8oExceptionMessage.InvalidLocalCacheResponseInformation());
            }
            if (!C8oUtils.TryGetParameterObjectValue <long>(properties, C8o.LOCAL_CACHE_DOCUMENT_KEY_EXPIRATION_DATE, out expirationDate))
            {
                expirationDate = -1;
            }

            return(new C8oLocalCacheResponse(response, responseType, expirationDate));
        }
Exemplo n.º 4
0
        //*** DeleteDocument ***//

        /// <summary>
        /// Deletes an existing document from the local database.
        /// </summary>
        /// <param name="fullSyncDatabase"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public async override Task <object> HandleDeleteDocumentRequest(string fullSyncDatatbaseName, string docid, IDictionary <string, object> parameters)
        {
            var fullSyncDatabase = await GetOrCreateFullSyncDatabase(fullSyncDatatbaseName);

            string revParameterValue = C8oUtils.GetParameterStringValue(parameters, FullSyncDeleteDocumentParameter.REV.name, false);

            var document = fullSyncDatabase.Database.GetExistingDocument(docid);

            if (document == null)
            {
                throw new C8oRessourceNotFoundException(C8oExceptionMessage.RessourceNotFound("requested document"));
            }

            string documentRevision = document.CurrentRevisionId;

            // If the revision is specified then checks if this is the right revision
            if (revParameterValue != null && !revParameterValue.Equals(documentRevision))
            {
                throw new C8oRessourceNotFoundException(C8oExceptionMessage.RessourceNotFound("requested document"));
            }

            try
            {
                document.Delete();
            }
            catch (Exception e)
            {
                throw new C8oException(C8oExceptionMessage.CouchDeleteFailed(), e);
            }
            bool deleted = document.Deleted;

            return(new FullSyncDocumentOperationResponse(docid, revParameterValue, deleted));
        }
Exemplo n.º 5
0
        //*** GetDocument ***//

        /// <summary>
        /// Returns the requested document.
        /// </summary>
        /// <param name="fullSyncDatatbase"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public async override Task <object> HandleGetDocumentRequest(string fullSyncDatatbaseName, string docid, IDictionary <string, object> parameters)
        {
            var fullSyncDatabase = await GetOrCreateFullSyncDatabase(fullSyncDatatbaseName);

            // Gets the document form the local database
            var document = fullSyncDatabase.Database.GetExistingDocument(docid);

            if (document != null)
            {
                // If there are attachments, compute for each one the url to local storage and add it to the attachment descriptor
                var attachmentsProperty = document.GetProperty(C8oFullSync.FULL_SYNC__ATTACHMENTS) as JObject;
                if (attachmentsProperty != null)
                {
                    SavedRevision   rev = document.CurrentRevision;
                    Assembly        couchbaseLiteAssembly         = Assembly.GetAssembly(typeof(Attachment));
                    Type            attachmentInternalType        = couchbaseLiteAssembly.GetType(ATTACHMENT_INTERNAL_TYPE);
                    ConstructorInfo attachmentInternalConstructor = attachmentInternalType.GetConstructor(new Type[] { typeof(String), typeof(IDictionary <string, object>) });

                    foreach (var attachmentProperty in attachmentsProperty)
                    {
                        string     attachmentName = attachmentProperty.Key;
                        Attachment attachment     = rev.GetAttachment(attachmentName);
                        if (!attachment.Metadata.Keys.Contains(ATTACHMENT_PROPERTY_KEY_CONTENT_URL))
                        {
                            Object[] attachmentInternalConstructorParams = new Object[] { attachment.Name, attachment.Metadata };
                            object   attachmentInternal = attachmentInternalConstructor.Invoke(attachmentInternalConstructorParams);

                            PropertyInfo databaseProp = attachmentInternalType.GetProperty(ATTACHMENT_INTERNAL_PROPERTY_DATABASE);
                            databaseProp.SetValue(attachmentInternal, fullSyncDatabase.Database);

                            PropertyInfo urlProp    = attachmentInternalType.GetProperty(ATTACHMENT_INTERNAL_PROPERTY_CONTENT_URL);
                            object       contentUrl = urlProp.GetValue(attachmentInternal, null);
                            if (contentUrl != null && contentUrl is Uri)
                            {
                                Uri    uri          = (Uri)contentUrl;
                                string absoluteUri  = C8oUtils.UrlDecode(uri.AbsoluteUri);
                                string absolutePath = C8oUtils.UrlDecode(uri.AbsolutePath);
                                attachment.Metadata.Add(ATTACHMENT_PROPERTY_KEY_CONTENT_URL, absoluteUri);
                                if (attachmentProperty.Value is JObject)
                                {
                                    (attachmentProperty.Value as JObject)[ATTACHMENT_PROPERTY_KEY_CONTENT_URL] = absoluteUri;
                                }
                                attachment.Metadata.Add("content_path", absolutePath);
                                if (attachmentProperty.Value is JObject)
                                {
                                    (attachmentProperty.Value as JObject)["content_path"] = absolutePath;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                throw new C8oRessourceNotFoundException(C8oExceptionMessage.RessourceNotFound("requested document \"" + docid + "\""));
            }

            return(document);
        }
Exemplo n.º 6
0
        public C8oFullSyncDatabase(C8o c8o, Manager manager, string databaseName, string fullSyncDatabases, string localSuffix)
        {
            this.c8o = c8o;

            c8oFullSyncDatabaseUrl = new Uri(fullSyncDatabases + databaseName + "/");

            this.databaseName = (databaseName += localSuffix);
            try
            {
                var options = new DatabaseOptions();
                options.Create = true;
                if (c8o.FullSyncEncryptionKey != null)
                {
                    var key = new Couchbase.Lite.Store.SymmetricKey(c8o.FullSyncEncryptionKey);
                    options.EncryptionKey = key;
                }
                if (C8o.FS_STORAGE_SQL.Equals(c8o.FullSyncStorageEngine))
                {
                    options.StorageType = StorageEngineTypes.SQLite;
                }
                else
                {
                    options.StorageType = StorageEngineTypes.ForestDB;
                }

                try
                {
                    c8o.Log._Debug("manager.OpenDatabase(databaseName, options); //create");
                    database = manager.OpenDatabase(databaseName, options);
                    c8o.Log._Debug("manager.OpenDatabase(databaseName, options); //create ok");
                } catch (Exception ex)
                {
                    c8o.Log._Debug("manager.OpenDatabase(databaseName, options); //nocreate");
                    options.Create = false;
                    database       = manager.OpenDatabase(databaseName, options);
                    c8o.Log._Debug("manager.OpenDatabase(databaseName, options); //nocreate ok");
                }

                /*for (int i = 0; i < 6 && database == null; i++)
                 * {
                 *  Task.Delay(500).Wait();
                 *  database = manager.OpenDatabase(databaseName, options);
                 * }*/
                if (database == null)
                {
                    throw new C8oException("Cannot get the local database: " + databaseName);
                }
            }
            catch (Exception e)
            {
                if (!(e is C8oException))
                {
                    e = new C8oException(C8oExceptionMessage.FullSyncDatabaseInitFailed(databaseName), e);
                }
                throw e;
            }
        }
Exemplo n.º 7
0
        //*** Request handlers ***//

        public async Task <object> HandleFullSyncRequest(IDictionary <string, object> parameters, C8oResponseListener listener)
        {
            parameters = new Dictionary <string, object>(parameters);

            // Gets the project and the sequence parameter in order to know which database and which fullSyncrequestable to use
            string projectParameterValue = C8oUtils.PeekParameterStringValue(parameters, C8o.ENGINE_PARAMETER_PROJECT, true);

            if (!projectParameterValue.StartsWith(FULL_SYNC_PROJECT))
            {
                throw new ArgumentException(C8oExceptionMessage.InvalidParameterValue(projectParameterValue, "its don't start with " + FULL_SYNC_PROJECT));
            }

            string fullSyncRequestableValue = C8oUtils.PeekParameterStringValue(parameters, C8o.ENGINE_PARAMETER_SEQUENCE, true);
            // Gets the fullSync requestable and gets the response from this requestable
            FullSyncRequestable fullSyncRequestable = FullSyncRequestable.GetFullSyncRequestable(fullSyncRequestableValue);

            if (fullSyncRequestable == null)
            {
                throw new ArgumentException(C8oExceptionMessage.InvalidParameterValue(C8o.ENGINE_PARAMETER_PROJECT, C8oExceptionMessage.UnknownValue("fullSync requestable", fullSyncRequestableValue)));
            }

            // Gets the database name if this is not specified then if takes the default database name
            string databaseName = projectParameterValue.Substring(C8oFullSync.FULL_SYNC_PROJECT.Length);

            if (databaseName.Length < 1)
            {
                databaseName = c8o.DefaultDatabaseName;
                if (databaseName == null)
                {
                    throw new ArgumentException(C8oExceptionMessage.InvalidParameterValue(C8o.ENGINE_PARAMETER_PROJECT, C8oExceptionMessage.MissingValue("fullSync database name")));
                }
            }

            Object response;

            try
            {
                response = await fullSyncRequestable.HandleFullSyncRequest(this, databaseName, parameters, listener);
            }
            catch (C8oException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new C8oException(C8oExceptionMessage.FullSyncRequestFail(), e);
            }

            if (response == null)
            {
                throw new C8oException(C8oExceptionMessage.couchNullResult());
            }

            response = HandleFullSyncResponse(response, listener);
            return(response);
        }
Exemplo n.º 8
0
 public static object StringToObject(string objectValue, Type type)
 {
     try
     {
         return(JsonConvert.DeserializeObject(objectValue as string, type));
     }
     catch (Exception e)
     {
         throw new System.FormatException(C8oExceptionMessage.ParseStringToObject(type), e);
     }
 }
Exemplo n.º 9
0
 internal static void AddToQuery(Query query, FullSyncRequestParameter requestParameter, object value)
 {
     Init();
     // Checks if the type is valid
     if (requestParameter.type.IsAssignableFrom(value.GetType()))
     {
         fullSyncRequestParameters[requestParameter](query, value);
     }
     else
     {
         throw new ArgumentException(C8oExceptionMessage.InvalidArgumentInvalidParameterType(requestParameter.name, "" + requestParameter.type, "" + value.GetType()));
     }
 }
Exemplo n.º 10
0
        public async override Task <object> HandleReplicatePushRequest(string databaseName, IDictionary <string, object> parameters, C8oResponseListener c8oResponseListener)
        {
            var fullSyncDatabase = await GetOrCreateFullSyncDatabase(databaseName);

            try
            {
                fullSyncDatabase.StartPushReplication(parameters, c8oResponseListener);
            }
            catch (Exception e)
            {
                throw new C8oException(C8oExceptionMessage.FullSyncReplicationFail(databaseName, "push"), e);
            }
            return(VoidResponse.GetInstance());
        }
Exemplo n.º 11
0
        internal static Document PostDocument(FullSyncPolicy policy, Database database, IDictionary <string, object> newProperties)
        {
            Init();
            Func <Database, IDictionary <string, object>, Document> postDocumentOp = null;

            if (fullSyncPolicies.TryGetValue(policy, out postDocumentOp))
            {
                return(postDocumentOp(database, newProperties));
            }
            else
            {
                throw new ArgumentException(C8oExceptionMessage.UnknownFullSyncPolicy(policy));
            }
        }
Exemplo n.º 12
0
        public static string PeekParameterStringValue(IDictionary <string, object> parameters, string name, bool exceptionIfMissing = false)
        {
            string value = GetParameterStringValue(parameters, name, false);

            if (value == null)
            {
                if (exceptionIfMissing)
                {
                    throw new ArgumentException(C8oExceptionMessage.MissParameter(name));
                }
            }
            else
            {
                parameters.Remove(name);
            }
            return(value);
        }
Exemplo n.º 13
0
        //*** DeleteAttachment ***//

        public async override Task <object> HandleDeleteAttachmentRequest(string databaseName, string docid, string attachmentName)
        {
            var fullSyncDatabase = await GetOrCreateFullSyncDatabase(databaseName);

            // Gets the document form the local database
            var document = fullSyncDatabase.Database.GetExistingDocument(docid);

            if (document != null)
            {
                var newRev = document.CurrentRevision.CreateRevision();
                newRev.RemoveAttachment(attachmentName);
                var savedRev = newRev.Save();
            }
            else
            {
                throw new C8oRessourceNotFoundException(C8oExceptionMessage.RessourceNotFound("requested document \"" + docid + "\""));
            }

            return(new FullSyncDocumentOperationResponse(document.Id, document.CurrentRevisionId, true));
        }
Exemplo n.º 14
0
        private async Task <JObject> Execute(HttpWebRequest request, JObject document = null)
        {
            if (request.Accept == null)
            {
                request.Accept = "application/json";
            }

            if (authBasicHeader != null)
            {
                request.Headers["Authorization"] = authBasicHeader;
            }

            if (document != null)
            {
                request.ContentType = "application/json";

                using (var postStream = Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request).Result)
                {
                    // postData = "__connector=HTTP_connector&__transaction=transac1&testVariable=TEST 01";
                    byte[] byteArray = Encoding.UTF8.GetBytes(document.ToString());
                    // Add the post data to the web request

                    postStream.Write(byteArray, 0, byteArray.Length);
                }
            }

            HttpWebResponse response;

            try
            {
                response = await Task <WebResponse> .Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request) as HttpWebResponse;
            }
            catch (WebException e)
            {
                response = e.Response as HttpWebResponse;
                if (response == null)
                {
                    throw new C8oHttpException(C8oExceptionMessage.RunHttpRequest(), e);
                }
            }
            catch (Exception e)
            {
                if (e.InnerException is WebException)
                {
                    response = (e.InnerException as WebException).Response as HttpWebResponse;
                }
                else
                {
                    throw new C8oHttpException(C8oExceptionMessage.RunHttpRequest(), e);
                }
            }

            var matchContentType = RE_CONTENT_TYPE.Match(response.ContentType);

            string contentType;
            string charset;

            if (matchContentType.Success)
            {
                contentType = matchContentType.Groups[1].Value;
                charset     = matchContentType.Groups[2].Value;
            }
            else
            {
                contentType = response.ContentType;
                charset     = "UTF-8";
            }

            JObject json;

            if (contentType == "application/json" || contentType == "test/plain")
            {
                StreamReader streamReader  = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(charset));
                string       entityContent = streamReader.ReadToEnd();
                try
                {
                    json = JObject.Parse(entityContent);
                }
                catch
                {
                    json = new JObject();
                    try
                    {
                        json["item"] = JArray.Parse(entityContent);
                    }
                    catch
                    {
                        json["data"] = entityContent;
                    }
                }
            }
            else
            {
                json = new JObject();

                if (response.ContentType.StartsWith("text/"))
                {
                    StreamReader streamReader  = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(charset));
                    string       entityContent = streamReader.ReadToEnd();
                    json["data"] = entityContent;
                }
                else
                {
                    // TODO base64
                }
            }

            if (json == null)
            {
                json = new JObject();
            }

            var c8oMeta = new JObject();

            int code = (int)response.StatusCode;

            c8oMeta["statusCode"] = code;

            string status =
                code < 100 ? "unknown" :
                code < 200 ? "informational" :
                code < 300 ? "success" :
                code < 400 ? "redirection" :
                code < 500 ? "client error" :
                code < 600 ? "server error" : "unknown";

            c8oMeta["status"] = status;

            c8oMeta["reasonPhrase"] = response.StatusDescription;

            var headers = new JObject();

            foreach (string name in response.Headers.AllKeys)
            {
                headers[name] = response.Headers[name];
            }

            c8oMeta["headers"] = headers;

            json["_c8oMeta"] = c8oMeta;

            response.Dispose();

            return(json);
        }
Exemplo n.º 15
0
        //*** Request handlers ***//

        public override object HandleFullSyncResponse(object response, C8oResponseListener listener)
        {
            response = base.HandleFullSyncResponse(response, listener);
            if (response is VoidResponse)
            {
                return(response);
            }

            if (listener is C8oResponseJsonListener)
            {
                //*** Document (GetDocument) ***//
                if (response is Document)
                {
                    return(C8oFullSyncCblTranslator.DocumentToJson(response as Document));
                }
                //*** FullSyncDocumentOperationResponse (DeleteDocument, PostDocument) ***//
                else if (response is FullSyncDocumentOperationResponse)
                {
                    return(C8oFullSyncCblTranslator.FullSyncDocumentOperationResponseToJSON(response as FullSyncDocumentOperationResponse));
                }
                //*** QueryEnumerator (GetAllDocuments, GetView) ***//
                else if (response is QueryEnumerator)
                {
                    try
                    {
                        return(C8oFullSyncCblTranslator.QueryEnumeratorToJson(response as QueryEnumerator));
                    }
                    catch (C8oException e)
                    {
                        throw new C8oException(C8oExceptionMessage.queryEnumeratorToJSON(), e);
                    }
                }
                //*** FullSyncDefaultResponse (Sync, ReplicatePull, ReplicatePush, Reset) ***//
                else if (response is FullSyncDefaultResponse)
                {
                    return(C8oFullSyncCblTranslator.FullSyncDefaultResponseToJson(response as FullSyncDefaultResponse));
                }
            }
            else if (listener is C8oResponseXmlListener)
            {
                //*** Document (GetDocument) ***//
                if (response is Document)
                {
                    return(C8oFullSyncCblTranslator.DocumentToXml(response as Document));
                }
                //*** FullSyncDocumentOperationResponse (DeleteDocument, PostDocument) ***//
                else if (response is FullSyncDocumentOperationResponse)
                {
                    return(C8oFullSyncCblTranslator.FullSyncDocumentOperationResponseToXml(response as FullSyncDocumentOperationResponse));
                }
                //*** QueryEnumerator (GetAllDocuments, GetView) ***//
                else if (response is QueryEnumerator)
                {
                    try
                    {
                        return(C8oFullSyncCblTranslator.QueryEnumeratorToXml(response as QueryEnumerator));
                    }
                    catch (C8oException e)
                    {
                        throw new C8oException(C8oExceptionMessage.queryEnumeratorToXML(), e);
                    }
                }
                //*** FullSyncDefaultResponse (Sync, ReplicatePull, ReplicatePush, Reset) ***//
                else if (response is FullSyncDefaultResponse)
                {
                    return(C8oFullSyncCblTranslator.FullSyncDefaultResponseToXml(response as FullSyncDefaultResponse));
                }
            }
            else if (listener is C8oResponseCblListener)
            {
                //*** Document (GetDocument) ***// || //*** QueryEnumerator (GetAllDocuments, GetView) ***//
                if (response is Document || response is QueryEnumerator)
                {
                    return(response);
                }
            }
            return(response);
        }
Exemplo n.º 16
0
        //*** FullSyncPolicies ***//

        private static void InitFullSyncPolicies()
        {
            fullSyncPolicies = new Dictionary <FullSyncPolicy, Func <Database, IDictionary <string, object>, Document> >();
            FullSyncPolicy policy;
            Func <Database, IDictionary <string, object>, Document> func;

            // NONE
            policy = FullSyncPolicy.NONE;
            func   = (database, newProperties) =>
            {
                Document createdDocument;
                try
                {
                    string documentId = C8oUtils.GetParameterStringValue(newProperties, C8oFullSync.FULL_SYNC__ID, false);

                    // removes special properties
                    newProperties.Remove(C8oFullSync.FULL_SYNC__ID);

                    // Creates a new document or get an existing one (if the ID is specified)
                    createdDocument = (documentId == null) ? database.CreateDocument() : database.GetDocument(documentId);

                    createdDocument.PutProperties(newProperties);
                }
                catch (CouchbaseLiteException e)
                {
                    throw new C8oCouchbaseLiteException(C8oExceptionMessage.FullSyncPutProperties(newProperties), e);
                }
                return(createdDocument);
            };
            fullSyncPolicies.Add(policy, func);
            // CREATE
            policy = FullSyncPolicy.CREATE;
            func   = (database, newProperties) =>
            {
                Document createdDocument;
                try
                {
                    // Removes specials properties in order to create a new document
                    newProperties.Remove(C8oFullSync.FULL_SYNC__ID);
                    newProperties.Remove(C8oFullSync.FULL_SYNC__REV);
                    createdDocument = database.CreateDocument();
                    createdDocument.PutProperties(newProperties);
                }
                catch (CouchbaseLiteException e)
                {
                    throw new C8oCouchbaseLiteException(C8oExceptionMessage.FullSyncPutProperties(newProperties), e);
                }
                return(createdDocument);
            };
            fullSyncPolicies.Add(policy, func);
            // OVERRIDE
            policy = FullSyncPolicy.OVERRIDE;
            func   = (database, newProperties) =>
            {
                Document createdDocument;
                try
                {
                    // Gets the document ID
                    string documentId = C8oUtils.GetParameterStringValue(newProperties, C8oFullSync.FULL_SYNC__ID, false);

                    // Removes special properties in order to create a new document
                    newProperties.Remove(C8oFullSync.FULL_SYNC__ID);
                    newProperties.Remove(C8oFullSync.FULL_SYNC__REV);

                    // Creates a new document or get an existing one (if the ID is specified)
                    if (documentId == null)
                    {
                        createdDocument = database.CreateDocument();
                    }
                    else
                    {
                        createdDocument = database.GetDocument(documentId);
                        // Must add the current revision to the properties
                        var currentRevision = createdDocument.CurrentRevision;
                        if (currentRevision != null)
                        {
                            newProperties[C8oFullSync.FULL_SYNC__REV] = currentRevision.Id;
                        }
                    }

                    createdDocument.PutProperties(newProperties);
                }
                catch (CouchbaseLiteException e)
                {
                    throw new C8oCouchbaseLiteException(C8oExceptionMessage.FullSyncPutProperties(newProperties), e);
                }
                return(createdDocument);
            };
            fullSyncPolicies.Add(policy, func);
            // MERGE
            policy = FullSyncPolicy.MERGE;
            func   = (database, newProperties) =>
            {
                Document createdDocument;
                try
                {
                    // Gets the document ID
                    string documentId = C8oUtils.GetParameterStringValue(newProperties, C8oFullSync.FULL_SYNC__ID, false);

                    // Removes special properties in order to create a new document
                    newProperties.Remove(C8oFullSync.FULL_SYNC__ID);
                    newProperties.Remove(C8oFullSync.FULL_SYNC__REV);

                    // Creates a new document or get an existing one (if the ID is specified)
                    if (documentId == null)
                    {
                        createdDocument = database.CreateDocument();
                    }
                    else
                    {
                        createdDocument = database.GetDocument(documentId);
                    }

                    // Merges old properties with the new ones
                    var oldProperties = createdDocument.Properties;
                    if (oldProperties != null)
                    {
                        FullSyncUtils.MergeProperties(newProperties, oldProperties);
                    }

                    createdDocument.PutProperties(newProperties);
                }
                catch (CouchbaseLiteException e)
                {
                    throw new C8oCouchbaseLiteException(C8oExceptionMessage.FullSyncPutProperties(newProperties), e);
                }
                return(createdDocument);
            };
            fullSyncPolicies.Add(policy, func);
        }
Exemplo n.º 17
0
        private void HandleResponse(object result)
        {
            try
            {
                if (result is VoidResponse)
                {
                    return;
                }

                if (c8oResponseListener == null)
                {
                    return;
                }

                if (result is XDocument)
                {
                    c8o.c8oLogger.LogC8oCallXMLResponse(result as XDocument, c8oCallUrl, parameters);
                    (c8oResponseListener as C8oResponseXmlListener).OnXmlResponse(result as XDocument, parameters);
                }
                else if (result is JObject)
                {
                    c8o.c8oLogger.LogC8oCallJSONResponse(result as JObject, c8oCallUrl, parameters);
                    (c8oResponseListener as C8oResponseJsonListener).OnJsonResponse(result as JObject, parameters);
                }
                else if (result is Exception)
                {
                    // The result is an Exception
                    c8o.HandleCallException(c8oExceptionListener, parameters, (Exception)result);
                }
                else
                {
                    // The result type is unknown
                    c8o.HandleCallException(c8oExceptionListener, parameters, new C8oException(C8oExceptionMessage.WrongResult(result)));
                }

                /*else if (result instanceof com.couchbase.lite.Document) {
                 *  // TODO log
                 *
                 *  // The result is a fillSync query response
                 *  ((C8oFullSyncResponseListener) this.c8oResponseListener).onDocumentResponse(this.parameters, (com.couchbase.lite.Document) result);
                 * } else if (result instanceof QueryEnumerator) {
                 *  // TODO log
                 *
                 *  // The result is a fillSync query response
                 *  ((C8oFullSyncResponseListener) this.c8oResponseListener).onQueryEnumeratorResponse(this.parameters, (QueryEnumerator) result);
                 * } */
            }
            catch (Exception e)
            {
                c8o.HandleCallException(c8oExceptionListener, parameters, e);
            }
        }
Exemplo n.º 18
0
        async private Task <object> HandleRequest()
        {
            bool isFullSyncRequest = C8oFullSync.IsFullSyncRequest(parameters);

            if (isFullSyncRequest)
            {
                c8o.Log._Debug("Is FullSync request");

                var liveid = C8oUtils.GetParameterStringValue(parameters, C8o.FS_LIVE, false);
                if (liveid != null)
                {
                    var dbName = C8oUtils.GetParameterStringValue(parameters, C8o.ENGINE_PARAMETER_PROJECT, true).Substring(C8oFullSync.FULL_SYNC_PROJECT.Length);
                    c8o.AddLive(liveid, dbName, this);
                }

                // The result cannot be handled here because it can be different depending to the platform
                // But it can be useful bor debug
                try
                {
                    var fullSyncResult = await c8o.c8oFullSync.HandleFullSyncRequest(parameters, c8oResponseListener);

                    return(fullSyncResult);
                }
                catch (C8oException e)
                {
                    throw e;
                }
                catch (Exception e)
                {
                    throw new C8oException(C8oExceptionMessage.FullSyncRequestFail(), e);
                }
            }
            else
            {
                string responseType;
                if (c8oResponseListener == null || c8oResponseListener is C8oResponseXmlListener)
                {
                    responseType = C8o.RESPONSE_TYPE_XML;
                }
                else if (c8oResponseListener is C8oResponseJsonListener)
                {
                    responseType = C8o.RESPONSE_TYPE_JSON;
                }
                else
                {
                    return(new C8oException("wrong listener"));
                }

                //*** Local cache ***//

                string c8oCallRequestIdentifier = null;

                // Allows to enable or disable the local cache on a Convertigo requestable, default value is true
                C8oLocalCache localCache        = C8oUtils.GetParameterObjectValue(parameters, C8oLocalCache.PARAM, false) as C8oLocalCache;
                bool          localCacheEnabled = false;

                // If the engine parameter for local cache is specified
                if (localCache != null)
                {
                    // Removes local cache parameters and build the c8o call request identifier
                    parameters.Remove(C8oLocalCache.PARAM);

                    if (localCacheEnabled = localCache.enabled)
                    {
                        c8oCallRequestIdentifier = C8oUtils.IdentifyC8oCallRequest(parameters, responseType);

                        if (localCache.priority.IsAvailable(c8o))
                        {
                            try
                            {
                                C8oLocalCacheResponse localCacheResponse = await c8o.c8oFullSync.GetResponseFromLocalCache(c8oCallRequestIdentifier);

                                if (!localCacheResponse.Expired)
                                {
                                    if (responseType == C8o.RESPONSE_TYPE_XML)
                                    {
                                        return(C8oTranslator.StringToXml(localCacheResponse.Response));
                                    }
                                    else if (responseType == C8o.RESPONSE_TYPE_JSON)
                                    {
                                        return(C8oTranslator.StringToJson(localCacheResponse.Response));
                                    }
                                }
                            }
                            catch (C8oUnavailableLocalCacheException)
                            {
                                // no entry
                            }
                        }
                    }
                }

                //*** Get response ***//

                parameters[C8o.ENGINE_PARAMETER_DEVICE_UUID] = c8o.DeviceUUID;


                // Build the c8o call URL
                c8oCallUrl = c8o.Endpoint + "/." + responseType;

                HttpWebResponse httpResponse = null;
                Exception       exception    = null;
                try
                {
                    httpResponse = await c8o.httpInterface.HandleC8oCallRequest(c8oCallUrl, parameters);
                }
                catch (Exception e)
                {
                    exception = e;
                }

                if (exception != null)
                {
                    if (localCacheEnabled)
                    {
                        try
                        {
                            C8oLocalCacheResponse localCacheResponse = await c8o.c8oFullSync.GetResponseFromLocalCache(c8oCallRequestIdentifier);

                            if (!localCacheResponse.Expired)
                            {
                                if (responseType == C8o.RESPONSE_TYPE_XML)
                                {
                                    return(C8oTranslator.StringToXml(localCacheResponse.Response));
                                }
                                else if (responseType == C8o.RESPONSE_TYPE_JSON)
                                {
                                    return(C8oTranslator.StringToJson(localCacheResponse.Response));
                                }
                            }
                        }
                        catch (C8oUnavailableLocalCacheException)
                        {
                            // no entry
                        }
                    }
                    return(new C8oException(C8oExceptionMessage.handleC8oCallRequest(), exception));
                }

                var responseStream = httpResponse.GetResponseStream();

                object response;
                string responseString = null;
                if (c8oResponseListener is C8oResponseXmlListener)
                {
                    response = C8oTranslator.StreamToXml(responseStream);
                    if (localCacheEnabled)
                    {
                        responseString = C8oTranslator.XmlToString(response as XDocument);
                    }
                }
                else if (c8oResponseListener is C8oResponseJsonListener)
                {
                    responseString = C8oTranslator.StreamToString(responseStream);
                    response       = C8oTranslator.StringToJson(responseString);
                }
                else
                {
                    return(new C8oException("wrong listener"));
                }

                if (localCacheEnabled)
                {
                    // String responseString = C8oTranslator.StreamToString(responseStream);
                    long expirationDate = -1;
                    if (localCache.ttl > 0)
                    {
                        expirationDate = localCache.ttl + C8oUtils.GetUnixEpochTime(DateTime.Now);
                    }
                    var localCacheResponse = new C8oLocalCacheResponse(responseString, responseType, expirationDate);
                    await c8o.c8oFullSync.SaveResponseToLocalCache(c8oCallRequestIdentifier, localCacheResponse);
                }

                return(response);
            }
        }