Example #1
0
        /// <summary>
        /// Set the data for the node of the given path if such a node exists and the
        /// given version matches the version of the node (if the given version is
        /// -1, it matches any node's versions). Return the stat of the node.
        ///
        /// This operation, if successful, will trigger all the watches on the node
        /// of the given path left by getData calls.
        ///
        /// A KeeperException with error code KeeperException.NoNode will be thrown
        /// if no node with the given path exists.
        ///
        /// A KeeperException with error code KeeperException.BadVersion will be
        /// thrown if the given version does not match the node's version.
        ///
        /// The maximum allowable size of the data array is 1 MB (1,048,576 bytes).
        /// Arrays larger than this will cause a KeeperExecption to be thrown.
        /// @param path
        ///                the path of the node
        /// @param data
        ///                the data to set
        /// @param version
        ///                the expected matching version
        /// @return the state of the node
        /// @throws InterruptedException If the server transaction is interrupted.
        /// @throws KeeperException If the server signals an error with a non-zero error code.
        /// @throws IllegalArgumentException if an invalid path is specified
        /// </summary>
        public Stat SetData(string path, byte[] data, int version)
        {
            string clientPath = path;

            PathUtils.ValidatePath(clientPath);

            string serverPath = PrependChroot(clientPath);

            RequestHeader h = new RequestHeader();

            h.Type = (int)OpCode.SetData;
            SetDataRequest request = new SetDataRequest();

            request.Path    = serverPath;
            request.Data    = data;
            request.Version = version;
            SetDataResponse response = new SetDataResponse();
            ReplyHeader     r        = cnxn.SubmitRequest(h, request, response, null);

            if (r.Err != 0)
            {
                throw KeeperException.Create((KeeperException.Code)Enum.ToObject(typeof(KeeperException.Code), r.Err), clientPath);
            }
            return(response.Stat);
        }
Example #2
0
            public static SetDataRequest create(string jsonString)
            {
                JObject jObject = deserializeJson(jsonString);

                JProperty type      = jObject.Property("type");
                JProperty handshake = jObject.Property("handshake");
                JProperty values    = jObject.Property("values");

                if (type == null || type.Value == null || type.Value.Type != JTokenType.Integer)
                {
                    return(null);
                }

                // Must have handshake
                if (handshake == null)
                {
                    return(null);
                }

                if (values == null)
                {
                    return(null);
                }

                SimCapiMessageType messageType = type.ToObject <SimCapiMessageType>();

                if (messageType != SimCapiMessageType.SET_DATA_REQUEST)
                {
                    return(null);
                }

                JToken key   = values.Value["key"];
                JToken simId = values.Value["simId"];
                JToken value = values.Value["value"];

                if (key == null && key.Type != JTokenType.String)
                {
                    return(null);
                }

                if (simId == null && simId.Type != JTokenType.String)
                {
                    return(null);
                }

                if (value == null && value.Type != JTokenType.String)
                {
                    return(null);
                }

                SetDataRequest setDataRequest = new SetDataRequest();

                setDataRequest.handshake = handshake.Value.ToObject <SimCapiHandshake>();
                setDataRequest.key       = key.ToObject <string>();
                setDataRequest.simId     = simId.ToObject <string>();
                setDataRequest.value     = value.ToObject <string>();

                return(setDataRequest);
            }
        public IActionResult SetRight(string id, [FromBody] SetDataRequest requestBody)
        {
            _logger.LogInformation($"Updating right data for id {id}, {requestBody}");
            var data = requestBody?.Data;

            if (string.IsNullOrEmpty(data))
            {
                throw new InvalidInputException("Missing data field");
            }

            return(Ok(_diffCheckerService.SetRight(id, data)));
        }
        public async Task <ActionResult <SetDataResponse> > SetData([FromBody] SetDataRequest request)
        {
            if (_magoAPI.Client == null)
            {
                return(new ContentResult {
                    StatusCode = 500,
                    Content = "Error on SetData: not logged in"
                });
            }
            try
            {
                ITbServerMagicLinkResult tbResult = await _magoAPI.Client.TbServer?.SetXmlData(request.userData, request.xmlData, 0, DateTime.Now);

                if (!tbResult.Success)
                {
                    return(new ContentResult {
                        StatusCode = 500,
                        Content = $"Error in SetData\r\n{tbResult.ReturnValue}"
                    });
                }
                if (tbResult.Xmls.Count == 0)
                {
                    return(new ContentResult {
                        StatusCode = 500,
                        Content = "No postback received"
                    });
                }

                var strMessages = extractXMLMessages(tbResult.Xmls[0], out bool hasErrors);
                if (hasErrors)
                {
                    return(new ContentResult {
                        StatusCode = 500,
                        Content = $"Request failed:\r\n{strMessages}"
                    });
                }

                return(new SetDataResponse {
                    xmlData = tbResult.Xmls[0],
                    warnings = strMessages
                });
            }
            catch (System.Exception e)
            {
                return(new ContentResult {
                    StatusCode = 500,
                    Content = e.Message
                });
            }
        }
        public void CallsServiceWhenSetRightIsCalledCorrectly()
        {
            var request = new SetDataRequest
            {
                Data = TestData
            };

            _controller.SetRight(TestId, request);

            _diffCheckerServiceMock
            .Verify(
                dcs => dcs.SetRight(
                    It.Is <string>(id => id.Equals(TestId)),
                    It.Is <string>(dataRequest => dataRequest.Equals(TestData)))
                );
        }
        public void deserialize(InputArchive archive, string tag)
        {
            archive.startRecord(tag);
            MultiHeader h = new MultiHeader();

            ((Record)h).deserialize(archive, tag);

            while (!h.getDone())
            {
                ZooDefs.OpCode opCode = EnumUtil <ZooDefs.OpCode> .DefinedCast(h.get_Type());

                switch (opCode)
                {
                case ZooDefs.OpCode.create:
                    CreateRequest cr = new CreateRequest();
                    ((Record)cr).deserialize(archive, tag);
                    add(Op.create(cr.getPath(), cr.getData(), cr.getAcl(), cr.getFlags()));
                    break;

                case ZooDefs.OpCode.delete:
                    DeleteRequest dr = new DeleteRequest();
                    ((Record)dr).deserialize(archive, tag);
                    add(Op.delete(dr.getPath(), dr.getVersion()));
                    break;

                case ZooDefs.OpCode.setData:
                    SetDataRequest sdr = new SetDataRequest();
                    ((Record)sdr).deserialize(archive, tag);
                    add(Op.setData(sdr.getPath(), sdr.getData(), sdr.getVersion()));
                    break;

                case ZooDefs.OpCode.check:
                    CheckVersionRequest cvr = new CheckVersionRequest();
                    ((Record)cvr).deserialize(archive, tag);
                    add(Op.check(cvr.getPath(), cvr.getVersion()));
                    break;

                default:
                    throw new IOException("Invalid type of op");
                }
                ((Record)h).deserialize(archive, tag);
            }
            archive.endRecord(tag);
        }
        /// <summary>
        /// <para>Trying to update node data with optimistic concurrency strategy according to given <paramref name="request"/>.</para>
        /// <para>Check returned <see cref="UpdateDataResult"/> to see if operation was successful.</para>
        /// </summary>
        public static async Task <UpdateDataResult> UpdateDataAsync(this IZooKeeperClient zooKeeperClient, UpdateDataRequest request)
        {
            try
            {
                for (var i = 0; i < request.Attempts; i++)
                {
                    var readResult = await zooKeeperClient.GetDataAsync(new GetDataRequest(request.Path)).ConfigureAwait(false);

                    if (!readResult.IsSuccessful)
                    {
                        return(UpdateDataResult.Unsuccessful(readResult.Status, readResult.Path, readResult.Exception));
                    }

                    var newData = request.Update(readResult.Data);

                    if (ByteArrayKey.Equals(readResult.Data, newData))
                    {
                        return(UpdateDataResult.Successful(readResult.Path));
                    }

                    var setDataRequest = new SetDataRequest(request.Path, newData)
                    {
                        Version = readResult.Stat.Version
                    };

                    var updateResult = await zooKeeperClient.SetDataAsync(setDataRequest).ConfigureAwait(false);

                    if (updateResult.Status == ZooKeeperStatus.VersionsMismatch)
                    {
                        continue;
                    }

                    return(updateResult.IsSuccessful ? UpdateDataResult.Successful(updateResult.Path) : UpdateDataResult.Unsuccessful(updateResult.Status, updateResult.Path, updateResult.Exception));
                }

                return(UpdateDataResult.Unsuccessful(ZooKeeperStatus.VersionsMismatch, request.Path, null));
            }
            catch (Exception e)
            {
                return(UpdateDataResult.Unsuccessful(ZooKeeperStatus.UnknownError, request.Path, e));
            }
        }
Example #8
0
        private async Task <Stat> SetDataAsyncInternal(string path, byte[] data, int version, bool sync)
        {
            string clientPath = path;

            PathUtils.ValidatePath(clientPath);

            string serverPath = PrependChroot(clientPath);

            RequestHeader h = new RequestHeader();

            h.Type = (int)OpCode.SetData;
            SetDataRequest  request  = new SetDataRequest(serverPath, data, version);
            SetDataResponse response = new SetDataResponse();
            ReplyHeader     r        = cnxn.SubmitRequest(h, request, response, null);

            if (r.Err != 0)
            {
                throw KeeperException.Create((KeeperException.Code)Enum.ToObject(typeof(KeeperException.Code), r.Err), clientPath);
            }
            return(response.Stat);
        }
 public Task <SetDataResult> SetDataAsync(SetDataRequest request) =>
 throw new NotSupportedException();
 /// <inheritdoc cref="IZooKeeperClient.SetDataAsync"/>
 public static SetDataResult SetData(this IZooKeeperClient client, SetDataRequest request) =>
 client.SetDataAsync(request).GetAwaiter().GetResult();
 /// <inheritdoc />
 public Task <SetDataResult> SetDataAsync(SetDataRequest request) =>
 ExecuteOperation(new SetDataOperation(request));