//=========================================================
        // Peer eventing
        public Task PeerVentAsync(TransactionContext tcontext, CancellationToken token = default(CancellationToken))
        {
            try
            {
                SeekPosition start = new SeekPosition();
                if (peerOptions.Newest != null)
                {
                    start.Newest = new SeekNewest();
                }
                else if (peerOptions.StartEventsBlock != null)
                {
                    start.Specified = new SeekSpecified {
                        Number = (ulong)peerOptions.StartEventsBlock.Value
                    };
                }
                else
                {
                    start.Newest = new SeekNewest();
                }

                //   properties.

                Envelope envelope = ProtoUtils.CreateSeekInfoEnvelope(tcontext, start, new SeekPosition {
                    Specified = new SeekSpecified {
                        Number = (ulong)peerOptions.StopEventsBlock
                    }
                }, SeekInfo.Types.SeekBehavior.BlockUntilReady, clientTLSCertificateDigest);
                return(ConnectEnvelopeAsync(envelope, token));
            }
            catch (CryptoException e)
            {
                throw new TransactionException($"{ToString()} error message {e.Message}", e);
            }
        }
Exemplo n.º 2
0
        public override Task <Response> AddBooking(Request request, ServerCallContext context)
        {
            Logger.Info("add booking");
            Response response = null;

            try
            {
                tripsGrpc.Booking booking = request.Booking;
                Trip    trip         = ProtoUtils.ConvertToTrip(booking.Trip);
                Account account      = ProtoUtils.ConvertToAccount(booking.Account);
                Booking savedBooking = tripServices.AddBooking(booking.Client, booking.Phone, booking.NumTickets, trip, account);
                response = ProtoUtils.CreateOkResponse();

                Logger.Info("notifying observers");
                Response responseBookingAdded = new Response()
                {
                    Booking = new tripsGrpc.Booking()
                    {
                        Id         = savedBooking.Id,
                        Account    = booking.Account,
                        Trip       = booking.Trip,
                        Client     = savedBooking.ClientName,
                        Phone      = savedBooking.PhoneNumber,
                        NumTickets = savedBooking.NumTickets
                    }
                };
                buffer.Post(responseBookingAdded);
            }
            catch (Exception e)
            {
                response = ProtoUtils.CreateErrorResponse(e);
            }
            Logger.InfoFormat("add booking response {0}", response);
            return(Task.FromResult(response));
        }
Exemplo n.º 3
0
        public void UpdateContext([NotNull] List <ContextPage> updatedPages)
        {
            var updatedTracks = updatedPages
                                .SelectMany(x => x.Tracks).ToList();

            foreach (var track in updatedTracks)
            {
                var index = Tracks.FindIndex(x => x.Uri == track.Uri);
                if (index == -1)
                {
                    continue;
                }

                var b = new ContextTrack(Tracks[index]);
                ProtoUtils.CopyOverMetadata(track, b);
                Tracks[index] = b;

                if (index != GetCurrentTrackIndex())
                {
                    continue;
                }
                ProtoUtils.CopyOverMetadata(track, _state.ConnectState.Track);
                UpdateLikeDislike();
            }
        }
Exemplo n.º 4
0
        private string SetContext([NotNull] Context ctx)
        {
            var uri = ctx.Uri;

            Context = AbsSpotifyContext.From(uri);
            ConnectState.ContextUri = uri;

            if (!Context.IsFinite())
            {
                SetRepeatingContext(false);
                SetShufflingContext(false);
            }

            if (ctx.HasUrl)
            {
                this.ConnectState.ContextUrl = ctx.Url;
            }
            else
            {
                this.ConnectState.ContextUrl = String.Empty;
            }

            ConnectState.ContextMetadata.Clear();
            ProtoUtils.CopyOverMetadata(ctx, ConnectState);

            this.Pages        = PagesLoader.From(Session, ctx);
            this.TracksKeeper = new TracksKeeper(this);

            this.SpotifyDevice.SetIsActive(true);

            return(RenewSessionId());
        }
Exemplo n.º 5
0
        private async Task LoadTransforming()
        {
            if (TracksKeeper == null)
            {
                throw new Exception("Illegal State");
            }

            string url = null;

            if (ConnectState.ContextMetadata.ContainsKey("transforming.url"))
            {
                url = ConnectState.ContextMetadata["transforming.url"];
            }
            if (url == null)
            {
                return;
            }

            var shuffle = false;

            if (ConnectState.ContextMetadata.ContainsKey("transforming.shuffle"))
            {
                shuffle = bool.Parse(ConnectState.ContextMetadata["transforming.shuffle"]);
            }

            var willRequest =
                !ConnectState.Track.Metadata.ContainsKey(
                    "audio.fwdbtn.fade_overlap"); // I don't see another way to do this

            Debug.WriteLine("Context has transforming! url: {0}, shuffle: {1}, willRequest: {2}", url, shuffle,
                            willRequest);

            if (!willRequest)
            {
                return;
            }
            var obj = ProtoUtils.CraftContextStateCombo(ConnectState,
                                                        TracksKeeper.Tracks);

            try
            {
                var body = await url
                           .PostJsonAsync(obj)
                           .ReceiveString();

                if (body != null)
                {
                    UpdateContext(JObject.Parse(body));
                }
                Debug.WriteLine("Updated context with transforming information!");
            }
            catch (FlurlHttpException ex)
            {
                Debug.WriteLine($"Failed loading cuepoints " +
                                $"Error returned from {ex.Call.Request.Url}: {ex.Message}");
                return;
            }
        }
Exemplo n.º 6
0
 private Response HandleGetTrials(Request request)
 {
     return
         (new Response
     {
         ResponseType = ResponseType.OkResponse,
         Trials = { ProtoUtils.TrialsListToDto(_trialService.GetAll()) }
     });
 }
 private void InitScope()
 {
     if (this.scope != null)
     {
         return;
     }
     YarnServiceProtos.GetApplicationsRequestProtoOrBuilder p = viaProto ? proto : builder;
     this.scope = ProtoUtils.ConvertFromProtoFormat(p.GetScope());
 }
Exemplo n.º 8
0
        public override Task <Response> Logout(Request request, ServerCallContext context)
        {
            tripsGrpc.Account account        = request.Account;
            IServerStreamWriter <Response> o = null;

            observers.Remove(account.Id, out o);
            Logger.InfoFormat("removing observer {0}", account.Id);
            return(Task.FromResult(ProtoUtils.CreateOkResponse()));
        }
Exemplo n.º 9
0
        public override Task OutcomingMessage(NList message)
        {
            byte[]        data          = ProtoUtils.Serialize(message);
            NetDataWriter netDataWriter = new NetDataWriter();

            netDataWriter.PutBytesWithLength(data);
            Connection.Send(netDataWriter, DeliveryMethod.ReliableOrdered);

            return(Task.CompletedTask);
        }
Exemplo n.º 10
0
        public void TimeStampCurrent()
        {
            int      skew                 = 200; // need some skew here as we are not getting the times at same instance.
            DateTime original             = DateTime.UtcNow;
            DateTime currentDateTimestamp = ProtoUtils.GetCurrentFabricTimestamp().ToDateTime();
            DateTime before               = original.AddMilliseconds(-skew);
            DateTime after                = original.AddMilliseconds(skew);

            Assert.IsTrue(before < currentDateTimestamp);
            Assert.IsTrue(after > currentDateTimestamp);
        }
Exemplo n.º 11
0
        /*
         * GetTransaction
         * blockHash, UInt256
         */
        public string?GetTransaction(string[] arguments)
        {
            arguments[1] = EraseHexPrefix(arguments[1]);
            if (!IsValidHexString(arguments[1]))
            {
                return(null);
            }

            var tx = _transactionManager.GetByHash(arguments[1].HexToUInt256());

            return(tx is null ? $"Transaction {arguments[1]} not found" : ProtoUtils.ParsedObject(tx));
        }
Exemplo n.º 12
0
 public override AMCommand GetAMCommand()
 {
     lock (this)
     {
         YarnServiceProtos.AllocateResponseProtoOrBuilder p = viaProto ? proto : builder;
         if (!p.HasAMCommand())
         {
             return(null);
         }
         return(ProtoUtils.ConvertFromProtoFormat(p.GetAMCommand()));
     }
 }
Exemplo n.º 13
0
        private void CreateNetModeTransaction()
        {
            logger.Debug("NetModeTransaction");

            LinkedList <string> modlist = new LinkedList <string>();

            modlist.AddFirst("init");
            iargList.ForEach(a => modlist.AddAfter(modlist.Last, a));

            switch (chaincodeType)
            {
            case TransactionRequest.Type.JAVA:
                CcType(ChaincodeSpec.Types.Type.Java);
                break;

            case TransactionRequest.Type.NODE:
                CcType(ChaincodeSpec.Types.Type.Node);
                break;

            case TransactionRequest.Type.GO_LANG:
                CcType(ChaincodeSpec.Types.Type.Golang);
                break;

            default:
                throw new ArgumentException("Requested chaincode type is not supported: " + chaincodeType);
            }

            ChaincodeDeploymentSpec depspec = ProtoUtils.CreateDeploymentSpec(ccType, chaincodeName, chaincodePath, chaincodeVersion, modlist.ToList(), null);

            List <ByteString> argsList = new List <ByteString>();

            argsList.Add(ByteString.CopyFromUtf8(action));
            argsList.Add(ByteString.CopyFromUtf8(context.ChannelID));
            argsList.Add(depspec.ToByteString());
            if (chaincodePolicy != null)
            {
                argsList.Add(ByteString.CopyFrom(chaincodePolicy));
            }
            else if (null != chaincodeCollectionConfiguration)
            {
                argsList.Add(ByteString.Empty); //place holder for chaincodePolicy
            }

            if (null != chaincodeCollectionConfiguration)
            {
                argsList.Add(ByteString.Empty); //escc name place holder
                argsList.Add(ByteString.Empty); //vscc name place holder
                argsList.Add(ByteString.CopyFrom(chaincodeCollectionConfiguration));
            }

            Args(argsList);
        }
Exemplo n.º 14
0
        private async void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod clientDeliveryMethod)
        {
            NList      msg     = ProtoUtils.Deserialize <NList>(reader.GetBytesWithLength());
            UdpSession session = null;

            if (_Sessions.TryGetValue(peer.Id, out session))
            {
                await session.IncomingMessage(msg);
            }

            _NetManager.TriggerUpdate();
            reader.Recycle();
        }
Exemplo n.º 15
0
 public override void SetAMCommand(AMCommand command)
 {
     lock (this)
     {
         MaybeInitBuilder();
         if (command == null)
         {
             builder.ClearAMCommand();
             return;
         }
         builder.SetAMCommand(ProtoUtils.ConvertToProtoFormat(command));
     }
 }
Exemplo n.º 16
0
        public void Proto_Obtain_the_original_object_when_serialize_then_deserialize()
        {
            for (int i = 0; i < 100000; i++)
            {
                var project = new Project(10, "hello protobuf");
                var bytes   = ProtoUtils.ProtoSerialize(project);

                var deserializedProject = ProtoUtils.ProtoDeserialize <Project>(bytes);

                Check.That(deserializedProject.Id).IsEqualTo(10);
                Check.That(deserializedProject.Name).IsEqualTo("hello protobuf");
            }
        }
Exemplo n.º 17
0
        private List <ContextTrack> GetPage(int index)
        {
            if (index == -1)
            {
                throw new Exception("You must call nextPage() first!");
            }

            if (index == 0 && !_pages.Any() && _resolveUrl != null)
            {
                var m = _session.Mercury().SendSync(MercuryRequests.ResolveContext(_resolveUrl));
                var x = ProtoUtils.JsonToContextPages(JObject.Parse(m)["pages"] as JArray);
                _pages.AddRange(x);
            }

            _resolveUrl = null;

            if (index < _pages.Count)
            {
                var page   = _pages[index];
                var tracks = ResolvePage(page);
                page.ClearPageUrl();
                page.Tracks.Clear();
                page.Tracks.Add(tracks);
                _pages[index] = page;
                return(tracks);
            }
            else
            {
                if (index > _pages.Count)
                {
                    throw new IndexOutOfRangeException();
                }

                var prev = _pages[index - 1];
                if (!prev.HasNextPageUrl)
                {
                    throw new Exception("Illegal State");
                }

                var nextPageUrl = prev.NextPageUrl;
                prev.ClearNextPageUrl();
                _pages[index - 1] = prev;

                var tracks = FetchTracks(nextPageUrl);
                var tr     = new ContextPage();
                tr.Tracks.AddRange(tracks);
                _pages.Add(tr);

                return(tracks);
            }
        }
Exemplo n.º 18
0
        public async Task <string> Load([NotNull] JObject obj)
        {
            var k = (PlayCommandHelper.GetPlayOrigin(obj) as JObject);

            ConnectState.PlayOrigin = ProtoUtils.JsonToPlayOrigin(k !);
            ConnectState.Options    =
                ProtoUtils.JsonToPlayerOptions((JObject)PlayCommandHelper.GetPlayerOptionsOverride(obj), ConnectState.Options);
            var sessionId = SetContext(ProtoUtils.JsonToContext((JObject)PlayCommandHelper.GetContext(obj)));

            var trackUid   = PlayCommandHelper.GetSkipToUid(obj);
            var trackUri   = PlayCommandHelper.GetSkipToUri(obj);
            var trackIndex = PlayCommandHelper.GetSkipToIndex(obj);

            if (trackUri != null)
            {
                TracksKeeper.InitializeFrom(list => list.FindIndex(z => z.Uri == trackUri), null, null);
            }
            else if (trackUid != null)
            {
                TracksKeeper.InitializeFrom(list => list.FindIndex(z => z.Uid == trackUid), null, null);
            }
            else if (trackIndex != null)
            {
                TracksKeeper.InitializeFrom(list =>
                {
                    if (trackIndex < list.Count)
                    {
                        return((int)trackIndex);
                    }
                    return(-1);
                }, null, null);
            }
            else
            {
                TracksKeeper.InitializeStart();
            }

            var seekTo = PlayCommandHelper.GetSeekTo(obj);

            if (seekTo != null)
            {
                SetPosition((long)seekTo);
            }
            else
            {
                SetPosition(0);
            }
            await LoadTransforming();

            return(sessionId);
        }
Exemplo n.º 19
0
        private void InitNodeStates()
        {
            if (this.states != null)
            {
                return;
            }
            YarnServiceProtos.GetClusterNodesRequestProtoOrBuilder p = viaProto ? proto : builder;
            IList <YarnProtos.NodeStateProto> list = p.GetNodeStatesList();

            this.states = EnumSet.NoneOf <NodeState>();
            foreach (YarnProtos.NodeStateProto c in list)
            {
                this.states.AddItem(ProtoUtils.ConvertFromProtoFormat(c));
            }
        }
Exemplo n.º 20
0
 private Response HandleGetAgeCategories(Request request)
 {
     if (request.RequestType != RequestType.GetAgeCategoriesRequest)
     {
         return(new Response {
             ResponseType = ResponseType.InvalidRequest
         });
     }
     return
         (new Response
     {
         ResponseType = ResponseType.OkResponse,
         AgeCategories = { ProtoUtils.AgeCategoryListToDto(_ageCategoryService.GetAll()) }
     });
 }
 public override Credentials GetAppAttemptTokens()
 {
     YarnServerResourceManagerRecoveryProtos.ApplicationAttemptStateDataProtoOrBuilder
         p = viaProto ? proto : builder;
     if (appAttemptTokens != null)
     {
         return(ConvertCredentialsFromByteBuffer(appAttemptTokens));
     }
     if (!p.HasAppAttemptTokens())
     {
         return(null);
     }
     this.appAttemptTokens = ProtoUtils.ConvertFromProtoFormat(p.GetAppAttemptTokens()
                                                               );
     return(ConvertCredentialsFromByteBuffer(appAttemptTokens));
 }
        private void InitApplicationStates()
        {
            if (this.applicationStates != null)
            {
                return;
            }
            YarnServiceProtos.GetApplicationsRequestProtoOrBuilder p             = viaProto ? proto : builder;
            IList <YarnProtos.YarnApplicationStateProto>           appStatesList = p.GetApplicationStatesList
                                                                                       ();

            this.applicationStates = EnumSet.NoneOf <YarnApplicationState>();
            foreach (YarnProtos.YarnApplicationStateProto c in appStatesList)
            {
                this.applicationStates.AddItem(ProtoUtils.ConvertFromProtoFormat(c));
            }
        }
        private void InitSystemCredentials()
        {
            YarnServerCommonServiceProtos.NodeHeartbeatResponseProtoOrBuilder p = viaProto ?
                                                                                  proto : builder;
            IList <YarnServerCommonServiceProtos.SystemCredentialsForAppsProto> list = p.GetSystemCredentialsForAppsList
                                                                                           ();

            this.systemCredentials = new Dictionary <ApplicationId, ByteBuffer>();
            foreach (YarnServerCommonServiceProtos.SystemCredentialsForAppsProto c in list)
            {
                ApplicationId appId      = ConvertFromProtoFormat(c.GetAppId());
                ByteBuffer    byteBuffer = ProtoUtils.ConvertFromProtoFormat(c.GetCredentialsForApp(
                                                                                 ));
                this.systemCredentials[appId] = byteBuffer;
            }
        }
 private void MergeLocalToBuilder()
 {
     if (this.attemptId != null)
     {
         builder.SetAttemptId(((ApplicationAttemptIdPBImpl)attemptId).GetProto());
     }
     if (this.masterContainer != null)
     {
         builder.SetMasterContainer(((ContainerPBImpl)masterContainer).GetProto());
     }
     if (this.appAttemptTokens != null)
     {
         builder.SetAppAttemptTokens(ProtoUtils.ConvertToProtoFormat(this.appAttemptTokens
                                                                     ));
     }
 }
Exemplo n.º 25
0
 public void EnrichCurrentTrack([NotNull] ContextTrack track)
 {
     if (_isPlayingQueue)
     {
         var b = _state.ConnectState.Track;
         ProtoUtils.EnrichTrack(b, track);
     }
     else
     {
         int index   = (int)GetCurrentTrackIndex();
         var current = Tracks[index];
         ProtoUtils.EnrichTrack(current, track);
         Tracks[index]             = current;
         _state.ConnectState.Track = ProtoUtils.ConvertToProvidedTrack(current);
     }
 }
 private void MergeLocalToBuilder()
 {
     if (applicationTypes != null && !applicationTypes.IsEmpty())
     {
         builder.ClearApplicationTypes();
         builder.AddAllApplicationTypes(applicationTypes);
     }
     if (applicationStates != null && !applicationStates.IsEmpty())
     {
         builder.ClearApplicationStates();
         builder.AddAllApplicationStates(Iterables.Transform(applicationStates, new _Function_91
                                                                 ()));
     }
     if (applicationTags != null && !applicationTags.IsEmpty())
     {
         builder.ClearApplicationTags();
         builder.AddAllApplicationTags(this.applicationTags);
     }
     if (scope != null)
     {
         builder.SetScope(ProtoUtils.ConvertToProtoFormat(scope));
     }
     if (start != null)
     {
         builder.SetStartBegin(start.GetMinimumLong());
         builder.SetStartEnd(start.GetMaximumLong());
     }
     if (finish != null)
     {
         builder.SetFinishBegin(finish.GetMinimumLong());
         builder.SetFinishEnd(finish.GetMaximumLong());
     }
     if (limit != long.MaxValue)
     {
         builder.SetLimit(limit);
     }
     if (users != null && !users.IsEmpty())
     {
         builder.ClearUsers();
         builder.AddAllUsers(users);
     }
     if (queues != null && !queues.IsEmpty())
     {
         builder.ClearQueues();
         builder.AddAllQueues(queues);
     }
 }
        private void InitApplicationACLs()
        {
            if (this.applicationACLS != null)
            {
                return;
            }
            YarnServiceProtos.RegisterApplicationMasterResponseProtoOrBuilder p = viaProto ?
                                                                                  proto : builder;
            IList <YarnProtos.ApplicationACLMapProto> list = p.GetApplicationACLsList();

            this.applicationACLS = new Dictionary <ApplicationAccessType, string>(list.Count);
            foreach (YarnProtos.ApplicationACLMapProto aclProto in list)
            {
                this.applicationACLS[ProtoUtils.ConvertFromProtoFormat(aclProto.GetAccessType())]
                    = aclProto.GetAcl();
            }
        }
Exemplo n.º 28
0
        public void UpdateState()
        {
            if (_isPlayingQueue)
            {
                _state.ConnectState.Track = ProtoUtils.ConvertToProvidedTrack(_queue.First.Value);
                _queue.RemoveFirst();
            }
            else
            {
                _state.ConnectState.Track = ProtoUtils.ConvertToProvidedTrack(Tracks[(int)GetCurrentTrackIndex()]);
            }

            UpdateLikeDislike();

            UpdateTrackDuration();
            UpdatePrevNextTracks();
        }
Exemplo n.º 29
0
        public override Task <Response> GetAllTrips(Request request, ServerCallContext context)
        {
            Logger.Info("getting all trips");
            Response response = null;

            try
            {
                List <Trip> t = tripServices.GetAllTrips();
                response = ProtoUtils.CreateGetTripsResponse(t);
            }
            catch (Exception e)
            {
                response = ProtoUtils.CreateErrorResponse(e);
            }
            Logger.InfoFormat("sending get all trips response {0}", response.Type);
            return(Task.FromResult(response));
        }
Exemplo n.º 30
0
        public override Task <Response> GetTripsByLandmarkDepartureHour(Request request, ServerCallContext context)
        {
            Logger.Info("searching trips");
            Response response = null;

            try
            {
                tripsGrpc.Trip t        = request.Trip;
                List <Trip>    tripList = tripServices.GetTripsByLandmarkDepartureHour(t.Landmark, t.Start, t.End);
                response = ProtoUtils.CreateGetTripsResponse(tripList);
            }
            catch (Exception e)
            {
                response = ProtoUtils.CreateErrorResponse(e);
            }
            Logger.InfoFormat("sending search trips response {0}", response.Type);
            return(Task.FromResult(response));
        }