Exemplo n.º 1
0
 private void Cancel_Click(object sender, EventArgs e)
 {
     if (MessageBox.Show(this, "Are you sure you want to stop the process? This operation cannot be undone.", "Confirmation required.", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
     {
         CancellationRequest?.Invoke(this, EventArgs.Empty);
     }
 }
Exemplo n.º 2
0
 public CancellationResponse Cancel(CancellationRequest request)
 {
     return(new CancellationResponse {
         ConfirmationNumber = request.ConfirmationNumber,
         BookingNumber = request.BookingNumber,
         StatusCode = BookingStatus.Cancelled
     });
 }
Exemplo n.º 3
0
        public void TestCancellationRequest()
        {
            var request = new CancellationRequest {
                BookingNumber = "D35F673C-728F-447C-9872-F6F8D05CE0C7", ConfirmationNumber = "100", LastName = "Narayanappa"
            };
            var response = new WorkerRepository().CancelBooking(request);

            Assert.IsNotNull(response);
        }
        public ActionResult CancelMandateResult(CancellationRequest model)
        {
            if (String.IsNullOrEmpty(model.MessageId))
            {
                model.MessageId = MessageIdGenerator.New();
            }

            var response = b2bCommunicator.Cancel(model);

            return(View(response));
        }
Exemplo n.º 5
0
 private bool WaitGoNext()
 {
     CanGoNext = true;
     using (var wait = new EventWaitHandle(false, EventResetMode.ManualReset, "WAIT_NEXT_3_DAYS"))
     {
         while (!wait.WaitOne(1000))
         {
             CancellationRequest.ThrowIfCancellationRequested();
         }
     }
     CanGoNext = false;
     return(true);
 }
Exemplo n.º 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotBranchStoreUnlessWeHaveCopiedDownAReplacement() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotBranchStoreUnlessWeHaveCopiedDownAReplacement()
        {
            // Given
            StoreCopyClient storeCopyClient = mock(typeof(StoreCopyClient));

            doAnswer(invocation =>
            {
                MoveAfterCopy moveAfterCopy = invocation.getArgument(2);
                moveAfterCopy.move(Stream.empty(), new File(""), Function.identity());
                return(null);
            }).when(storeCopyClient).copyStore(any(typeof(StoreCopyClient.StoreCopyRequester)), any(typeof(CancellationRequest)), any(typeof(MoveAfterCopy)));

            PageCache pageCacheMock = mock(typeof(PageCache));
            PagedFile pagedFileMock = mock(typeof(PagedFile));

            when(pagedFileMock.LastPageId).thenReturn(1L);
            when(pageCacheMock.Map(any(typeof(File)), anyInt())).thenReturn(pagedFileMock);

            SwitchToSlaveCopyThenBranch switchToSlave = NewSwitchToSlaveSpy(pageCacheMock, storeCopyClient);

            URI masterUri = new URI("cluster://localhost?serverId=1");
            URI me        = new URI("cluster://localhost?serverId=2");
            CancellationRequest cancellationRequest = Org.Neo4j.Helpers.CancellationRequest_Fields.NeverCancelled;

            MasterClient masterClient = mock(typeof(MasterClient));

            when(masterClient.Handshake(anyLong(), any(typeof(StoreId)))).thenThrow(new BranchedDataException(""));

            TransactionIdStore transactionIdStore = mock(typeof(TransactionIdStore));

            when(transactionIdStore.LastCommittedTransaction).thenReturn(new TransactionId(42, 42, 42));
            when(transactionIdStore.LastCommittedTransactionId).thenReturn(Org.Neo4j.Kernel.impl.transaction.log.TransactionIdStore_Fields.BASE_TX_ID);

            // When
            BranchedDataPolicy branchPolicy = mock(typeof(BranchedDataPolicy));

            switchToSlave.StopServicesAndHandleBranchedStore(branchPolicy, masterUri, me, cancellationRequest);

            // Then
            InOrder inOrder = Mockito.inOrder(storeCopyClient, branchPolicy);

            inOrder.verify(storeCopyClient).copyStore(any(typeof(StoreCopyClient.StoreCopyRequester)), any(typeof(CancellationRequest)), any(typeof(MoveAfterCopy)));
            inOrder.verify(branchPolicy).handle(TestDirectory.databaseDir(), pageCacheMock, NullLogService.Instance);
        }
Exemplo n.º 7
0
        private void InternalExecute()
        {
            while (!CancellationRequest.IsCancellationRequested)
            {
                Controller.PressAndRelease(ButtonType.A, 50, 900);       // 巣穴を選択

                Clock.DaysCount = 3;
                while (Clock.DaysCount > 0)
                {
                    Controller.PressAndRelease(ButtonType.A, 50, 900);       // みんなで挑戦選択
                    Controller.PressAndRelease(ButtonType.A, 50, 2700);      // ボールがありません>はい選択(ボールがなければ)

                    Clock.IncreaseOneDayFromGameScreen();

                    Controller.PressAndRelease(ButtonType.B, 50, 900);   // やめる
                    Controller.PressAndRelease(ButtonType.A, 50, 4900);  // 募集をやめる>はい選択

                    CancellationRequest.ThrowIfCancellationRequested();

                    Controller.PressAndRelease(ButtonType.A, 50, 700);   // 巣穴を選択
                    Controller.PressAndRelease(ButtonType.A, 50, 700);   // エネルギーがあふれでてる
                    Controller.PressAndRelease(ButtonType.A, 50, 900);   // ワット手に入れた

                    CancellationRequest.ThrowIfCancellationRequested();
                }

                GameCapture.SaveFrame(null);
                bool stop = CheckFourthDayPokemon();
                if (stop)
                {
                    WaitGoNext();
                }
                CheckSearchTemplates();

                Controller.PressAndRelease(ButtonType.Home, 50, 600);
                Controller.PressAndRelease(ButtonType.X, 50, 250);
                Controller.PressAndRelease(ButtonType.A, 50, 3500);

                Controller.PressAndRelease(ButtonType.A, 50, 1250);
                Controller.PressAndRelease(ButtonType.A, 50, 19000);
                Controller.PressAndRelease(ButtonType.A, 50, 9000);
            }
        }
Exemplo n.º 8
0
        public string GetTransactionRequest(CancellationRequest cancellationRequest, string containedData)
        {
            VerifyExpirationPeriod(cancellationRequest.ExpirationPeriod);

            var containedDocument = new XmlDocument();

            containedDocument.LoadXml(containedData);

            var acquirerTrxReq = new AcquirerTrxReq
            {
                createDateTimestamp = Now(),
                productID           = this.LocalInstrumentCode == Instrumentation.Core ? ProductId_CORE : ProductId_B2B,
                version             = "1.0.0",

                Merchant = new AcquirerTrxReqMerchant
                {
                    merchantID        = Configuration.Contract.Id,
                    subID             = Configuration.Contract.SubId.ToString(CultureInfo.InvariantCulture),
                    merchantReturnURL = Configuration.Merchant.ReturnUrl
                },

                Issuer = new AcquirerTrxReqIssuer
                {
                    issuerID = cancellationRequest.DebtorBankId
                },

                Transaction = new AcquirerTrxReqTransaction
                {
                    entranceCode = cancellationRequest.EntranceCode,

                    expirationPeriod = cancellationRequest.ExpirationPeriod.HasValue ? XmlConvert.ToString(cancellationRequest.ExpirationPeriod.Value) : null,
                    language         = cancellationRequest.Language.ToString(),
                    container        = new Transactioncontainer
                    {
                        Any = new[] { containedDocument.DocumentElement }
                    }
                }
            };

            return(ProcessDateTimes(acquirerTrxReq.Serialize()));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Cancels a single order item.
        /// </summary>
        /// <param name="orderItemId">The order item identifier.</param>
        /// <param name="cancellationReason">The cancellation reason.</param>
        /// <returns>StatusResponse.</returns>
        public async Task <StatusResponse> CancelOrderItemAsync(
            string orderItemId,
            CancellationReason cancellationReason = null)
        {
            cancellationReason ??= new CancellationReason();
            var cancellationRequest = new CancellationRequest()
            {
                OrderItems = new[]
                {
                    new OrderItemCancellation()
                    {
                        OrderItemId = orderItemId,
                        ReasonCode  = cancellationReason.ReasonValue
                    }
                }
            };

            return(await GetApiResult <StatusResponse>(
                       HttpMethod.Put,
                       $"{EndPoints.BaseUriApiCalls}{EndPoints.Orders}/cancellation",
                       cancellationRequest
                       ));
        }
Exemplo n.º 10
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: void copyStoreFromMaster(org.neo4j.kernel.ha.com.slave.MasterClient masterClient, org.neo4j.helpers.CancellationRequest cancellationRequest, org.neo4j.com.storecopy.MoveAfterCopy moveAfterCopy) throws Throwable
        internal virtual void CopyStoreFromMaster(MasterClient masterClient, CancellationRequest cancellationRequest, MoveAfterCopy moveAfterCopy)
        {
            try
            {
                UserLog.info("Copying store from master");
                StoreCopyClient.StoreCopyRequester requester = new StoreCopyRequesterAnonymousInnerClass(this, masterClient);
                MoveAfterCopy moveAfterCopyWithLogging       = (moves, fromDirectory, toDirectory) =>
                {
                    UserLog.info("Copied store from master to " + fromDirectory);
                    MsgLog.info("Starting post copy operation to move store from " + fromDirectory + " to " + toDirectory);
                    moveAfterCopy.Move(moves, fromDirectory, toDirectory);
                };
                _storeCopyClient.copyStore(requester, cancellationRequest, moveAfterCopyWithLogging);

                StartServicesAgain();
                UserLog.info("Finished copying store from master");
            }
            catch (Exception t)
            {
                // Delete store so that we can copy from master without conflicts next time
                CleanStoreDir();
                throw t;
            }
        }
Exemplo n.º 11
0
        private void ProcessRequests(object notUsed)
        {
            try
            {
                // process rules and run handlers as required
                BasicServerState state = this.GetState();
                if (state != BasicServerState.Running)
                {
                    return;
                }

                // subscription is ready and callback flood has stopped
                List <InternalRequest> existingRequests  = new List <InternalRequest>();
                List <InternalRequest> enqueuedRequests  = new List <InternalRequest>();
                List <InternalRequest> cancelledRequests = new List <InternalRequest>();
                var requestItems      = _AssignedRequestsCache.Items;
                var cancellationItems = _CancellationsCache.Items;
                var responseItems     = _WorkerResponseCache.Items;
                _InternalRequests.Locked((internalRequests) =>
                {
                    // - process responses
                    foreach (ICoreItem item in responseItems)
                    {
                        try
                        {
                            WorkerResponse response = (WorkerResponse)item.Data;
                            Guid requestId          = Guid.Parse(response.RequestId);
                            InternalRequest internalRequest;
                            if (!internalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Status      = response.Status;
                            internalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process requests
                    foreach (ICoreItem item in requestItems)
                    {
                        try
                        {
                            AssignedWorkflowRequest request = (AssignedWorkflowRequest)item.Data;
                            Guid requestId = Guid.Parse(request.RequestId);
                            InternalRequest internalRequest;
                            if (!internalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.ExternalRequest = request;
                            internalRequests[requestId]     = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process cancellations
                    foreach (ICoreItem item in cancellationItems)
                    {
                        try
                        {
                            CancellationRequest cancellation = (CancellationRequest)item.Data;
                            Guid requestId = Guid.Parse(cancellation.RequestId);
                            InternalRequest internalRequest;
                            if (!internalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Cancellation = cancellation;
                            internalRequests[requestId]  = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }

                    // determine requests to be launched or cancelled
                    foreach (InternalRequest internalRequest in internalRequests.Values)
                    {
                        if ((internalRequest.ExternalRequest != null) &&
                            ((internalRequest.Status == RequestStatusEnum.Undefined) || (internalRequest.Status == RequestStatusEnum.Enqueued)))
                        {
                            // find requests to launch
                            if (internalRequest.Cancellation == null)
                            {
                                if (internalRequest.Status != RequestStatusEnum.Enqueued)
                                {
                                    // new request
                                    internalRequest.Status = RequestStatusEnum.Enqueued;
                                    enqueuedRequests.Add(internalRequest);
                                }
                                existingRequests.Add(internalRequest);
                            }
                            else
                            {
                                // cancelled
                                internalRequest.Status = RequestStatusEnum.Cancelled;
                                cancelledRequests.Add(internalRequest);
                            }
                        }
                    }
                });

                // publish status for cancelled and enqueued requests
                foreach (InternalRequest request in cancelledRequests)
                {
                    PublishWorkerResponse(_IntClient.Target, request, HostInstance);
                }

                // now find handlers to launch
                foreach (InternalRequest request in enqueuedRequests)
                {
                    // publish enqueued status
                    PublishWorkerResponse(_IntClient.Target, request, HostInstance);
                }
                foreach (InternalRequest request in existingRequests)
                {
                    // launch if handler available
                    int count = Interlocked.Decrement(ref _HandlersAvailable);
                    if (count >= 0)
                    {
                        Interlocked.Increment(ref _AvailabilityChangeCount);
                        Interlocked.Increment(ref _HandlersExecuting);
                        // publish launched status
                        request.Status = RequestStatusEnum.Launched;
                        PublishWorkerResponse(_IntClient.Target, request, HostInstance);
                        // launch
                        ThreadPool.QueueUserWorkItem(Launch, new LaunchPackage(_IntClient, request));
                    }
                    else
                    {
                        Interlocked.Increment(ref _HandlersAvailable);
                    }
                }

                // publish availability (throttled)
                int changeCount = Interlocked.Exchange(ref _AvailabilityChangeCount, 0);
                if ((changeCount > 0) || ((DateTimeOffset.Now - _AvailabilityLastPublished) > TimeSpan.FromSeconds(5)))
                {
                    _IntClient.Target.SaveObject <WorkerAvailability>(new WorkerAvailability()
                    {
                        WorkerHostComputer = Environment.MachineName,
                        WorkerHostInstance = this.HostInstance,
                        AvailableNodeCount = Interlocked.Add(ref _HandlersAvailable, 0)
                    });
                    _AvailabilityLastPublished = DateTimeOffset.Now;
                }
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
        }
Exemplo n.º 12
0
 public JsonResult Cancel(CancellationRequest request)
 {
     return(Json(canceller.Cancel(request)));
 }
Exemplo n.º 13
0
        /// <summary>
        /// Envia uma requisição-cancelamento para o webservice Cielo para cancelar uma transação
        /// </summary>
        /// <returns>A transação com o respectivo status retornada pela Cielo</returns>
        /// <param name="transaction">A transação que será cancelada</param>
        /// <param name="total">Total do cancelamento</param>
        public Transaction cancellationRequest(Transaction transaction, int total)
        {
            CancellationRequest request = CancellationRequest.create(transaction, total);

            return(TransacaoElement.unserialize(transaction, sendHttpRequest(serialize(request))));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Envia uma requisição-cancelamento para o webservice Cielo para cancelar uma transação
        /// </summary>
        /// <returns>A transação com o respectivo status retornada pela Cielo</returns>
        /// <param name="transaction">A transação que será cancelada</param>
        /// <param name="total">Total do cancelamento</param>
        public Transaction cancellationRequest(string tid, int total, Merchant merchant = null)
        {
            CancellationRequest request = CancellationRequest.create(tid, merchant ?? this.merchant, total);

            return(TransacaoElement.unserialize(null, sendHttpRequest(serialize(request))));
        }
Exemplo n.º 15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: abstract void checkDataConsistency(org.neo4j.kernel.ha.com.slave.MasterClient masterClient, org.neo4j.kernel.impl.transaction.log.TransactionIdStore txIdStore, org.neo4j.storageengine.api.StoreId storeId, java.net.URI masterUri, java.net.URI me, org.neo4j.helpers.CancellationRequest cancellationRequest) throws Throwable;
        internal abstract void CheckDataConsistency(MasterClient masterClient, TransactionIdStore txIdStore, StoreId storeId, URI masterUri, URI me, CancellationRequest cancellationRequest);
Exemplo n.º 16
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private boolean executeConsistencyChecks(org.neo4j.kernel.impl.transaction.log.TransactionIdStore txIdStore, java.net.URI masterUri, java.net.URI me, org.neo4j.storageengine.api.StoreId storeId, org.neo4j.helpers.CancellationRequest cancellationRequest) throws Throwable
        private bool ExecuteConsistencyChecks(TransactionIdStore txIdStore, URI masterUri, URI me, StoreId storeId, CancellationRequest cancellationRequest)
        {
            LifeSupport consistencyCheckLife = new LifeSupport();

            try
            {
                MasterClient masterClient = NewMasterClient(masterUri, me, storeId, consistencyCheckLife);
                consistencyCheckLife.Start();

                if (cancellationRequest.CancellationRequested())
                {
                    return(false);
                }

                CheckDataConsistency(masterClient, txIdStore, storeId, masterUri, me, cancellationRequest);
            }
            finally
            {
                consistencyCheckLife.Shutdown();
            }
            return(true);
        }
Exemplo n.º 17
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private java.net.URI startHaCommunication(org.neo4j.kernel.lifecycle.LifeSupport haCommunicationLife, org.neo4j.kernel.NeoStoreDataSource neoDataSource, java.net.URI me, java.net.URI masterUri, org.neo4j.storageengine.api.StoreId storeId, org.neo4j.helpers.CancellationRequest cancellationRequest) throws IllegalArgumentException, InterruptedException
        private URI StartHaCommunication(LifeSupport haCommunicationLife, NeoStoreDataSource neoDataSource, URI me, URI masterUri, StoreId storeId, CancellationRequest cancellationRequest)
        {
            MasterClient master = NewMasterClient(masterUri, me, neoDataSource.StoreId, haCommunicationLife);

            TransactionObligationFulfiller obligationFulfiller   = ResolveDatabaseDependency(typeof(TransactionObligationFulfiller));
            UpdatePullerScheduler          updatePullerScheduler = _updatePullerFactory.createUpdatePullerScheduler(UpdatePuller);

            Slave slaveImpl = new SlaveImpl(obligationFulfiller);

            SlaveServer server = _slaveServerFactory.apply(slaveImpl);

            if (cancellationRequest.CancellationRequested())
            {
                MsgLog.info("Switch to slave cancelled, unable to start HA-communication");
                return(null);
            }

            _masterDelegateHandler.Delegate = master;

            haCommunicationLife.Add(updatePullerScheduler);
            haCommunicationLife.Add(server);
            haCommunicationLife.Start();

            /*
             * Take the opportunity to catch up with master, now that we're alone here, right before we
             * drop the availability guard, so that other transactions might start.
             */
            if (!CatchUpWithMaster(UpdatePuller))
            {
                return(null);
            }

            URI slaveHaURI = CreateHaURI(me, server);

            _clusterMemberAvailability.memberIsAvailable(HighAvailabilityModeSwitcher.SLAVE, slaveHaURI, storeId);

            return(slaveHaURI);
        }
Exemplo n.º 18
0
 public void OnCancellationRequest(object sender, EventArgs e)
 {
     CancellationRequest?.Invoke(sender, e);
 }
Exemplo n.º 19
0
        public CancellationResponse CancelBooking(CancellationRequest request)
        {
            var dbAccess = new DbAccess();

            return(dbAccess.CancelBooking(request));
        }
        public string GetCancel(CancellationRequest cancellationRequest)
        {
            VerifyMaxAmount(cancellationRequest.MaxAmount);

            var eMandate = new p11.Document
            {
                MndtCxlReq = new p11.MandateCancellationRequestV04
                {
                    GrpHdr = new p11.GroupHeader47
                    {
                        CreDtTm = Now(),
                        MsgId   = cancellationRequest.MessageId
                    },
                    UndrlygCxlDtls = new []
                    {
                        new p11.MandateCancellation4
                        {
                            CxlRsn = new p11.PaymentCancellationReason1
                            {
                                Rsn = new p11.MandateReason1Choice
                                {
                                    ItemElementName = p11.ItemChoiceType4.Cd,
                                    Item            = "MD16"
                                }
                            },
                            OrgnlMndt = new p11.OriginalMandate3Choice
                            {
                                Item = new p11.Mandate5
                                {
                                    MndtId    = cancellationRequest.EMandateId,
                                    MndtReqId = "NOTPROVIDED",
                                    Tp        = new p11.MandateTypeInformation1
                                    {
                                        SvcLvl = new p11.ServiceLevel8Choice
                                        {
                                            ItemElementName = p11.ItemChoiceType5.Cd,
                                            Item            = "SEPA"
                                        },
                                        LclInstrm = new p11.LocalInstrument2Choice
                                        {
                                            ItemElementName = p11.ItemChoiceType6.Cd,
                                            Item            = Enum.GetName(typeof(Instrumentation), this.LocalInstrumentCode).ToUpper()
                                        }
                                    },
                                    Ocrncs = new p11.MandateOccurrences3
                                    {
                                        SeqTp = (p11.SequenceType2Code)cancellationRequest.SequenceType,
                                        //Frqcy = new p11.Frequency21Choice
                                        //{
                                        //    Item = new p11.FrequencyPeriod1
                                        //    {
                                        //        Tp = p11.Frequency6Code.YEAR,
                                        //        CntPerPrd = 1.0
                                        //    }
                                        //}
                                    },
                                    MaxAmt = (cancellationRequest.MaxAmount.HasValue)?
                                             new p11.ActiveOrHistoricCurrencyAndAmount {
                                        Ccy = "EUR", Value = cancellationRequest.MaxAmount.Value
                                    } : null,
                                    Rsn = cancellationRequest.EMandateReason != null? new p11.MandateSetupReason1Choice
                                    {
                                        ItemElementName = p11.ItemChoiceType7.Prtry,
                                        Item            = cancellationRequest.EMandateReason != null? cancellationRequest.EMandateReason : String.Empty
                                    } : null,
                                    Cdtr = new p11.PartyIdentification43
                                    {
                                    },
                                    Dbtr = new p11.PartyIdentification43
                                    {
                                        Id = cancellationRequest.DebtorReference != null? new p11.Party11Choice
                                        {
                                            Item = new p11.PersonIdentification5
                                            {
                                                Othr = new []
                                                {
                                                    new p11.GenericPersonIdentification1
                                                    {
                                                        Id = cancellationRequest.DebtorReference
                                                    }
                                                }
                                            }
                                        } : null,
                                    },
                                    DbtrAcct = new p11.CashAccount24
                                    {
                                        Id = new p11.AccountIdentification4Choice
                                        {
                                            Item = cancellationRequest.OriginalIban
                                        }
                                    },
                                    DbtrAgt = new p11.BranchAndFinancialInstitutionIdentification5
                                    {
                                        FinInstnId = new p11.FinancialInstitutionIdentification8
                                        {
                                            BICFI = cancellationRequest.DebtorBankId
                                        }
                                    },
                                    RfrdDoc = cancellationRequest.PurchaseId != null? new []
                                    {
                                        new p11.ReferredDocumentInformation6
                                        {
                                            Tp = new p11.ReferredDocumentType4
                                            {
                                                CdOrPrtry = new p11.ReferredDocumentType3Choice
                                                {
                                                    Item = cancellationRequest.PurchaseId
                                                }
                                            }
                                        }
                                    }: null
                                }
                            }
                        }
                    }
                }
            };

            return(ProcessDateTimes(eMandate.Serialize()));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Performs a switch to the slave state. Starts the communication endpoints, switches components to the slave state
        /// and ensures that the current database is appropriate for this cluster. It also broadcasts the appropriate
        /// Slave Is Available event
        /// </summary>
        /// <param name="haCommunicationLife"> The LifeSupport instance to register the network facilities required for
        ///                            communication with the rest of the cluster </param>
        /// <param name="me"> The URI this instance must bind to </param>
        /// <param name="masterUri"> The URI of the master for which this instance must become slave to </param>
        /// <param name="cancellationRequest"> A handle for gracefully aborting the switch </param>
        /// <returns> The URI that was broadcasted as the slave endpoint or null if the task was cancelled </returns>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public java.net.URI switchToSlave(org.neo4j.kernel.lifecycle.LifeSupport haCommunicationLife, java.net.URI me, java.net.URI masterUri, org.neo4j.helpers.CancellationRequest cancellationRequest) throws Throwable
//JAVA TO C# CONVERTER NOTE: Members cannot have the same name as their enclosing type:
        public virtual URI SwitchToSlaveConflict(LifeSupport haCommunicationLife, URI me, URI masterUri, CancellationRequest cancellationRequest)
        {
            URI  slaveUri;
            bool success = false;

            Monitor.switchToSlaveStarted();

            // Wait a short while for current transactions to stop first, just to be nice.
            // We can't wait forever since switching to our designated role is quite important.
            Clock clock    = Clocks.systemClock();
            long  deadline = clock.millis() + Config.get(HaSettings.internal_state_switch_timeout).toMillis();
            DatabaseTransactionStats transactionStats = _transactionStatsSupplier.get();

            while (transactionStats.NumberOfActiveTransactions > 0 && clock.millis() < deadline)
            {
                parkNanos(MILLISECONDS.toNanos(10));
            }

            try
            {
                InstanceId myId = Config.get(ClusterSettings.server_id);

                UserLog.info("ServerId %s, moving to slave for master %s", myId, masterUri);

                Debug.Assert(masterUri != null);                           // since we are here it must already have been set from outside

                _idGeneratorFactory.switchToSlave();

                CopyStoreFromMasterIfNeeded(masterUri, me, cancellationRequest);

                /*
                 * The following check is mandatory, since the store copy can be cancelled and if it was actually
                 * happening then we can't continue, as there is no store in place
                 */
                if (cancellationRequest.CancellationRequested())
                {
                    MsgLog.info("Switch to slave cancelled during store copy if no local store is present.");
                    return(null);
                }

                /*
                 * We get here either with a fresh store from the master copy above so we need to
                 * start the ds or we already had a store, so we have already started the ds. Either way,
                 * make sure it's there.
                 */
                NeoStoreDataSource neoDataSource = _neoDataSourceSupplier.get();
                neoDataSource.AfterModeSwitch();
                StoreId myStoreId = neoDataSource.StoreId;

                bool consistencyChecksExecutedSuccessfully = ExecuteConsistencyChecks(_transactionIdStoreSupplier.get(), masterUri, me, myStoreId, cancellationRequest);

                if (!consistencyChecksExecutedSuccessfully)
                {
                    MsgLog.info("Switch to slave cancelled due to consistency check failure.");
                    return(null);
                }

                if (cancellationRequest.CancellationRequested())
                {
                    MsgLog.info("Switch to slave cancelled after consistency checks.");
                    return(null);
                }

                // no exception were thrown and we can proceed
                slaveUri = StartHaCommunication(haCommunicationLife, neoDataSource, me, masterUri, myStoreId, cancellationRequest);
                if (slaveUri == null)
                {
                    MsgLog.info("Switch to slave unable to connect.");
                    return(null);
                }

                success = true;
                UserLog.info("ServerId %s, successfully moved to slave for master %s", myId, masterUri);
            }
            finally
            {
                Monitor.switchToSlaveCompleted(success);
            }

            return(slaveUri);
        }
Exemplo n.º 22
0
        private void ProcessRequests(object notUsed)
        {
            try
            {
                BasicServerState state = this.GetState();
                if (state != BasicServerState.Running)
                {
                    return;
                }

                List <InternalRequest> existingRequests  = new List <InternalRequest>();
                List <InternalRequest> receivedRequests  = new List <InternalRequest>();
                List <InternalRequest> cancelledRequests = new List <InternalRequest>();
                //Dictionary<string, InternalAvailability> availableWorkers = new Dictionary<string, InternalAvailability>();
                _State.Locked((managerState) =>
                {
                    // - process responses
                    foreach (ICoreItem item in _ManagerResponseCache.Items)
                    {
                        try
                        {
                            ManagerResponse response = (ManagerResponse)item.Data;
                            Guid requestId           = Guid.Parse(response.RequestId);
                            InternalRequest internalRequest;
                            if (!managerState.InternalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Status = response.Status;
                            managerState.InternalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process requests
                    foreach (ICoreItem item in _UnassignedRequestsCache.Items)
                    {
                        try
                        {
                            UnassignedWorkflowRequest request = (UnassignedWorkflowRequest)item.Data;
                            Guid requestId = Guid.Parse(request.RequestId);
                            InternalRequest internalRequest;
                            if (!managerState.InternalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.ExternalRequest          = request;
                            managerState.InternalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }
                    // - process cancellations
                    foreach (ICoreItem item in _CancellationsCache.Items)
                    {
                        try
                        {
                            CancellationRequest cancellation = (CancellationRequest)item.Data;
                            Guid requestId = Guid.Parse(cancellation.RequestId);
                            InternalRequest internalRequest;
                            if (!managerState.InternalRequests.TryGetValue(requestId, out internalRequest))
                            {
                                internalRequest = new InternalRequest(requestId);
                            }
                            internalRequest.Cancellation             = cancellation;
                            managerState.InternalRequests[requestId] = internalRequest;
                        }
                        catch (Exception excp)
                        {
                            Logger.Log(excp);
                        }
                    }

                    // determine requests to be launched or cancelled
                    foreach (InternalRequest internalRequest in managerState.InternalRequests.Values)
                    {
                        if ((internalRequest.ExternalRequest != null) &&
                            ((internalRequest.Status == RequestStatusEnum.Undefined) || (internalRequest.Status == RequestStatusEnum.Received)))
                        {
                            // find requests to launch
                            if (internalRequest.Cancellation == null)
                            {
                                if (internalRequest.Status != RequestStatusEnum.Received)
                                {
                                    // new request
                                    internalRequest.Status = RequestStatusEnum.Received;
                                    receivedRequests.Add(internalRequest);
                                }
                                existingRequests.Add(internalRequest);
                            }
                            else
                            {
                                // cancelled
                                internalRequest.Status = RequestStatusEnum.Cancelled;
                                cancelledRequests.Add(internalRequest);
                            }
                        }
                    }
                });

                // publish cancelled requests
                foreach (InternalRequest request in cancelledRequests)
                {
                    PublishManagerResponse(_IntClient.Target, request);
                }

                // publish received status
                foreach (InternalRequest request in receivedRequests)
                {
                    PublishManagerResponse(_IntClient.Target, request);
                }

                // find available workers for received requests
                //Logger.LogDebug("Assigning {0} requests ...", existingRequests.Count);
                foreach (InternalRequest request in existingRequests)
                {
                    //Logger.LogDebug("----- Request: {0}", request.RequestId);
                    WorkerAvailability chosenWorker = null;
                    int highestAvailability         = 0;
                    foreach (var item in _WorkerAvailabilityCache.Items)
                    {
                        WorkerAvailability worker = (WorkerAvailability)item.Data;
                        //Logger.LogDebug("----- Worker: {0} ({1})", worker.PrivateKey, worker.AvailableNodeCount);
                        if (worker.AvailableNodeCount > highestAvailability)
                        {
                            highestAvailability = worker.AvailableNodeCount;
                            chosenWorker        = worker;
                        }
                    }
                    // exit if no workers available
                    if (chosenWorker == null)
                    {
                        break;
                    }
                    Logger.LogDebug("Assigned request '{0}' to {1} ({2})", request.RequestId, chosenWorker.PrivateKey, chosenWorker.AvailableNodeCount);
                    chosenWorker.AvailableNodeCount = chosenWorker.AvailableNodeCount - 1;
                    // publish assigned status
                    request.Status = RequestStatusEnum.Assigned;
                    PublishManagerResponse(_IntClient.Target, request);
                    // reassign to worker
                    RequestBase.TransferToWorker(_IntClient.Target, request.ExternalRequest, chosenWorker.WorkerHostComputer, chosenWorker.WorkerHostInstance);
                }
                //Logger.LogDebug("Assigned.");
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
        }