@SuppressWarnings("unchecked") @Override public <T> ProtocolProxy<T> getProxy( Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth) throws IOException { T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new StoppedInvocationHandler()); return new ProtocolProxy<T>(protocol, proxy, false); }
/** Construct a client-side proxy object that implements the named protocol, * talking to a server at the named address. */ public static <T> T getProxy( Class<T> protocol, long clientVersion, InetSocketAddress addr, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { T proxy = (T) Proxy.newProxyInstance( protocol.getClassLoader(), new Class[] { protocol }, new Invoker(protocol, addr, conf, factory, rpcTimeout)); return proxy; }
private static HttpURLConnection a(Context context, String str) { try { URL url = new URL(str); if (context.getPackageManager().checkPermission(z[43], context.getPackageName()) == 0) { NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService(z[44])).getActiveNetworkInfo(); if (!(activeNetworkInfo == null || activeNetworkInfo.getType() == 1)) { String extraInfo = activeNetworkInfo.getExtraInfo(); if (extraInfo != null && (extraInfo.equals(z[40]) || extraInfo.equals(z[41]) || extraInfo.equals(z[42]))) { return (HttpURLConnection) url.openConnection(new Proxy(Type.HTTP, new InetSocketAddress(z[45], 80))); } } } return (HttpURLConnection) url.openConnection(); } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e2) { e2.printStackTrace(); return null; } }
@Before public void setUp() throws IOException { DelayedTransactionId dti1 = new DelayedTransactionId(new byte[]{13, 14}, new InetSocketAddress(5683)); DelayedTransactionId dti2 = new DelayedTransactionId(new byte[]{13, 14}, new InetSocketAddress(5683)); dti1.equals(dti2); assertEquals(dti1.hashCode(), dti2.hashCode()); assertEquals(dti1, dti2); server = CoapServer.builder().transport(InMemoryCoapTransport.create()) .timeout(new SingleTimeout(1000)) .build(); server.addRequestHandler("/temp", new ReadOnlyCoapResource("23 C")); server.addRequestHandler("/seperate", new CoapResourceSeparateRespImpl("test-content")); server.start(); serverAddr = InMemoryCoapTransport.createAddress(server.getLocalSocketAddress().getPort()); }
/** * Returns the address of the node we think is the leader. */ protected InetSocketAddress findLeader() { InetSocketAddress addr = null; // Find the leader by id Vote current = self.getCurrentVote(); for (QuorumServer s : self.getView().values()) { if (s.id == current.getId()) { // Ensure we have the leader's correct IP address before // attempting to connect. s.recreateSocketAddresses(); addr = s.addr; break; } } if (addr == null) { LOG.warn("Couldn't find the leader with id = " + current.getId()); } return addr; }
public static void main(String args[]) throws Exception { InetAddress iaddr = InetAddress.getLocalHost(); try ( ServerSocket ss = new ServerSocket(0); Socket s1 = new Socket(iaddr, ss.getLocalPort()); Socket s2 = ss.accept() ) { test(s1, s2, "Testing NET"); } // check the NIO socket adapter try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null); SocketChannel s1 = SocketChannel.open( new InetSocketAddress(iaddr, sc.socket().getLocalPort())); SocketChannel s2 = sc.accept() ) { test(s1.socket(), s2.socket(), "Testing NIO"); } if (failed) { throw new RuntimeException("Failed: check output"); } }
private int getAvailablePort(int fromPort, int toPort) { if (toPort <= fromPort) return fromPort; int count = 50; int step = (toPort - fromPort) / count; while (count > 0) { int port = fromPort + (50-count) * step + random.nextInt(step); try { ServerSocket s = new ServerSocket(); s.bind(new InetSocketAddress("localhost", port)); s.close(); } catch (IOException ex) { --count; continue; } return port; } return random.nextInt((toPort-fromPort)) + fromPort; }
/** Construct a client-side proxy object that implements the named protocol, * talking to a server at the named address. * @param <T>*/ @Override @SuppressWarnings("unchecked") public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth) throws IOException { if (connectionRetryPolicy != null) { throw new UnsupportedOperationException( "Not supported: connectionRetryPolicy=" + connectionRetryPolicy); } T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout, fallbackToSimpleAuth)); return new ProtocolProxy<T>(protocol, proxy, true); }
public Socket connectSocket( final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress); } try { sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } return sock; }
@Override public DistributedDatabaseContact importContact( InetSocketAddress address ) throws DistributedDatabaseException { throwIfNotAvailable(); DHTPluginContact contact = getDHT().importContact( address ); if ( contact == null ){ throw( new DistributedDatabaseException( "import of '" + address + "' failed" )); } return( new DDBaseContactImpl( this, contact)); }
@Test public void testClientReconnect() throws IOException, InterruptedException { HostProvider hostProvider = mock(HostProvider.class); when(hostProvider.size()).thenReturn(1); InetSocketAddress inaddr = new InetSocketAddress(1111); when(hostProvider.next(anyLong())).thenReturn(inaddr); ZooKeeper zk = mock(ZooKeeper.class); sc = SocketChannel.open(); ClientCnxnSocketNIO nioCnxn = new MockCnxn(); ClientWatchManager watcher = mock(ClientWatchManager.class); ClientCnxn clientCnxn = new ClientCnxn( "tmp", hostProvider, 5000, zk, watcher, nioCnxn, false); clientCnxn.start(); countDownLatch.await(5000, TimeUnit.MILLISECONDS); Assert.assertTrue(countDownLatch.getCount() == 0); clientCnxn.close(); }
public InetSocketAddress getAddress(HttpClientImpl client) { URI uri = uri(); if (uri == null) { return authority(); } int port = uri.getPort(); if (port == -1) { if (uri.getScheme().equalsIgnoreCase("https")) { port = 443; } else { port = 80; } } String host = uri.getHost(); if (proxy(client) == null) { return new InetSocketAddress(host, port); } else { return InetSocketAddress.createUnresolved(host, port); } }
private ZooMap(Builder builder) { this.connectionString = builder.connectionString; ConnectStringParser connectStringParser = new ConnectStringParser(connectionString); if(connectStringParser.getChrootPath() != null) { final String connectionStringForChrootCreation = connectStringParser.getServerAddresses().stream().map(InetSocketAddress::toString).collect(Collectors.joining(",")); try(final CuratorFramework clientForChrootCreation = newCuratorFrameworkClient(builder, connectionStringForChrootCreation)) { startAndBlock(clientForChrootCreation); tryIt(() -> clientForChrootCreation.createContainers(connectStringParser.getChrootPath())); } } client = newCuratorFrameworkClient(builder, connectionString); this.root = builder.root; startAndBlock(client); if(!root.isEmpty()) { tryIt(() -> client.createContainers(root)); } }
void finishAccept() throws IOException { /** * Set local/remote addresses. This is currently very inefficient * in that it requires 2 calls to getsockname and 2 calls to getpeername. * (should change this to use GetAcceptExSockaddrs) */ updateAcceptContext(handle, channel.handle()); InetSocketAddress local = Net.localAddress(channel.fd); final InetSocketAddress remote = Net.remoteAddress(channel.fd); channel.setConnected(local, remote); // permission check (in context of initiating thread) if (acc != null) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { SecurityManager sm = System.getSecurityManager(); sm.checkAccept(remote.getAddress().getHostAddress(), remote.getPort()); return null; } }, acc); } }
@Test public void create() { ECKey key = new ECKey(); String check = UUID.randomUUID().toString(); PingPeerMessage pingPeerMessage = PingPeerMessage.create("localhost", 80, check, key); PongPeerMessage pongPeerMessage = PongPeerMessage.create("localhost", 80, check, key); InetSocketAddress address = new InetSocketAddress("localhost", 8080); PeerDiscoveryRequest request = PeerDiscoveryRequestBuilder.builder().messageId(check) .message(pingPeerMessage).address(address).expectedResponse(DiscoveryMessageType.PONG) .expirationPeriod(1000).attemptNumber(1).build(); Assert.assertNotNull(request); Assert.assertTrue(request.validateMessageResponse(pongPeerMessage)); Assert.assertFalse(request.validateMessageResponse(pingPeerMessage)); }
@Test public void testDeliveryListener_success() throws CoapException { ObservationTest.SyncObservationListener obsListener = new ObservationTest.SyncObservationListener(); assertNotNull(client.resource("/obs").sync().observe(obsListener)); NotificationDeliveryListener delivListener = mock(NotificationDeliveryListener.class); obsResource.setBody("A", delivListener); verify(delivListener, timeout(3000)).onSuccess(any(InetSocketAddress.class)); obsResource.setBody("B", delivListener); verify(delivListener, timeout(3000).times(2)).onSuccess(any(InetSocketAddress.class)); verify(delivListener, never()).onFail(any(InetSocketAddress.class)); verify(delivListener, never()).onNoObservers(); }
public void start(Client client, String streamName) throws IOException { conn=client.conn; oss=new OutputStreamSender(client.getMultiplexer(), StreamShareVNC.bufferSize, true); try(ServerSocket ss=new ServerSocket()) { ss.bind(new InetSocketAddress("localhost", 0)); int localport=ss.getLocalPort(); System.out.println("Local port: "+localport); params=new StreamParametersVNC(streamName, client.id); StreamDataDuplex data=(StreamDataDuplex)client.conn.shareStream(oss.getId(), params); isr=new InputStreamReceiver(StreamShareVNC.bufferSize, true); client.getMultiplexer().register(isr, data.backChannel); ChainList<String> command=new ChainList<>(client.getArgs().program_x11vnc,"-connect", "localhost:"+localport); //command.addcs("-clip", "200x200+50+50"); command.add("-localhost"); new ProcessBuilder(command).redirectError(Redirect.INHERIT) .redirectOutput(Redirect.INHERIT) .start(); s=ss.accept(); os=new LogFilterOutpurStream(s.getOutputStream()); System.out.println("CONNECTED!"); ConnectStreams.startStreamThread(s.getInputStream(), oss.os); ConnectStreams.startStreamThread(isr.in, os); } }
@Override public DHTPluginContact importContact( InetSocketAddress address, byte version ) { if ( !isEnabled()){ throw( new RuntimeException( "DHT isn't enabled" )); } InetAddress contact_address = address.getAddress(); for ( DHTPluginImpl dht: dhts ){ InetAddress dht_address = dht.getLocalAddress().getAddress().getAddress(); if ( ( contact_address instanceof Inet4Address && dht_address instanceof Inet4Address ) || ( contact_address instanceof Inet6Address && dht_address instanceof Inet6Address )){ return( dht.importContact( address, version )); } } return( null ); }
public DistributedDatabaseContact importContact( InetSocketAddress address, byte protocol_version, int preferred_dht ) throws DistributedDatabaseException;
/** * Test that, if a RuntimeException is thrown after creating a socket * but before successfully connecting to the IPC server, that the * failure is handled properly. This is a regression test for * HADOOP-7428. */ @Test(timeout=60000) public void testRTEDuringConnectionSetup() throws IOException { // Set up a socket factory which returns sockets which // throw an RTE when setSoTimeout is called. SocketFactory spyFactory = spy(NetUtils.getDefaultSocketFactory(conf)); Mockito.doAnswer(new Answer<Socket>() { @Override public Socket answer(InvocationOnMock invocation) throws Throwable { Socket s = spy((Socket)invocation.callRealMethod()); doThrow(new RuntimeException("Injected fault")).when(s) .setSoTimeout(anyInt()); return s; } }).when(spyFactory).createSocket(); Server server = new TestServer(1, true); Client client = new Client(LongWritable.class, conf, spyFactory); server.start(); try { // Call should fail due to injected exception. InetSocketAddress address = NetUtils.getConnectAddress(server); try { call(client, RANDOM.nextLong(), address, conf); fail("Expected an exception to have been thrown"); } catch (Exception e) { LOG.info("caught expected exception", e); assertTrue(StringUtils.stringifyException(e).contains( "Injected fault")); } // Resetting to the normal socket behavior should succeed // (i.e. it should not have cached a half-constructed connection) Mockito.reset(spyFactory); call(client, RANDOM.nextLong(), address, conf); } finally { client.stop(); server.stop(); } }
@Nullable private InetSocketAddress nextPeer() throws UnknownHostException, PeerDiscoveryException { if (seedAddrs == null || seedAddrs.length == 0) throw new PeerDiscoveryException("No IP address seeds configured; unable to find any peers"); if (pnseedIndex >= seedAddrs.length) return null; return new InetSocketAddress(convertAddress(seedAddrs[pnseedIndex++]), params.getPort()); }
/** * Instantiates the wrapper object based on an existing {@link Socket} * @throws DataSocketFailedToInitialiseException If the socket provided is <code>null</code> or if there * is any error when attempting to create the {@link DataInputStream} or {@link DataOutputStream}. * @see #initialiseIOStreams() */ public DataSocket(Socket socket) throws DataSocketFailedToInitialiseException { if(socket == null) throw new DataSocketFailedToInitialiseException(new NullPointerException("socket")); this.socket = socket; this.remoteSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); initialiseIOStreams(); log.info("New connection on socket: {}", remoteSocketAddress); }
private String getHost(final InetSocketAddress isa) { //@@@ Will this work with literal IPv6 addresses, or do we //@@@ need to wrap these in [] for the string representation? //@@@ Having it in this method at least allows for easy workarounds. return isa.isUnresolved() ? isa.getHostName() : isa.getAddress().getHostAddress(); }
@Override protected void setLocalSocketAddress(InetSocketAddress a) { if (mappingResult != null && mappingResult.isUsable()) { // Advertise the external address to contacts if (a.equals(mappingResult.getInternal())) { InetSocketAddress external = mappingResult.getExternal(); if (external != null) a = external; } } TransportProperties p = new TransportProperties(); p.put(PROP_IP_PORT, getIpPortString(a)); callback.mergeLocalProperties(p); }
@Test public void testServerHandlerNotEnoughCharsReturned() throws Exception { List<DiscoveredCube> cubes = new ArrayList<>(); MinaDiscoveryClient.DiscoveryServerHandler handler = new MinaDiscoveryClient.DiscoveryServerHandler(cubes); IoSession session = mock(IoSession.class); String host = randomAsciiOfLength(10); when(session.getRemoteAddress()).thenReturn(InetSocketAddress.createUnresolved(host, randomIntBetween(10000, 65000))); IoBuffer buffer = IoBuffer.wrap("a".getBytes(UTF_8)); handler.messageReceived(session, buffer); assertThat(cubes, hasSize(0)); }
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].getAddress().getHostAddress(), this.tracker_servers[i].getPort()); } return new TrackerGroup(trackerServers); }
private static OutputStream chooseOutputStream(String[] args) throws IOException { if (args.length > 0) { int port = Integer.parseInt(args[0]); Socket sock = new Socket(); sock.connect(new InetSocketAddress(InetAddress.getLocalHost(), port)); return sock.getOutputStream(); } else { return System.out; } }
/** * Constructs a new MockChannel instance intended for handling the actual incoming / outgoing traffic. * * @param socket The client socket. Mut not be null. * @param localAddress Address associated with the corresponding local server socket. Must not be null. * @param profile The associated profile name. * @param onClose Callback to execute when this channel is closed. */ public MockChannel(Socket socket, InetSocketAddress localAddress, String profile, Consumer<MockChannel> onClose) { this.localAddress = localAddress; this.activeChannel = socket; this.serverSocket = null; this.profile = profile; this.onClose = () -> onClose.accept(this); synchronized (openChannels) { openChannels.add(this); } }
protected ContainerManagementProtocol getContainerManagementProtocolProxy( final YarnRPC rpc, org.apache.hadoop.yarn.api.records.Token nmToken, NodeId nodeId, String user) { ContainerManagementProtocol proxy; UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user); final InetSocketAddress addr = NetUtils.createSocketAddr(nodeId.getHost(), nodeId.getPort()); if (nmToken != null) { ugi.addToken(ConverterUtils.convertFromYarn(nmToken, addr)); } proxy = NMProxy.createNMProxy(conf, ContainerManagementProtocol.class, ugi, rpc, addr); return proxy; }
public static void main(String[] args) { StringUtils.startupShutdownMessage(Portmap.class, args, LOG); final int port = RpcProgram.RPCB_PORT; Portmap pm = new Portmap(); try { pm.start(DEFAULT_IDLE_TIME_MILLISECONDS, new InetSocketAddress(port), new InetSocketAddress(port)); } catch (Throwable e) { LOG.fatal("Failed to start the server. Cause:", e); pm.shutdown(); System.exit(-1); } }
/** * Returns a description of a given host address. * * @param address an address * @return a description of the address */ public static String formatHostAddress(final InetSocketAddress address) { if (address != null) { final String host = address.getAddress().getHostAddress(); final int port = address.getPort(); return formatHostAddress(host, port); } return null; }
@Override public int getLocalPort() { SocketAddress address = exchange.getConnection().getLocalAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getPort(); } return -1; }
@Test public void testShortCircuitRenewCancelWildcardAddress() throws IOException, InterruptedException { InetSocketAddress rmAddr = new InetSocketAddress(123); InetSocketAddress serviceAddr = NetUtils.createSocketAddr( InetAddress.getLocalHost().getHostName(), rmAddr.getPort(), null); checkShortCircuitRenewCancel( rmAddr, serviceAddr, true); }
private static void reply(String msg) throws IOException { InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), reply_port); SocketChannel sc = SocketChannel.open(isa); byte b[] = msg.getBytes("UTF-8"); ByteBuffer bb = ByteBuffer.wrap(b); sc.write(bb); sc.close(); }
@Override public void registerRemote(String cluster, InetSocketAddress node) throws HekateException { if (DEBUG) { log.debug("Registering remote address [cluster={}], node={}]", cluster, node); } doRegister(cluster, node); }
/** * Using DFSUtil methods get the list of given {@code type} of address */ private Map<String, Map<String, InetSocketAddress>> getAddressListFromConf( TestType type, HdfsConfiguration conf) throws IOException { switch (type) { case NAMENODE: return DFSUtil.getNNServiceRpcAddressesForCluster(conf); case BACKUP: return DFSUtil.getBackupNodeAddresses(conf); case SECONDARY: return DFSUtil.getSecondaryNameNodeAddresses(conf); case NNRPCADDRESSES: return DFSUtil.getNNServiceRpcAddressesForCluster(conf); } return null; }
@Test public void testGoodHostsAndPorts() { InetSocketAddress compare = NetUtils.createSocketAddrForHost("localhost", 123); runGoodCases(compare, "localhost", 123); runGoodCases(compare, "localhost:", 123); runGoodCases(compare, "localhost:123", 456); }
protected static <T> T getProxy(final Configuration conf, final Class<T> protocol, final InetSocketAddress rmAddress) throws IOException { return UserGroupInformation.getCurrentUser().doAs( new PrivilegedAction<T>() { @Override public T run() { return (T) YarnRPC.create(conf).getProxy(protocol, rmAddress, conf); } }); }
public void start() throws IOException { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress(PORT)); ServiceTask.SERVICE_REGISITRY.put(RpcServiceRepository.class.getName(),SimpleRpcServiceImpl.class); LOGGER.info("start server"); try { while (true) { EXECUTOR.execute(new ServiceTask(server.accept())); } } finally { server.close(); } }