Exemplo n.º 1
0
        public static ClientConnectionInfo Create(HttpServletRequest request)
        {
            string        connectionId;
            string        protocol = request.Scheme;
            SocketAddress clientAddress;
            SocketAddress serverAddress;
            string        requestURI = request.RequestURI;

            JettyHttpConnection connection = JettyHttpConnection.CurrentJettyHttpConnection;

            if (connection != null)
            {
                connectionId  = connection.Id();
                clientAddress = connection.ClientAddress();
                serverAddress = connection.ServerAddress();
            }
            else
            {
                // connection is unknown, connection object can't be extracted or is missing from the Jetty thread-local
                // get all the available information directly from the request
                connectionId  = null;
                clientAddress = new InetSocketAddress(request.RemoteAddr, request.RemotePort);
                serverAddress = new InetSocketAddress(request.ServerName, request.ServerPort);
            }

            return(new HttpConnectionInfo(connectionId, protocol, clientAddress, serverAddress, requestURI));
        }
Exemplo n.º 2
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void start() throws Throwable
        public override void Start()
        {
            string          className      = this.GetType().Name;
            ExecutorService bossExecutor   = newCachedThreadPool(daemon("Boss-" + className));
            ExecutorService workerExecutor = newCachedThreadPool(daemon("Worker-" + className));

            _bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(bossExecutor, workerExecutor, _config.MaxConcurrentTransactions));
            _bootstrap.PipelineFactory = this;

            PortRangeSocketBinder portRangeSocketBinder = new PortRangeSocketBinder(_bootstrap);

            try
            {
                Connection connection = portRangeSocketBinder.BindToFirstAvailablePortInRange(_config.ServerAddress);
                Channel    channel    = connection.Channel;
                _socketAddress = connection.SocketAddress;

                _channelGroup = new DefaultChannelGroup();
                _channelGroup.add(channel);
                _msgLog.info(className + " communication server started and bound to " + _socketAddress);
            }
            catch (Exception ex)
            {
                _msgLog.error("Failed to bind server to " + _socketAddress, ex);
                _bootstrap.releaseExternalResources();
                _targetCallExecutor.shutdownNow();
                _unfinishedTransactionExecutor.shutdownNow();
                _silentChannelExecutor.shutdownNow();
                throw new IOException(ex);
            }
        }
Exemplo n.º 3
0
        internal virtual URI GetURI(InetSocketAddress socketAddress)
        {
            string uri;

            InetAddress address = socketAddress.Address;

            if (address is Inet6Address)
            {
                uri = CLUSTER_SCHEME + "://" + WrapAddressForIPv6Uri(address.HostAddress) + ":" + socketAddress.Port;
            }
            else if (address is Inet4Address)
            {
                uri = CLUSTER_SCHEME + "://" + address.HostAddress + ":" + socketAddress.Port;
            }
            else
            {
                throw new System.ArgumentException("Address type unknown");
            }

            // Add name if given
            if (!string.ReferenceEquals(_config.name(), null))
            {
                uri += "/?name=" + _config.name();
            }

            return(URI.create(uri));
        }
        /// <summary>
        /// Tests if a remote host name is reachable
        /// </summary>
        /// <param name="host">Host name can be a remote IP or URL of website</param>
        /// <param name="port">Port to attempt to check is reachable.</param>
        /// <param name="msTimeout">Timeout in milliseconds.</param>
        /// <returns></returns>
        public override async Task <bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000)
        {
            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentNullException("host");
            }

            if (!IsConnected)
            {
                return(false);
            }

            return(await Task.Run(async() =>
            {
                try
                {
                    var sockaddr = new InetSocketAddress(host, port);
                    using (var sock = new Socket())
                    {
                        await sock.ConnectAsync(sockaddr, msTimeout);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Unable to reach: " + host + " Error: " + ex);
                    return false;
                }
            }));
        }
Exemplo n.º 5
0
            public override void MessageReceived(ChannelHandlerContext ctx, MessageEvent @event)
            {
                if (!outerInstance.BindingDetected)
                {
                    InetSocketAddress local = ( InetSocketAddress )@event.Channel.LocalAddress;
                    outerInstance.BindingDetected = true;
                    outerInstance.ListeningAt(outerInstance.GetURI(local));
                }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.cluster.com.message.Message message = (org.neo4j.cluster.com.message.Message) event.getMessage();
                Message message = ( Message )@event.Message;

                // Fix HEADER_FROM header since sender cannot know it's correct IP/hostname
                InetSocketAddress remote        = ( InetSocketAddress )ctx.Channel.RemoteAddress;
                string            remoteAddress = remote.Address.HostAddress;
                URI fromHeader = URI.create(message.getHeader(Message.HEADER_FROM));

                if (remote.Address is Inet6Address)
                {
                    remoteAddress = WrapAddressForIPv6Uri(remoteAddress);
                }
                fromHeader = URI.create(fromHeader.Scheme + "://" + remoteAddress + ":" + fromHeader.Port);
                message.setHeader(Message.HEADER_FROM, fromHeader.toASCIIString());

                outerInstance.msgLog.Debug("Received:" + message);
                outerInstance.monitor.ReceivedMessage(message);
                outerInstance.Receive(message);
            }
Exemplo n.º 6
0
        public virtual void discover()
        {
            try
            {
                igd = new IGD();
                ListenerThread listener = new ListenerThread(this, igd);
                listener.Daemon = true;
                listener.Name   = "UPnP Discovery Listener";
                listener.Start();
                while (!listener.Ready)
                {
                    Utilities.sleep(100);
                }

                foreach (string device in deviceList)
                {
                    string discoveryRequest = string.Format("M-SEARCH * HTTP/1.1\r\nHOST: {0}:{1:D}\r\nST: {2}\r\nMAN: \"ssdp:discover\"\r\nMX: {3:D}\r\n\r\n", multicastIp, discoveryPort, device, discoveryTimeoutMillis / 1000);
                    IEnumerator <NetworkInterface> networkInterfaces = NetworkInterface.NetworkInterfaces;
                    while (networkInterfaces.MoveNext())
                    {
                        NetworkInterface networkInterface = networkInterfaces.Current;
                        if (networkInterface.Up && networkInterface.supportsMulticast())
                        {
                            for (IEnumerator <InetAddress> addresses = networkInterface.InetAddresses; addresses.MoveNext();)
                            {
                                InetAddress address = addresses.Current;
                                if (address is Inet4Address && !address.LoopbackAddress)
                                {
                                    MulticastSocket   socket        = new MulticastSocket(new InetSocketAddress(address, discoverySearchPort));
                                    InetSocketAddress socketAddress = new InetSocketAddress(multicastIp, discoveryPort);
                                    DatagramPacket    packet        = new DatagramPacket(discoveryRequest.GetBytes(), discoveryRequest.Length, socketAddress);
                                    socket.send(packet);
                                    socket.disconnect();
                                    socket.close();
                                }
                            }
                        }
                    }
                }

                for (int i = 0; i < discoveryTimeoutMillis / 10; i++)
                {
                    if (listener.Done)
                    {
                        break;
                    }
                    Utilities.sleep(10, 0);
                }

                listener.Done = true;
                while (!listener.Ready)
                {
                    Utilities.sleep(100);
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("discover", e);
            }
        }
Exemplo n.º 7
0
 public virtual void readFromInetSocketAddress(InetSocketAddress inetSocketAddress)
 {
     sin_len    = @sizeof();
     sin_family = sceNetInet.AF_INET;
     sin_port   = inetSocketAddress.Port;
     sin_addr   = sceNetInet.bytesToInternetAddress(inetSocketAddress.Address.Address);
 }
Exemplo n.º 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setup() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void Setup()
        {
            @lock = NewThrottleLockMock();

            _config = mock(typeof(SocketChannelConfig));

            _lockAttribute = mock(typeof(Attribute));
            when(_lockAttribute.get()).thenReturn(@lock);

            Attribute durationExceedAttribute = mock(typeof(Attribute));

            when(durationExceedAttribute.get()).thenReturn(null);

            _channel = mock(typeof(SocketChannel), Answers.RETURNS_MOCKS);
            when(_channel.config()).thenReturn(_config);
            when(_channel.Open).thenReturn(true);
            when(_channel.remoteAddress()).thenReturn(InetSocketAddress.createUnresolved("localhost", 32000));
            when(_channel.attr(TransportWriteThrottle.LockKey)).thenReturn(_lockAttribute);
            when(_channel.attr(TransportWriteThrottle.MaxDurationExceededKey)).thenReturn(durationExceedAttribute);

            ChannelPipeline pipeline = _channel.pipeline();

            when(_channel.pipeline()).thenReturn(pipeline);

            _context = mock(typeof(ChannelHandlerContext), Answers.RETURNS_MOCKS);
            when(_context.channel()).thenReturn(_channel);
        }
Exemplo n.º 9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRemoveChannelViaCallback()
        public virtual void ShouldRemoveChannelViaCallback()
        {
            // given
            AdvertisedSocketAddress address  = new AdvertisedSocketAddress("localhost", 1984);
            ReconnectingChannels    channels = new ReconnectingChannels();

            channels.PutIfAbsent(address, mock(typeof(ReconnectingChannel)));

            IdleChannelReaperHandler reaper = new IdleChannelReaperHandler(channels);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.net.InetSocketAddress socketAddress = address.socketAddress();
            InetSocketAddress socketAddress = address.SocketAddressConflict();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final io.netty.channel.Channel channel = mock(io.netty.channel.Channel.class);
            Channel channel = mock(typeof(Channel));

            when(channel.remoteAddress()).thenReturn(socketAddress);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final io.netty.channel.ChannelHandlerContext context = mock(io.netty.channel.ChannelHandlerContext.class);
            ChannelHandlerContext context = mock(typeof(ChannelHandlerContext));

            when(context.channel()).thenReturn(channel);

            // when
            reaper.UserEventTriggered(context, IdleStateEvent.ALL_IDLE_STATE_EVENT);

            // then
            assertNull(channels.Get(address));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Tests if a remote host name is reachable
        /// </summary>
        /// <param name="host">Host name can be a remote IP or URL of website (no http:// or www.)</param>
        /// <param name="port">Port to attempt to check is reachable.</param>
        /// <param name="msTimeout">Timeout in milliseconds.</param>
        /// <returns></returns>
        public override async Task <bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000)
        {
            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentNullException(nameof(host));
            }

            if (!IsConnected)
            {
                return(false);
            }

            host = host.Replace("http://www.", string.Empty).
                   Replace("http://", string.Empty).
                   Replace("https://www.", string.Empty).
                   Replace("https://", string.Empty);

            return(await Task.Run(async() =>
            {
                try
                {
                    var sockaddr = new InetSocketAddress(host, port);
                    using (var sock = new Socket())
                    {
                        await sock.ConnectAsync(sockaddr, msTimeout);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }));
        }
 private static string getKey(InetSocketAddress socketAddress)
 {
     if (socketAddress == null)
     {
         return(null);
     }
     return(string.Format("{0}:{1}", socketAddress.Address, socketAddress.Port));
 }
Exemplo n.º 12
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void connect() throws java.io.IOException
            public virtual void connect()
            {
                openChannel();
                if (!socketChannel.Connected && !socketChannel.ConnectionPending)
                {
                    SocketAddress socketAddress = new InetSocketAddress(InetAddress.getByAddress(destinationIPAddress), destinationPort);
                    socketChannel.connect(socketAddress);
                }
            }
 public object clone()
 {
     InetSocketAddress[] trackerServers = new InetSocketAddress[this.tracker_servers.Length];
     for (int i = 0; i < trackerServers.Length; i++)
     {
         trackerServers[i] = new InetSocketAddress(this.tracker_servers[i].Address, this.tracker_servers[i].Port);
     }
     return(new TrackerGroup(trackerServers));
 }
Exemplo n.º 14
0
 public static string Format(java.net.SocketAddress address)
 {
     if (address is InetSocketAddress)
     {
         InetSocketAddress inetSocketAddress = ( InetSocketAddress )address;
         return(Format(inetSocketAddress.HostString, inetSocketAddress.Port));
     }
     return(address.ToString());
 }
Exemplo n.º 15
0
        public virtual bool isBroadcast(SocketAddress socketAddress)
        {
            if (socketAddress is InetSocketAddress)
            {
                InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress;
                return(inetSocketAddress.Address.Equals(broadcastInetAddress));
            }

            return(false);
        }
Exemplo n.º 16
0
        private SslHandler CreateSslHandler(ChannelHandlerContext ctx, InetSocketAddress inetSocketAddress)
        {
            SSLEngine sslEngine = _sslContext.newEngine(ctx.alloc(), inetSocketAddress.HostName, inetSocketAddress.Port);

            foreach (System.Func <SSLEngine, SSLEngine> mod in _engineModifications)
            {
                sslEngine = mod(sslEngine);
            }
            // Don't need to set tls versions since that is set up from the context
            return(new SslHandler(sslEngine));
        }
Exemplo n.º 17
0
        public virtual void testParseSocketAddressToString_MuiltiFormatTest()
        {
            IPEndPoint socketAddress = new IPEndPoint(IPAddress.Parse("/127.0.0.1"), 1111);
            string     res           = RemotingUtil.parseSocketAddressToString(socketAddress);

            Assert.Equal("127.0.0.1:1111", res);

            socketAddress = new InetSocketAddress("sofatest-2.stack.alipay.net/127.0.0.1", 12200);
            res           = RemotingUtil.parseSocketAddressToString(socketAddress);
            Assert.Equal("127.0.0.1:12200", res);
        }
Exemplo n.º 18
0
 private void RegisterHttpsAddressAfterStartup()
 {
     if (_httpsConnector != null)
     {
         InetSocketAddress localHttpsAddress = WebServerConflict.LocalHttpsAddress;
         _connectorPortRegister.register(_httpsConnector.key(), localHttpsAddress);
         if (_httpsAdvertisedAddress.Port == 0)
         {
             _httpsAdvertisedAddress = new AdvertisedSocketAddress(localHttpsAddress.HostString, localHttpsAddress.Port);
         }
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Tries to connect the socket with a specific ip address and port.
        /// If first connection attempt fails a second one is executed
        /// socket streams are created for reading and writing.
        /// </summary>
        private void Connect()
        {
            if (mSocket.IsConnected == false)
            {
                isConnectingFinished = false;
                try
                {
                    // Connect to socket
                    mSocket = new Socket(SERVER_ADDRESS, SERVER_PORT);
                }
                catch (UnknownHostException uhe)
                {
                    Log.Debug(TAG, uhe.Message + " if the IP address of the host could not be determined.");
                }
                catch (IOException uhe)
                {
                    Log.Debug(TAG, uhe.Message + " if an I/O error occurs when creating the socket.");
                }
                catch (SecurityException uhe)
                {
                    Log.Debug(TAG, uhe.Message + " if a security manager exists and its checkConnect method doesn't allow the operation.");
                }
                catch (IllegalAccessException uhe)
                {
                    Log.Debug(TAG, uhe.Message + " if the port parameter is outside the specified range of valid port values, which is between 0 and 65535, inclusive.");
                }

                try
                {
                    if (!mSocket.IsConnected)
                    {
                        // If first connection attempt fails try again
                        SocketAddress socketAdr = new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT);
                        Thread.Sleep(5000);
                        mSocket.Connect(socketAdr, 2000);
                    }
                }
                catch (Java.Lang.Exception ex)
                {
                    Log.Debug(TAG, ex.Message);
                }
                finally
                {
                    if (mSocket.IsConnected)
                    {
                        // Create socket reading and writing streams
                        mSocketWriter = new SocketWriter(mSocket.OutputStream);
                        mSocketReader = new SocketReader(new DataInputStream(mSocket.InputStream), mRaspberryClose);
                    }
                    isConnectingFinished = true;
                }
            }
        }
Exemplo n.º 20
0
        public TcpTunnel(InetSocketAddress serverAddress, Selector selector, short portKey)
        {
            SocketChannel innerChannel = SocketChannel.Open();

            innerChannel.ConfigureBlocking(false);
            mInnerChannel = innerChannel;
            mSelector     = selector;
            mServerEP     = serverAddress;
            this.portKey  = portKey;

            sessionCount++;
        }
Exemplo n.º 21
0
        protected Proxy getProxy()
        {
            if (_proxyURL == null || _proxyURL.getPort() < 0)
            {
                return(null);
            }

            InetSocketAddress address
                = new InetSocketAddress(_proxyURL.getHost(), _proxyURL.getPort());

            return(new Proxy(Proxy.Type.valueOf(_proxyType), address));
        }
        public void HandleIncomingConnections()
        {
            //List<ServerThread> serverThreads = new List<ServerThread>();

            Task.Run(() =>
            {
                try
                {
                    // Create the ServerSocket
                    serverSocket = new ServerSocket();
                    var sAddr    = new InetSocketAddress(Port);
                    serverSocket.ReuseAddress = true;
                    serverSocket.Bind(sAddr);
                    Log.Debug(_tag, $"Server listening on {Port}.");

                    while (!_cts.IsCancellationRequested)
                    {
                        // Grab the next incoming connection
                        Socket socket = serverSocket.Accept();
                        Log.Debug(_tag, $"Server accepted a connection from {socket.InetAddress.CanonicalHostName}.");

                        lock (_lock)
                        {
                            // Cache the socket, filed under its address
                            connections[socket.InetAddress.CanonicalHostName] = socket;

                            //// Create and cache a DataOutputStream for sending data over it
                            //var dOutStream = new DataOutputStream(socket.OutputStream);
                            // outputStreams.Add(socket, dOutStream);
                        }

                        // Create a new thread for this connection
                        serverThreads[socket.InetAddress.CanonicalHostName] = new ServerThread(this, socket).Start();

                        //// Ack back to the connection to let it know you're hearing it (and to pass it the address you'll know it by)
                        //ForwardTo(socket.InetAddress.CanonicalHostName, GROUPSERVER, ACK + CONNECTED_AS + socket.InetAddress.CanonicalHostName);
                    }
                }
                catch (Exception e)
                {
                    Log.Debug(_tag, $"Exception in server socket listening: \n{e}\n");
                }
                finally
                {
                    Log.Debug(_tag, $"Releasing all connections ({serverThreads.Count} of them).");
                    serverSocket.Close();
                    foreach (var sThread in serverThreads.Values)
                    {
                        sThread.Stop();
                    }
                }
            });
        }
Exemplo n.º 23
0
        public void connectTo(String host, int port)
        {
            EzySocketStatus status = socketStatuses.last();

            if (!isSocketConnectable(status))
            {
                logger.warn("udp socket is connecting...");
                return;
            }
            serverAddress = new InetSocketAddress(host, port);
            connect0();
        }
Exemplo n.º 24
0
        private URI CreateHaURI <T1>(URI me, Server <T1> server)
        {
            InetSocketAddress serverSocketAddress = server.SocketAddress;
            string            hostString          = ServerUtil.getHostString(serverSocketAddress);

            string host = IsWildcard(hostString) ? me.Host : hostString;

            host = EnsureWrapForIpv6Uri(host);

            InstanceId serverId = Config.get(ClusterSettings.server_id);

            return(URI.create("ha://" + host + ":" + serverSocketAddress.Port + "?serverId=" + serverId));
        }
Exemplo n.º 25
0
        public virtual int getBroadcastPort(SocketAddress socketAddress)
        {
            if (socketAddress is InetSocketAddress)
            {
                InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress;
                if (inetSocketAddress.Address.Equals(broadcastInetAddress))
                {
                    return(inetSocketAddress.Port);
                }
            }

            return(-1);
        }
Exemplo n.º 26
0
        internal static URI GetMasterUri(URI me, MasterServer masterServer, Config config)
        {
            string            hostname            = config.Get(HaSettings.ha_server).Host;
            InetSocketAddress masterSocketAddress = masterServer.SocketAddress;

            if (string.ReferenceEquals(hostname, null) || IsWildcard(hostname))
            {
                InetAddress masterAddress = masterSocketAddress.Address;
                hostname = masterAddress.AnyLocalAddress ? me.Host : ServerUtil.getHostString(masterSocketAddress);
                hostname = EnsureWrapForIPv6Uri(hostname);
            }

            return(URI.create("ha://" + hostname + ":" + masterSocketAddress.Port + "?serverId=" + MyId(config)));
        }
Exemplo n.º 27
0
        public override void UserEventTriggered(ChannelHandlerContext ctx, object evt)
        {
            if (evt is IdleStateEvent && evt == IdleStateEvent.ALL_IDLE_STATE_EVENT)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.net.InetSocketAddress socketAddress = (java.net.InetSocketAddress) ctx.channel().remoteAddress();
                InetSocketAddress socketAddress = ( InetSocketAddress )ctx.channel().remoteAddress();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.helpers.AdvertisedSocketAddress address = new org.neo4j.helpers.AdvertisedSocketAddress(socketAddress.getHostName(), socketAddress.getPort());
                AdvertisedSocketAddress address = new AdvertisedSocketAddress(socketAddress.HostName, socketAddress.Port);

                _channels.remove(address);
            }
        }
Exemplo n.º 28
0
        public RemoteTcpTunnel(InetSocketAddress serverAddress, Selector selector, short portKey, Context context) : base(serverAddress, selector, portKey)
        {
            this.context = context;
            session      = NatSessionManager.getSession(portKey);
            string helperDir = new StringBuilder()
                               .Append(VPNConstants.DATA_DIR)
                               .Append(TimeFormatUtil.formatYYMMDDHHMMSS(session.vpnStartTime))
                               .Append("/")
                               .Append(session.getUniqueName())
                               .ToString();

            helper  = new TcpDataSaveHelper(helperDir, context);
            handler = new Handler(Looper.MainLooper);
        }
Exemplo n.º 29
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") private SwitchToSlaveCopyThenBranch newSwitchToSlaveSpy(org.neo4j.io.pagecache.PageCache pageCacheMock, org.neo4j.com.storecopy.StoreCopyClient storeCopyClient)
        private SwitchToSlaveCopyThenBranch NewSwitchToSlaveSpy(PageCache pageCacheMock, StoreCopyClient storeCopyClient)
        {
            ClusterMembers clusterMembers = mock(typeof(ClusterMembers));
            ClusterMember  master         = mock(typeof(ClusterMember));

            when(master.StoreId).thenReturn(_storeId);
            when(master.HARole).thenReturn(HighAvailabilityModeSwitcher.MASTER);
            when(master.HasRole(eq(HighAvailabilityModeSwitcher.MASTER))).thenReturn(true);
            when(master.InstanceId).thenReturn(new InstanceId(1));
            when(clusterMembers.Members).thenReturn(asList(master));

            Dependencies         resolver             = new Dependencies();
            DatabaseAvailability databaseAvailability = mock(typeof(DatabaseAvailability));

            when(databaseAvailability.Started).thenReturn(true);
            resolver.SatisfyDependencies(_requestContextFactory, clusterMembers, mock(typeof(TransactionObligationFulfiller)), mock(typeof(OnlineBackupKernelExtension)), mock(typeof(IndexConfigStore)), mock(typeof(TransactionCommittingResponseUnpacker)), mock(typeof(DataSourceManager)), mock(typeof(StoreLockerLifecycleAdapter)), mock(typeof(FileSystemWatcherService)), databaseAvailability);

            NeoStoreDataSource dataSource = mock(typeof(NeoStoreDataSource));

            when(dataSource.StoreId).thenReturn(_storeId);
            when(dataSource.DependencyResolver).thenReturn(resolver);

            DatabaseTransactionStats transactionCounters = mock(typeof(DatabaseTransactionStats));

            when(transactionCounters.NumberOfActiveTransactions).thenReturn(0L);

            Response <HandshakeResult> response = mock(typeof(Response));

            when(response.ResponseConflict()).thenReturn(new HandshakeResult(42, 2));
            when(_masterClient.handshake(anyLong(), any(typeof(StoreId)))).thenReturn(response);
            when(_masterClient.ProtocolVersion).thenReturn(Org.Neo4j.Kernel.ha.com.slave.MasterClient_Fields.Current);

            TransactionIdStore transactionIdStoreMock = mock(typeof(TransactionIdStore));

            // note that the checksum (the second member of the array) is the same as the one in the handshake mock above
            when(transactionIdStoreMock.LastCommittedTransaction).thenReturn(new TransactionId(42, 42, 42));

            MasterClientResolver masterClientResolver = mock(typeof(MasterClientResolver));

            when(masterClientResolver.Instantiate(anyString(), anyInt(), anyString(), any(typeof(Monitors)), argThat(_storeId => true), any(typeof(LifeSupport)))).thenReturn(_masterClient);

            return(spy(new SwitchToSlaveCopyThenBranch(TestDirectory.databaseLayout(), NullLogService.Instance, ConfigMock(), mock(typeof(HaIdGeneratorFactory)), mock(typeof(DelegateInvocationHandler)), mock(typeof(ClusterMemberAvailability)), _requestContextFactory, _pullerFactory, masterClientResolver, mock(typeof(SwitchToSlave.Monitor)), storeCopyClient, Suppliers.singleton(dataSource), Suppliers.singleton(transactionIdStoreMock), slave =>
            {
                SlaveServer server = mock(typeof(SlaveServer));
                InetSocketAddress inetSocketAddress = InetSocketAddress.createUnresolved("localhost", 42);

                when(server.SocketAddress).thenReturn(inetSocketAddress);
                return server;
            }, _updatePuller, pageCacheMock, mock(typeof(Monitors)), () => transactionCounters)));
        }
Exemplo n.º 30
0
 public void connect(InetSocketAddress destAddress)
 {
     if (VpnServiceHelper.protect(mInnerChannel.Socket()))
     {
         mDestAddress = destAddress;
         mInnerChannel.Register(mSelector, Operations.Connect, this);
         mInnerChannel.Connect(mServerEP);
         Debug.WriteLine($"Connecting to {mServerEP}");
     }
     else
     {
         throw new Exception("VPN protect socket failed.");
     }
 }