Beispiel #1
0
        public ExecuteResponse Execute(ExecuteRequest request)
        {
            ExecuteResponse response = new ExecuteResponse();

            List <Header> headers = new List <Header>();

            for (int i = 0; i < 4; i++)
            {
                Header header = new Header();
                header.Title = $"T{i + 1}";
                headers.Add(header);
            }
            response.HeaderList = headers;

            List <List <string> > rows = new List <List <string> >();

            for (int i = 0; i < 68; i++)
            {
                List <string> row = new List <string>();

                for (int ij = 0; ij < 4; ij++)
                {
                    row.Add($"C-{i}-{ij}");
                }

                rows.Add(row);
            }
            response.RowList = rows;

            response.Message = request.Command;

            response.Status = 1;
            return(response);
        }
Beispiel #2
0
 private void SetHeaders <TResponse>(ExecuteRequest <TResponse> info) where TResponse : class, IResponseResult
 {
     foreach (var value in info.Headers)
     {
         _client.DefaultRequestHeaders.Add(value.Key, value.Value);
     }
 }
Beispiel #3
0
 private void CleanHeaders <TResponse>(ExecuteRequest <TResponse> info) where TResponse : class, IResponseResult
 {
     foreach (var value in info.Headers)
     {
         _client.DefaultRequestHeaders.Remove(value.Key);
     }
 }
Beispiel #4
0
        public void Execute_Prepared_With_Param_Test()
        {
            using (var connection = CreateConnection())
            {
                connection.Open().Wait();

                var prepareRequest = new PrepareRequest(GetSerializer(), "SELECT * FROM system.local WHERE key = ?", null, null);
                var task           = connection.Send(prepareRequest);
                var prepareOutput  = ValidateResult <OutputPrepared>(task.Result);

                var options = new QueryProtocolOptions(ConsistencyLevel.One, new object[] { "local" }, false, 100, null, ConsistencyLevel.Any);

                var executeRequest = new ExecuteRequest(
                    GetSerializer(),
                    prepareOutput.QueryId,
                    null,
                    new ResultMetadata(prepareOutput.ResultMetadataId, prepareOutput.ResultRowsMetadata),
                    options,
                    false,
                    null);

                task = connection.Send(executeRequest);
                var output = ValidateResult <OutputRows>(task.Result);

                var rows = output.RowSet.ToList();
                Assert.Greater(rows.Count, 0);
                Assert.NotNull(rows[0].GetValue <string>("key"), "It should contain a key column value");
            }
        }
        public void RunScript()
        {
            LogIn();
            var executeRequest = new ExecuteRequest();

            executeRequest.Code = Code;
            if (InputParameters.Count != 0)
            {
                executeRequest.InputParameters = InputParameters;
            }

            if (OutputParameters.Count != 0)
            {
                executeRequest.OutputParameters = OutputParameters;
            }

            var executeResponse = Client.ExecuteCode(Response.SessionId, executeRequest);

            if (executeResponse.Success.Value)
            {
                PopulateResults(executeResponse);
                LogOut();
            }
            else
            {
                LogOut();
                throw new Exception(executeResponse.ErrorMessage);
            }
        }
Beispiel #6
0
        public void Execute_Prepared_Test()
        {
            using (var connection = CreateConnection())
            {
                connection.Open().Wait();

                //Prepare a query
                var prepareRequest = new PrepareRequest(GetSerializer(), BasicQuery, null, null);
                var task           = connection.Send(prepareRequest);
                var prepareOutput  = ValidateResult <OutputPrepared>(task.Result);

                //Execute the prepared query
                var executeRequest = new ExecuteRequest(
                    GetSerializer(),
                    prepareOutput.QueryId,
                    null,
                    new ResultMetadata(prepareOutput.ResultMetadataId, prepareOutput.ResultRowsMetadata),
                    QueryProtocolOptions.Default,
                    false,
                    null);
                task = connection.Send(executeRequest);
                var output = ValidateResult <OutputRows>(task.Result);
                var rs     = output.RowSet;
                var rows   = rs.ToList();
                Assert.Greater(rows.Count, 0);
                Assert.True(rows[0].GetValue <string>("key") != null, "It should contain a key column");
            }
        }
Beispiel #7
0
        public async Task GetRawResult_ValidRequestGiven_ShouldReturnResult()
        {
            const string expectedResultXml = "<wps:LiteralValue xmlns:wps=\"http://www.opengis.net/wps/2.0\" dataType=\"https://www.w3.org/2001/XMLSchema-datatypes#string\">150</wps:LiteralValue>";

            var request = new ExecuteRequest
            {
                Inputs = new[]
                {
                    new DataInput
                    {
                        Data = new LiteralDataValue {
                            Value = "test"
                        }
                    }
                },
                ExecutionMode = ExecutionMode.Synchronous,
                ResponseType  = ResponseType.Raw
            };

            var expectedRequestXml = new XmlSerializationService().Serialize(request);

            var wpsClient = new WpsClient(new HttpClient(GetMockedMessageHandlerForResponse(expectedResultXml, HttpStatusCode.OK, expectedRequestXml)), new XmlSerializationService());

            var result = await wpsClient.GetRawResult(MockUri, request);

            result.Should().Be(expectedResultXml);
        }
Beispiel #8
0
        public async Task AsyncGetDocumentedResult_ValidRequestGiven_ShouldReturnResult(string expectedHttpResponse)
        {
            var request = new ExecuteRequest
            {
                Identifier = "org.n52.javaps.test.EchoProcess",
                Inputs     = new[]
                {
                    new DataInput
                    {
                        Data = new LiteralDataValue {
                            Value = "test"
                        }
                    }
                },
                Outputs = new []
                {
                    new DataOutput
                    {
                        MimeType = "text/xml"
                    }
                },
                ExecutionMode = ExecutionMode.Asynchronous,
                ResponseType  = ResponseType.Document
            };

            var expectedRequestXml = new XmlSerializationService().Serialize(request);

            var wpsClient = new WpsClient(new HttpClient(GetMockedMessageHandlerForResponse(expectedHttpResponse, HttpStatusCode.OK, expectedRequestXml)), new XmlSerializationService());

            var session = await wpsClient.AsyncGetDocumentResultAs <LiteralDataValue>(MockUri, request);

            session.Should().NotBeNull();
            session.JobId.Should().Be("test-job-id");
        }
Beispiel #9
0
        private void EventLoop(NetMQSocket socket)
        {
            this.logger.LogDebug("Starting shell server event loop at {Address}.", socket);
            while (alive)
            {
                try
                {
                    // Start by pulling off the next <action>_request message
                    // from the client.
                    var nextMessage = socket.ReceiveMessage(context);
                    logger.LogDebug(
                        $"Received new message:\n" +
                        $"\t{JsonConvert.SerializeObject(nextMessage.Header)}\n" +
                        $"\t{JsonConvert.SerializeObject(nextMessage.ParentHeader)}\n" +
                        $"\t{JsonConvert.SerializeObject(nextMessage.Metadata)}\n" +
                        $"\t{JsonConvert.SerializeObject(nextMessage.Content)}"
                        );

                    // If this is our first message, we need to set the session
                    // id.
                    if (session == null)
                    {
                        session = nextMessage.Header.Session;
                    }

                    // Get a service that can handle the message type and
                    // dispatch.
                    switch (nextMessage.Header.MessageType)
                    {
                    case "kernel_info_request":
                        KernelInfoRequest?.Invoke(nextMessage);
                        break;

                    case "execute_request":
                        ExecuteRequest?.Invoke(nextMessage);
                        break;

                    case "shutdown_request":
                        ShutdownRequest?.Invoke(nextMessage);
                        break;
                    }
                }
                catch (ProtocolViolationException ex)
                {
                    logger.LogCritical(ex, $"Protocol violation when trying to receive next ZeroMQ message.");
                }
                catch (ThreadInterruptedException)
                {
                    if (alive)
                    {
                        continue;
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
    public override Task <GenericResponse> Execute(ExecuteRequest request, ServerCallContext context)
    {
        Process.Start(request.Path);

        return(Task.FromResult(new GenericResponse {
            Succeeded = true
        }));
    }
 public OpenRequest(JupyterRequestContext context, ExecuteRequest executeRequest, int executionCount, Guid id, Dictionary <string, object> transient)
 {
     Context        = context;
     ExecuteRequest = executeRequest;
     ExecutionCount = executionCount;
     Id             = id;
     Transient      = transient;
 }
 private ExecuteResponse.Builder GetAccountDigest(ExecuteRequest request)
 {
     ExecuteResponse.Builder builder = ExecuteResponse.CreateBuilder();
     foreach (OperationResult result in request.OperationsList.Select(operation => CreateOperationResult(operation, 1, AccountDigest.ToByteString())))
     {
         builder.AddResults(result);
     }
     return(builder);
 }
Beispiel #13
0
        private string CreateEndpoint <TResponse>(ExecuteRequest <TResponse> info) where TResponse : class, IResponseResult
        {
            if (_options.IsTest)
            {
                return($"{info.EndPointPath}{(info.EndPointPath.Contains("?") ? "&test=1" : "?test=1")}");
            }

            return(info.EndPointPath);
        }
Beispiel #14
0
        public void Build_ReturnDeliveryRequest()
        {
            var context       = new Mock <Context>().Object;
            var execute       = new ExecuteRequest();
            var prefetch      = new PrefetchRequest();
            var notifications = new List <Notification>();
            var customerIds   = new List <CustomerId>();
            var property      = new Property("testToken");
            var telemetry     = new Telemetry();
            var trace         = new Trace("testAuthToken");
            var expCloud      = new ExperienceCloud();
            var qaMode        = new QAMode();

            var request = new TargetDeliveryRequest.Builder()
                          .SetTntId(tntId)
                          .SetMarketingCloudVisitorId(marketingCloudVisitorId)
                          .SetThirdPartyId(thirdPartyId)
                          .SetContext(context)
                          .SetExecute(execute)
                          .SetPrefetch(prefetch)
                          .SetNotifications(notifications)
                          .SetProperty(property)
                          .SetTelemetry(telemetry)
                          .SetTrace(trace)
                          .SetExperienceCloud(expCloud)
                          .SetEnvironmentId(environmentId)
                          .SetImpressionId(impressionId)
                          .SetQaMode(qaMode)
                          .SetLocationHint(locationHint)
                          .SetRequestId(requestId)
                          .SetSessionId(sessionId)
                          .SetTargetCustomerIds(customerIds)
                          .SetDecisioningMethod(DecisioningMethod.Hybrid)
                          .Build();

            Assert.Equal(tntId, request.DeliveryRequest.Id.TntId);
            Assert.Equal(marketingCloudVisitorId, request.DeliveryRequest.Id.MarketingCloudVisitorId);
            Assert.Equal(thirdPartyId, request.DeliveryRequest.Id.ThirdPartyId);
            Assert.Equal(customerIds, request.DeliveryRequest.Id.CustomerIds);
            Assert.Equal(context, request.DeliveryRequest.Context);
            Assert.Equal(execute, request.DeliveryRequest.Execute);
            Assert.Equal(prefetch, request.DeliveryRequest.Prefetch);
            Assert.Equal(notifications, request.DeliveryRequest.Notifications);
            Assert.Equal(property, request.DeliveryRequest.Property);
            Assert.Equal(telemetry, request.DeliveryRequest.Telemetry);
            Assert.Equal(trace, request.DeliveryRequest.Trace);
            Assert.Equal(expCloud, request.DeliveryRequest.ExperienceCloud);
            Assert.Equal(qaMode, request.DeliveryRequest.QaMode);
            Assert.Equal(environmentId, request.DeliveryRequest.EnvironmentId);
            Assert.Equal(impressionId, request.DeliveryRequest.ImpressionId);
            Assert.Equal(requestId, request.DeliveryRequest.RequestId);
            Assert.Equal(locationHint, request.LocationHint);
            Assert.Equal(sessionId, request.SessionId);
            Assert.Equal(DecisioningMethod.Hybrid, request.DecisioningMethod);
        }
Beispiel #15
0
        public override ExecuteResponse Execute(ExecuteRequest request, Action <ExecuteStream> stream)
        {
            StringBuilder message = new StringBuilder();

            message.AppendFormat("Execute:\n  Executable: {0}", request.Executable);
            if (request.__isset.arguments)
            {
                message.AppendFormat("\n  Arguments: {0}", request.Arguments);
            }
            if (request.__isset.timeout)
            {
                message.AppendFormat("\n  Timeout: {0} seconds", request.Timeout);
            }
            if (request.__isset.workingDirectory)
            {
                message.AppendFormat("\n  WorkingDirectory: {0}", request.WorkingDirectory);
            }
            if (request.__isset.environmentVariables)
            {
                message.Append("\n  EnvironmentVariables:");
                foreach (KeyValuePair <string, string> entry in request.EnvironmentVariables)
                {
                    message.AppendFormat("\n    {0}={1}", entry.Key, entry.Value);
                }
            }
            log.Info(message.ToString());

            int exitCode;

            try
            {
                exitCode = ProcessUtil.Execute(request.Executable,
                                               request.__isset.arguments ? request.Arguments : "",
                                               request.__isset.workingDirectory ? request.WorkingDirectory : null,
                                               request.__isset.environmentVariables ? request.EnvironmentVariables : null,
                                               line => stream(new ExecuteStream()
                {
                    StdoutLine = line
                }),
                                               line => stream(new ExecuteStream()
                {
                    StderrLine = line
                }),
                                               request.__isset.timeout ? TimeSpan.FromSeconds(request.Timeout) : (TimeSpan?)null);
            }
            catch (Exception ex)
            {
                throw OperationFailed(string.Format("Failed to execute process '{0}'.", request.Executable), ex.Message);
            }

            return(new ExecuteResponse()
            {
                ExitCode = exitCode
            });
        }
        public string LogExceptionReport(string jobId, ExecuteRequest request, Exception ex)
        {
            var serializer = new XmlSerializationService();
            var report     = new ErrorReport
            {
                JobId            = jobId,
                ExceptionMessage = ex.ToString(),
                ExecuteRequest   = request
            };

            return(Save(report));
        }
Beispiel #17
0
            ExecuteResponse Iface.Execute(ExecuteRequest request)
            {
                TProtocol oprot = CurrentOutputProtocol;
                int       seqId = CurrentSeqId;

                return(Execute(request, stream =>
                {
                    oprot.WriteMessageBegin(new TMessage("Execute", StreamMessageType, seqId));
                    stream.Write(oprot);
                    oprot.WriteMessageEnd();
                }));
            }
Beispiel #18
0
        private async Task <TResponse> CreateResult <TResponse>(ExecuteRequest <TResponse> info, HttpResponseMessage request) where TResponse : class, IResponseResult
        {
            if (request.IsSuccessStatusCode)
            {
                var content = await request.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <TResponse>(content));
            }

            var errorContent = await request.Content.ReadAsStringAsync();

            throw ApiErrorException.Create(errorContent);
        }
Beispiel #19
0
        public override Task <ExecuteResponse> Execute(ExecuteRequest request,
                                                       ServerCallContext context)
        {
            ExecuteResponse executeResponse = new ExecuteResponse();

            mutex.WaitOne();
            executeResponse.Latencies.Add(latencies);
            executeResponse.ReceivedMessages.Add(received_messages);
            latencies.Clear();
            received_messages.Clear();
            mutex.ReleaseMutex();
            return(Task.FromResult(executeResponse));
        }
        public void HandleMessage(Message message, RouterSocket serverSocket, PublisherSocket ioPub)
        {
            this.logger.Debug(string.Format("Message Content {0}", message.Content));
            ExecuteRequest executeRequest = JsonSerializer.Deserialize <ExecuteRequest>(message.Content);

            this.logger.Info(string.Format("Execute Request received with code {0}", executeRequest.Code));

            // 1: Send Busy status on IOPub
            this.SendMessageToIOPub(message, ioPub, StatusValues.Busy);

            // 2: Send execute input on IOPub
            this.SendInputMessageToIOPub(message, ioPub, executeRequest.Code);

            // 3: Evaluate the C# code
            IOPubConsole ioPubConsole = new IOPubConsole(message, ioPub, this.messageSender, this.executionCount, this.logger);

            ioPubConsole.RedirectConsole();
            string          code    = executeRequest.Code;
            ExecutionResult results = this.replEngine.Execute(code);

            ioPubConsole.CancelRedirect();

            string codeOutput     = this.GetCodeOutput(results);
            string codeHtmlOutput = this.GetCodeHtmlOutput(results);

            Dictionary <string, object> data = new Dictionary <string, object>()
            {
                { "text/plain", codeOutput },
                { "text/html", codeHtmlOutput }
            };

            DisplayData displayData = new DisplayData()
            {
                Data = data,
            };

            // 4: Send execute reply to shell socket
            this.SendExecuteReplyMessage(message, serverSocket);

            // 5: Send execute result message to IOPub
            if (results.OutputResultWithColorInformation.Any())
            {
                this.SendOutputMessageToIOPub(message, ioPub, displayData);
            }

            // 6: Send IDLE status message to IOPub
            this.SendMessageToIOPub(message, ioPub, StatusValues.Idle);

            this.executionCount += 1;
        }
Beispiel #21
0
        private static ExecuteResponse.Builder GetHeroDigest(ExecuteRequest request)
        {
            var results = new List<OperationResult>();

            foreach (Operation operation in request.OperationsList)
            {
                //var toonDigest = ToonHandle.ParseFrom(operation.RowId.Hash.ToByteArray().Skip(2).ToArray());

                OperationResult.Builder operationResult = OperationResult.CreateBuilder().SetTableId(operation.TableId);
                var value = new EntityId.Builder
                                          {

                                              IdHigh = 0x300016200004433,
                                              IdLow = 2
                                          };
                operationResult.AddData(
                    Cell.CreateBuilder()
                        .SetColumnId(operation.ColumnId)
                        .SetRowId(operation.RowId)
                        .SetVersion(1)
                        .SetData(D3.Hero.Digest.CreateBuilder().SetVersion(891)
                                     .SetHeroId(value)
                                     .SetHeroName("hazzik")
                                     .SetGbidClass(0)
                                     .SetPlayerFlags(0)
                                     .SetLevel(1)
                                     .SetVisualEquipment(new VisualEquipment.Builder().Build())
                                     .SetLastPlayedAct(0)
                                     .SetHighestUnlockedAct(0)
                                     .SetLastPlayedDifficulty(0)
                                     .SetHighestUnlockedDifficulty(0)
                                     .SetLastPlayedQuest(-1)
                                     .SetLastPlayedQuestStep(-1)
                                     .SetTimePlayed(0)
                                     .Build()
                                     .ToByteString())
                        .Build()
                    );
                results.Add(operationResult.Build());
            }

            ExecuteResponse.Builder builder = ExecuteResponse.CreateBuilder();
            foreach (OperationResult result in results)
            {
                builder.AddResults(result);
            }
            return builder;
        }
Beispiel #22
0
        public ShellServer(
            ILogger <ShellServer> logger,
            IOptions <KernelContext> context,
            IServiceProvider provider,
            IShellRouter router
            )
        {
            this.logger   = logger;
            this.context  = context.Value;
            this.provider = provider;
            this.router   = router;

            router.RegisterHandler("kernel_info_request", message => KernelInfoRequest?.Invoke(message));
            router.RegisterHandler("execute_request", message => ExecuteRequest?.Invoke(message));
            router.RegisterHandler("shutdown_request", message => ShutdownRequest?.Invoke(message));
        }
        public void SerializeExecuteRequest_ValidRequestGiven_ShouldPass()
        {
            const string expectedXml = @"<?xml version=""1.0"" encoding=""utf-8""?><wps:Execute xmlns:ows=""http://www.opengis.net/ows/2.0"" xmlns:xli=""http://www.w3.org/1999/xlink"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" service=""WPS"" version=""2.0.0"" mode=""sync"" response=""document"" xmlns:wps=""http://www.opengis.net/wps/2.0""><ows:Identifier>org.n52.wps.server.algorithm.SimpleBufferAlgorithm</ows:Identifier><wps:Input id=""data""><wps:Reference xmlns:ows=""http://www.opengis.net/ows/2.0"" xmlns:xli=""http://www.w3.org/1999/xlink"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xli:href=""http://geoprocessing.demo.52north.org:8080/geoserver/wfs?SERVICE=WFS&amp;VERSION=1.0.0&amp;REQUEST=GetFeature&amp;TYPENAME=topp:tasmania_roads&amp;SRS=EPSG:4326&amp;OUTPUTFORMAT=GML3"" schema=""http://schemas.opengis.net/gml/3.1.1/base/feature.xsd"" xmlns:wps=""http://www.opengis.net/wps/2.0"" /></wps:Input><wps:Input id=""width""><wps:Data><LiteralValue xmlns=""http://www.opengis.net/wps/2.0"">0.05</LiteralValue></wps:Data></wps:Input><wps:Output transmission=""value"" id=""result"" /></wps:Execute>";

            // Remove white spaces and new line characters for XML comparison.
            var trimmedExpectedXml = Regex.Replace(expectedXml, @"\s+", string.Empty);

            var executeRequest = new ExecuteRequest
            {
                Identifier    = "org.n52.wps.server.algorithm.SimpleBufferAlgorithm",
                ExecutionMode = ExecutionMode.Synchronous,
                ResponseType  = ResponseType.Document,
                Inputs        = new[]
                {
                    new DataInput
                    {
                        Identifier = "data",
                        Reference  = new ResourceReference
                        {
                            Href   = "http://geoprocessing.demo.52north.org:8080/geoserver/wfs?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=topp:tasmania_roads&SRS=EPSG:4326&OUTPUTFORMAT=GML3",
                            Schema = "http://schemas.opengis.net/gml/3.1.1/base/feature.xsd"
                        }
                    },
                    new DataInput
                    {
                        Identifier = "width",
                        Data       = new LiteralDataValue
                        {
                            Value = 0.05f.ToString(CultureInfo.InvariantCulture)
                        }
                    }
                },
                Outputs = new[]
                {
                    new DataOutput
                    {
                        Identifier   = "result",
                        Transmission = TransmissionMode.Value
                    }
                }
            };

            var resultXml     = _serializer.Serialize(executeRequest);
            var trimmedResult = Regex.Replace(resultXml, @"\s+", string.Empty);

            trimmedResult.Should().Be(trimmedExpectedXml);
        }
        private static ExecuteResponse.Builder GetHeroDigest(ExecuteRequest request)
        {
            var results = new List <OperationResult>();

            foreach (Operation operation in request.OperationsList)
            {
                //var toonDigest = ToonHandle.ParseFrom(operation.RowId.Hash.ToByteArray().Skip(2).ToArray());

                OperationResult.Builder operationResult = OperationResult.CreateBuilder().SetTableId(operation.TableId);
                var value = new EntityId.Builder
                {
                    IdHigh = 0x300016200004433,
                    IdLow  = 2
                };
                operationResult.AddData(
                    Cell.CreateBuilder()
                    .SetColumnId(operation.ColumnId)
                    .SetRowId(operation.RowId)
                    .SetVersion(1)
                    .SetData(D3.Hero.Digest.CreateBuilder().SetVersion(891)
                             .SetHeroId(value)
                             .SetHeroName("hazzik")
                             .SetGbidClass(0)
                             .SetPlayerFlags(0)
                             .SetLevel(1)
                             .SetVisualEquipment(new VisualEquipment.Builder().Build())
                             .SetLastPlayedAct(0)
                             .SetHighestUnlockedAct(0)
                             .SetLastPlayedDifficulty(0)
                             .SetHighestUnlockedDifficulty(0)
                             .SetLastPlayedQuest(-1)
                             .SetLastPlayedQuestStep(-1)
                             .SetTimePlayed(0)
                             .Build()
                             .ToByteString())
                    .Build()
                    );
                results.Add(operationResult.Build());
            }

            ExecuteResponse.Builder builder = ExecuteResponse.CreateBuilder();
            foreach (OperationResult result in results)
            {
                builder.AddResults(result);
            }
            return(builder);
        }
Beispiel #25
0
        public void HandleMessage(Message message, RouterSocket serverSocket, PublisherSocket ioPub)
        {
            this.logger.LogDebug(string.Format("Message Content {0}", message.Content));
            ExecuteRequest executeRequest = JsonConvert.DeserializeObject <ExecuteRequest>(message.Content);

            this.logger.LogInformation(string.Format("Execute Request received with code {0}", executeRequest.Code));

            // 1: Send Busy status on IOPub
            this.SendMessageToIOPub(message, ioPub, StatusValues.Busy);

            // 2: Send execute input on IOPub
            this.SendInputMessageToIOPub(message, ioPub, executeRequest.Code);

            // 3: Evaluate the C# code
            string code    = executeRequest.Code;
            var    results = this.replEngine.Execute(code);

            DisplayData displayData = results.GetDisplayData();

            // 4: Send execute reply to shell socket
            this.SendExecuteReplyMessage(message, serverSocket);


            // 5: Send execute result message to IOPub
            if (results.Output.Any())
            {
                this.SendOutputMessageToIOPub(message, ioPub, displayData);
            }

            if (results.Exceptions.Any())
            {
                this.SendExecuteErrorMessage(message, serverSocket);
                foreach (var ex in results.Exceptions)
                {
                    this.SendErrorToIOPub(message, ioPub, ex);
                }
            }

            // 6: Send IDLE status message to IOPub
            this.SendMessageToIOPub(message, ioPub, StatusValues.Idle);

            if (executeRequest.StoreHistory)
            {
                this.executionCount += 1;
            }
        }
Beispiel #26
0
        private async Task <TResponse> ExecutePostAsync <TResponse>(ExecuteRequest <TResponse> info) where TResponse : class, IResponseResult
        {
            var json = string.Empty;

            if (info.Data != null)
            {
                json = JsonConvert.SerializeObject(info.Data);
            }

            var buffer      = Encoding.UTF8.GetBytes(json);
            var byteContent = new ByteArrayContent(buffer);

            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var request = await _client.PostAsync(CreateEndpoint(info), byteContent);

            return(await CreateResult(info, request));
        }
Beispiel #27
0
        public ExecuteResponse Execute(ExecuteRequest executeRequest)
        {
            Contract.Requires(executeRequest != null);
            Contract.Requires(executeRequest.Command != null);
            Contract.Ensures(Contract.Result <ExecuteResponse>() != null);
            Contract.EnsuresOnThrow <FaultException <CommandWebServiceFault> >(Contract.Result <ExecuteResponse>() == null);

            try
            {
                _service.Execute(executeRequest.Command);
                return(new ExecuteResponse());
            }
            catch (Exception ex)
            {
                throw new FaultException <CommandWebServiceFault>(
                          new CommandWebServiceFault(executeRequest.Command, ex), "An exception occured while trying to execute the command");
            }
        }
Beispiel #28
0
        private void executeCode(string code)
        {
            try
            {
                ExecuteRequest request = new ExecuteRequest();
                request.Code = code;
                var response = mrsServer.ExecuteCode(sessionId, request);

                if (response.Success == false)
                {
                    throw new Exception(response.ErrorMessage);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Execute Code Failed : " + e.Message);
            }
        }
 protected ActionResult ExecuteRequestAndHandle(ExecuteRequest executeRequest, int responseCode)
 {
     try
     {
         return(RestErrorHandler.Handle(() =>
         {
             Log.Info(string.Format("Entering {0} method", executeRequest.Method));
             executeRequest.Invoke();
             var response = this.StatusCode(responseCode);
             Log.Info(string.Format("Leaving {0} method", executeRequest.Method));
             return response;
         }));
     }
     catch (Exception ex)
     {
         return(this.ProcessException(ex));
     }
 }
Beispiel #30
0
        public void Service_Execute_Zorgtoeslag_From_Url()
        {
            APIServiceController controller = new APIServiceController(InitMoqLogger(), new YamlScriptController(), InitMoqRoutingController());
            var executeRequest = new ExecuteRequest()
            {
                Config     = YamlTestFileLoader.Load(@"Rijksoverheid/Zorgtoeslag.yaml"),
                Parameters = new ParametersCollection()
                {
                    new ClientParameter("alleenstaande", "ja", TypeInference.InferenceResult.TypeEnum.Boolean, "Dummy")
                }
            };

            var payload = JsonConvert.SerializeObject(executeRequest);
            var result  = controller.Execute(executeRequest).Result;

            Assert.True(result.Questions.Parameters.Count == 1);
            Assert.True(result.Questions.Parameters[0].Name == "woonland");
        }
Beispiel #31
0
        public async Task <ActionResult <BoolResult> > Execute([FromBody] ExecuteRequest request)
        {
            if (!await _authManager.HasAppPermissionsAsync(DatabaseManager.PermissionsExecute))
            {
                return(Unauthorized());
            }

            if (request.SecurityKey != _settingsManager.SecurityKey)
            {
                return(this.Error("SecurityKey 输入错误!"));
            }

            await _databaseManager.ExecuteAsync(request.Execute);

            return(new BoolResult
            {
                Value = true
            });
        }
Beispiel #32
0
 public override void Execute(IRpcController controller, ExecuteRequest request, Action<ExecuteResponse> done)
 {
     ExecuteResponse.Builder response;
     switch (request.QueryName)
     {
         case "QueryAccountDigest":
             response = GetAccountDigest(request);
             break;
         case "LoadAccountDigest":
             response = LoadAccountDigest(request);
             break;
         case "GetHeroDigests":
             response = GetHeroDigest(request);
             break;
         default:
             response = new ExecuteResponse.Builder();
             break;
     }
     done(response.Build());
 }
Beispiel #33
0
            public ExecuteResponse Execute(ExecuteRequest request, Action<ExecuteStream> handleStream)
            {
                send_Execute(request);

                for (; ; )
                {
                    TMessage msg = iprot_.ReadMessageBegin();
                    if (msg.Type == TMessageType.Exception)
                    {
                        TApplicationException x = TApplicationException.Read(iprot_);
                        iprot_.ReadMessageEnd();
                        throw x;
                    }

                    if (msg.Type == StreamMessageType)
                    {
                        ExecuteStream stream = new ExecuteStream();
                        stream.Read(iprot_);
                        iprot_.ReadMessageEnd();
                        handleStream(stream);
                        continue;
                    }

                    Execute_result result = new Execute_result();
                    result.Read(iprot_);
                    iprot_.ReadMessageEnd();
                    if (result.__isset.success)
                    {
                        return result.Success;
                    }
                    if (result.__isset.ex)
                    {
                        throw result.Ex;
                    }
                    throw new TApplicationException(TApplicationException.ExceptionType.MissingResult, "Execute failed: unknown result");
                }
            }
Beispiel #34
0
        public override ExecuteResponse Execute(ExecuteRequest request, Action<ExecuteStream> stream)
        {
            StringBuilder message = new StringBuilder();
            message.AppendFormat("Execute:\n  Executable: {0}", request.Executable);
            if (request.__isset.arguments)
                message.AppendFormat("\n  Arguments: {0}", request.Arguments);
            if (request.__isset.timeout)
                message.AppendFormat("\n  Timeout: {0} seconds", request.Timeout);
            if (request.__isset.workingDirectory)
                message.AppendFormat("\n  WorkingDirectory: {0}", request.WorkingDirectory);
            if (request.__isset.environmentVariables)
            {
                message.Append("\n  EnvironmentVariables:");
                foreach (KeyValuePair<string, string> entry in request.EnvironmentVariables)
                    message.AppendFormat("\n    {0}={1}", entry.Key, entry.Value);
            }
            log.Info(message.ToString());

            int exitCode;
            try
            {
                exitCode = ProcessUtil.Execute(request.Executable,
                    request.__isset.arguments ? request.Arguments : "",
                    request.__isset.workingDirectory ? request.WorkingDirectory : null,
                    request.__isset.environmentVariables ? request.EnvironmentVariables : null,
                    line => stream(new ExecuteStream() { StdoutLine = line }),
                    line => stream(new ExecuteStream() { StderrLine = line }),
                    request.__isset.timeout ? TimeSpan.FromSeconds(request.Timeout) : (TimeSpan?) null);
            }
            catch (Exception ex)
            {
                throw OperationFailed(string.Format("Failed to execute process '{0}'.", request.Executable), ex.Message);
            }

            return new ExecuteResponse() { ExitCode = exitCode };
        }
Beispiel #35
0
 public override void Execute(IRpcController controller, ExecuteRequest request, Action<ExecuteResponse> done)
 {
     ProtoOutputBuffer.Write(request.GetType(), request.ToString());
 }
Beispiel #36
0
        public int Execute(string executable, string arguments, string workingDirectory,
            IDictionary<string, string> environmentVariables,
            LineHandler stdoutHandler, LineHandler stderrHandler, TimeSpan? timeout)
        {
            CheckProfileCanResolveSlave();

            StringBuilder message = new StringBuilder();
            message.AppendLine("Executing remote command: ");
            message.AppendFormat("  Executable  : {0}\n", executable);
            message.AppendFormat("  Arguments   : {0}\n", arguments);

            if (workingDirectory != null)
                message.AppendFormat("  Directory   : {0}\n", workingDirectory);

            if (environmentVariables != null)
            {
                message.AppendLine("  Environment :");
                foreach (KeyValuePair<string, string> entry in environmentVariables)
                    message.AppendFormat("    {0}={1}\n", entry.Key, entry.Value);
            }

            Log(message.ToString());

            ExecuteRequest request = new ExecuteRequest();
            request.Executable = executable;
            if (arguments.Length != 0)
                request.Arguments = arguments;
            if (workingDirectory != null)
                request.WorkingDirectory = workingDirectory;
            if (environmentVariables != null)
                request.EnvironmentVariables = new Dictionary<string, string>(environmentVariables);
            if (timeout.HasValue)
                request.Timeout = (int) timeout.Value.TotalSeconds;

            ExecuteResponse response = GetSlaveClient().Execute(request,
                stream =>
                {
                    if (stream.__isset.stdoutLine)
                        stdoutHandler(stream.StdoutLine);
                    if (stream.__isset.stderrLine)
                        stderrHandler(stream.StderrLine);
                });
            return response.ExitCode;
        }
Beispiel #37
0
 public abstract ExecuteResponse Execute(ExecuteRequest request, Action<ExecuteStream> sendStream);
Beispiel #38
0
 private ExecuteResponse.Builder GetAccountDigest(ExecuteRequest request)
 {
     ExecuteResponse.Builder builder = ExecuteResponse.CreateBuilder();
     foreach (OperationResult result in request.OperationsList.Select(operation => CreateOperationResult(operation, 1, AccountDigest.ToByteString())))
     {
         builder.AddResults(result);
     }
     return builder;
 }
Beispiel #39
0
		public override void Execute(Google.ProtocolBuffers.IRpcController controller, ExecuteRequest request, Action<ExecuteResponse> done) {
			var response = ExecuteResponse.CreateBuilder();
			
			foreach (var op in request.OperationsList) {

				var result = OperationResult.CreateBuilder();
				result.SetTableId(op.TableId);

				var data = Cell.CreateBuilder();
				data.SetColumnId(op.ColumnId);
				data.SetRowId(op.RowId);

				result.SetErrorCode(1);

				if (request.QueryName == "GetGameAccountSettings") {
					result.SetErrorCode(4);
				} else if (request.QueryName == "GetHeroDigests") {
					var hero_digest = D3.Hero.Digest.CreateBuilder();
					hero_digest.SetVersion(891);
					hero_digest.SetHeroId(D3.OnlineService.EntityId.CreateBuilder().SetIdHigh(216174302532224051).SetIdLow(2345959482769161802));
					hero_digest.SetHeroName("poop");
					hero_digest.SetGbidClass(-930376119);
					hero_digest.SetLevel(1);
					hero_digest.SetPlayerFlags(0);
					var eq = VisualEquipment.CreateBuilder();
					for (int i = 0; i < 8; i++) {
						eq.AddVisualItem(VisualItem.CreateBuilder().SetEffectLevel(0));
					}
					hero_digest.SetVisualEquipment(eq);
					//hero_digest.SetQuestHistory(QuestHistoryEntry
					hero_digest.SetLastPlayedAct(0);
					hero_digest.SetHighestUnlockedAct(0);
					hero_digest.SetLastPlayedQuest(-1);
					hero_digest.SetLastPlayedQuestStep(-1);
					hero_digest.SetLastPlayedDifficulty(0);
					hero_digest.SetTimePlayed(0);
					hero_digest.SetHighestUnlockedDifficulty(0);
					data.SetData(hero_digest.Build().ToByteString());
				} else if (request.QueryName == "LoadAccountDigest") {
					var account_digest = D3.Account.Digest.CreateBuilder();
					account_digest.SetVersion(1);

					// no last played hero
					var last_played = D3.OnlineService.EntityId.CreateBuilder();
					last_played.SetIdHigh(216174302532224051);
					last_played.SetIdLow(2345959482769161802);
					account_digest.SetLastPlayedHeroId(last_played);

					// default banner
					var banner = D3.Account.BannerConfiguration.CreateBuilder();
					banner.SetBannerIndex(0).SetSigilMain(0).SetSigilAccent(0).SetPatternColorIndex(0).SetBackgroundColorIndex(0).SetSigilColorIndex(0)
						.SetPlacementIndex(0).SetPattern(0).SetUseSigilVariant(false);
					account_digest.SetBannerConfiguration(banner);

					// default flags
					account_digest.SetFlags((uint)D3.Account.Digest.Types.Flags.HARDCORE_HERO_UNLOCKED);

					data.SetData(account_digest.Build().ToByteString());
				} else if (request.QueryName == "GetToonSettings") {
					//response.SetErrorCode(4);
				} else {
					throw new ArgumentException("Invalid query name: " + request.QueryName);
				}

				result.AddData(data);

				response.AddResults(result);
			}


			done(response.Build());
		}
        /// <summary>
        /// This request is used to execute a PreparedStatement, optionally with values to bind to the parameters in the Statement.
        /// </summary>
        public async Task<ExecuteResponse> ExecuteRequestAsync(StatementHandle statementHandle, pbc::RepeatedField<TypedValue> parameterValues, ulong firstFrameMaxSize, bool hasParameterValues, RequestOptions options)
        {
            ExecuteRequest req = new ExecuteRequest
            {
                StatementHandle = statementHandle,
                ParameterValues = parameterValues,
                FirstFrameMaxSize = firstFrameMaxSize,
                HasParameterValues = hasParameterValues
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "ExecuteRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "ExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            statementHandle.ConnectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteResponse res = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
Beispiel #41
0
            ExecuteResponse Iface.Execute(ExecuteRequest request)
            {
                TProtocol oprot = CurrentOutputProtocol;
                int seqId = CurrentSeqId;

                return Execute(request, stream =>
                {
                    oprot.WriteMessageBegin(new TMessage("Execute", StreamMessageType, seqId));
                    stream.Write(oprot);
                    oprot.WriteMessageEnd();
                });
            }