java.nio.channels.UnresolvedAddressException Java Examples

The following examples show how to use java.nio.channels.UnresolvedAddressException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: swim   Author: swimos   File: IpStation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
default IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
  try {
    final Station station = station();
    final ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    serverChannel.socket().setReuseAddress(true);
    serverChannel.socket().bind(localAddress, station().transportSettings.backlog);

    final TcpService context = new TcpService(station(), localAddress, serverChannel, service, ipSettings);
    service.setIpServiceContext(context);
    station().transport(context, FlowControl.ACCEPT);
    context.didBind();
    return context;
  } catch (IOException | UnresolvedAddressException error) {
    throw new StationException(localAddress.toString(), error);
  }
}
 
Example #2
Source Project: swim   Author: swimos   File: IpStation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
default IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
  try {
    final Station station = station();
    final ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    serverChannel.socket().setReuseAddress(true);
    serverChannel.socket().bind(localAddress, station.transportSettings.backlog);

    final TlsService context = new TlsService(station, localAddress, serverChannel, service, ipSettings);
    service.setIpServiceContext(context);
    station.transport(context, FlowControl.ACCEPT);
    context.didBind();
    return context;
  } catch (IOException | UnresolvedAddressException error) {
    throw new StationException(localAddress.toString(), error);
  }
}
 
Example #3
Source Project: swim   Author: swimos   File: IpStation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
default IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
  try {
    final Station station = station();
    final SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    ipSettings.configure(channel.socket());

    final boolean connected = channel.connect(remoteAddress);
    final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress();
    final TcpSocket context = new TcpSocket(localAddress, remoteAddress, channel, ipSettings, true);
    context.become(socket);
    if (connected) {
      station.transport(context, FlowControl.WAIT);
      context.didConnect();
    } else {
      context.willConnect();
      station.transport(context, FlowControl.CONNECT);
    }
    return context;
  } catch (IOException | UnresolvedAddressException error) {
    throw new StationException(remoteAddress.toString(), error);
  }
}
 
Example #4
Source Project: whiskey   Author: twitter   File: Socket.java    License: Apache License 2.0 6 votes vote down vote up
public ConnectFuture connect() {
    connectFuture = new ConnectFuture();

    runLoop.execute(new Runnable() {
        public void run() {
            try {
                channel = SocketChannel.open();
                channel.configureBlocking(false);
                channel.connect(new InetSocketAddress(origin.getHost(), origin.getPort()));
                reregister();
            } catch (IOException | UnresolvedAddressException e) {
                connectFuture.fail(e);
                closed = true;
            }
        }
    });

    return connectFuture;
}
 
Example #5
Source Project: xenqtt   Author: TwoGuysFromKabul   File: SyncMqttClientIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructor_InvalidHost() throws Exception {

	Throwable thrown = null;
	try {
		client = new SyncMqttClient("tcp://foo:1883", listener, 5, config);
		fail("expected exception");
	} catch (MqttInvocationException e) {
		thrown = e.getRootCause();
		assertEquals(UnresolvedAddressException.class, thrown.getClass());
	}

	verify(listener, timeout(5000)).disconnected(any(SyncMqttClient.class), same(thrown), eq(false));
	verify(reconnectionStrategy).clone();

	verifyNoMoreInteractions(listener, reconnectionStrategy);
}
 
Example #6
Source Project: xenqtt   Author: TwoGuysFromKabul   File: AsyncMqttClientIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructor_InvalidHost() throws Exception {

	Throwable thrown = null;
	try {
		client = new AsyncMqttClient("tcp://foo:1883", listener, 5, config);
		fail("expected exception");
	} catch (MqttInvocationException e) {
		thrown = e.getRootCause();
		assertEquals(UnresolvedAddressException.class, thrown.getClass());
	}

	verify(listener, timeout(5000)).disconnected(any(AsyncMqttClient.class), same(thrown), eq(false));
	verify(reconnectionStrategy).clone();

	verifyNoMoreInteractions(listener, reconnectionStrategy);
}
 
Example #7
Source Project: kafka-spark-consumer   Author: dibbhatt   File: KafkaUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static ConsumerRecords<byte[], byte[]> fetchMessages(
  KafkaConfig config, KafkaConsumer<byte[], byte[]> consumer, Partition partition,
  long offset) {
  String topic = (String) config._stateConf.get(Config.KAFKA_TOPIC);
  int partitionId = partition.partition;
  TopicPartition  topicAndPartition = new TopicPartition (topic, partitionId);
  consumer.seek(topicAndPartition, offset);
  ConsumerRecords<byte[], byte[]> records;
  try {
    records = consumer.poll(config._fillFreqMs / 2);
  } catch(InvalidOffsetException ex) {
    throw new OutOfRangeException(ex.getMessage());
  } catch (Exception e) {
    if (e instanceof KafkaException || e instanceof ConnectException
      || e instanceof SocketTimeoutException || e instanceof IOException
      || e instanceof UnresolvedAddressException) {

      LOG.warn("Network error when fetching messages:", e);
      throw new FailedFetchException(e);
    } else {
      throw new RuntimeException(e);
    }
  }
  return records;
}
 
Example #8
Source Project: directory-ldap-api   Author: apache   File: LdapNetworkConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Close the connection and generate the appropriate exception
 * 
 * @exception LdapException If we weren't able to close the connection
 */
private void close( ConnectFuture connectionFuture ) throws LdapException
{
    // disposing connector if not connected
    close();

    Throwable e = connectionFuture.getException();

    if ( e != null )
    {
        // Special case for UnresolvedAddressException
        // (most of the time no message is associated with this exception)
        if ( ( e instanceof UnresolvedAddressException ) && ( e.getMessage() == null ) )
        {
            throw new InvalidConnectionException( I18n.err( I18n.ERR_04121_CANNOT_RESOLVE_HOSTNAME, config.getLdapHost() ), e );
        }

        // Default case
        throw new InvalidConnectionException( I18n.err( I18n.ERR_04110_CANNOT_CONNECT_TO_SERVER, e.getMessage() ), e );
    }

    // We didn't received anything : this is an error
    if ( LOG.isErrorEnabled() )
    {
        LOG.error( I18n.err( I18n.ERR_04112_OP_FAILED_TIMEOUT, "Connect" ) );
    }

    throw new LdapException( TIME_OUT_ERROR );
}
 
Example #9
Source Project: neoscada   Author: eclipse   File: AutoConnectClient.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected void lookup ()
{
    fireState ( State.LOOKUP );

    // performing lookup
    final InetSocketAddress address = new InetSocketAddress ( this.address.getHostString (), this.address.getPort () );
    if ( address.isUnresolved () )
    {
        final UnresolvedAddressException e = new UnresolvedAddressException ();
        handleDisconnected ( e );
    }

    synchronized ( this )
    {
        if ( this.executor == null )
        {
            // we got disposed, do nothing
            return;
        }
        this.executor.execute ( new Runnable () {

            @Override
            public void run ()
            {
                createClient ( address );
            }
        } );
    }
}
 
Example #10
Source Project: twister2   Author: DSC-SPIDAL   File: TCPChannel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Start the connections to the servers
 * @param workerInfos information about all the workers
 */
public void startConnections(List<NetworkInfo> workerInfos) {

  for (NetworkInfo ni : workerInfos) {
    networkInfoMap.put(ni.getProcId(), ni);
    helloSendByteBuffers.add(ByteBuffer.allocate(4));
    helloReceiveByteBuffers.add(ByteBuffer.allocate(4));

    helloSendByteBuffers.add(ByteBuffer.allocate(4));
    helloReceiveByteBuffers.add(ByteBuffer.allocate(4));
  }

  // after sync we need to connect to all the servers
  for (NetworkInfo info : workerInfos) {
    if (info.getProcId() == thisInfo.getProcId()) {
      continue;
    }

    try {
      String remoteHost = TCPContext.getHostName(info);
      int remotePort = TCPContext.getPort(info);

      Client client = new Client(remoteHost, remotePort, config,
          looper, new ClientChannelHandler());
      client.connect();
      clients.put(info.getProcId(), client);
      clientChannels.put(info.getProcId(), client.getSocketChannel());
    } catch (UnresolvedAddressException e) {
      throw new RuntimeException("Failed to create client", e);
    }
  }
}
 
Example #11
Source Project: r2cloud   Author: dernasherbrezon   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
private static String getShortMessageToLog(Throwable e) {
	if (e.getCause() != null) {
		return getShortMessageToLog(e.getCause());
	}
	if (e instanceof IOException) {
		return e.getMessage();
	}
	if (e instanceof UnresolvedAddressException) {
		return e.toString();
	}
	if (e instanceof CertPathBuilderException) {
		return e.getMessage();
	}
	return null;
}
 
Example #12
Source Project: Bytecoder   Author: mirkosertic   File: Net.java    License: Apache License 2.0 5 votes vote down vote up
public static InetSocketAddress checkAddress(SocketAddress sa) {
    if (sa == null)
        throw new NullPointerException();
    if (!(sa instanceof InetSocketAddress))
        throw new UnsupportedAddressTypeException(); // ## needs arg
    InetSocketAddress isa = (InetSocketAddress)sa;
    if (isa.isUnresolved())
        throw new UnresolvedAddressException(); // ## needs arg
    InetAddress addr = isa.getAddress();
    if (!(addr instanceof Inet4Address || addr instanceof Inet6Address))
        throw new IllegalArgumentException("Invalid address type");
    return isa;
}
 
Example #13
Source Project: Bytecoder   Author: mirkosertic   File: Net.java    License: Apache License 2.0 5 votes vote down vote up
static void translateException(Exception x,
                               boolean unknownHostForUnresolved)
    throws IOException
{
    if (x instanceof IOException)
        throw (IOException)x;
    // Throw UnknownHostException from here since it cannot
    // be thrown as a SocketException
    if (unknownHostForUnresolved &&
        (x instanceof UnresolvedAddressException))
    {
         throw new UnknownHostException();
    }
    translateToSocketException(x);
}
 
Example #14
public UnresolvedHostnameErrorEventImpl
(
	Session session, 
	String rawEventData, 
	String hostName, 
	UnresolvedAddressException exception
)
{
	this.session = session;
	this.rawEventData = rawEventData;
	this.hostName = hostName;
	this.exception = exception;
}
 
Example #15
Source Project: jetbrains-plugin-graph-database-support   Author: neueda   File: Neo4jBoltDatabase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GraphQueryResult execute(String query, Map<String, Object> statementParameters) {
    try {
        Driver driver = GraphDatabase.driver(url, auth);
        try {
            try (Session session = driver.session()) {

                Neo4jBoltBuffer buffer = new Neo4jBoltBuffer();

                long startTime = System.currentTimeMillis();
                Result statementResult = session.run(query, statementParameters);
                buffer.addColumns(statementResult.keys());

                for (Record record : statementResult.list()) {
                    // Add row
                    buffer.addRow(record.asMap());
                }
                buffer.addResultSummary(statementResult.consume());
                long endTime = System.currentTimeMillis();

                return new Neo4jBoltQueryResult(endTime - startTime, buffer);
            }
        } finally {
            driver.closeAsync();
        }
    } catch (UnresolvedAddressException e) {
        throw new ClientException(e.getMessage());
    }
}
 
Example #16
Source Project: datacollector   Author: streamsets   File: OAuth2ConfigBean.java    License: Apache License 2.0 5 votes vote down vote up
private Response sendRequest(Invocation.Builder builder) throws IOException, StageException {
  Response response;
  try {
    response =
        builder.property(ClientProperties.REQUEST_ENTITY_PROCESSING, transferEncoding)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED + "; charset=utf-8")
            .post(generateRequestEntity());
  } catch (ProcessingException ex) {
    if (ex.getCause() instanceof UnresolvedAddressException || ex.getCause() instanceof UnknownHostException) {
      throw new NotFoundException(ex.getCause());
    }
    throw ex;
  }
  return response;
}
 
Example #17
Source Project: xenqtt   Author: TwoGuysFromKabul   File: AbstractMqttChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCtorInvalidHost() throws Exception {

	try {
		new TestChannel("foo", 123, clientHandler, selector, 10000);
		fail("Expected exception");
	} catch (UnresolvedAddressException e) {
		clientHandler.assertChannelOpenedCount(0);
		clientHandler.assertChannelClosedCount(1);
		clientHandler.assertLastChannelClosedCause(e);
	}
}
 
Example #18
Source Project: tajo   Author: apache   File: NettyClientBase.java    License: Apache License 2.0 5 votes vote down vote up
private ConnectException makeConnectException(InetSocketAddress address, ChannelFuture future) {
  if (future.cause() instanceof UnresolvedAddressException) {
    return new ConnectException("Can't resolve host name: " + address.toString());
  } else {
    return new ConnectTimeoutException(future.cause().getMessage());
  }
}
 
Example #19
Source Project: j2objc   Author: google   File: DatagramChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
 */
public void testConnect_Unresolved() throws IOException {
    assertFalse(this.channel1.isConnected());
    InetSocketAddress unresolved = new InetSocketAddress(
            "unresolved address", 1080);
    try {
        this.channel1.connect(unresolved);
        fail("Should throw an UnresolvedAddressException here."); //$NON-NLS-1$
    } catch (UnresolvedAddressException e) {
        // OK.
    }
}
 
Example #20
Source Project: j2objc   Author: google   File: SocketChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testCFII_Unresolved() throws IOException {
    statusNotConnected_NotPending();
    InetSocketAddress unresolved = new InetSocketAddress(
            "unresolved address", 1080);
    try {
        this.channel1.connect(unresolved);
        fail("Should throw an UnresolvedAddressException here.");
    } catch (UnresolvedAddressException e) {
        // OK.
    }
}
 
Example #21
Source Project: j2objc   Author: google   File: UnresolvedAddressExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @tests {@link java.nio.channels.UnresolvedAddressException#UnresolvedAddressException()}
 */
public void test_Constructor() {
    UnresolvedAddressException e = new UnresolvedAddressException();
    assertNull(e.getMessage());
    assertNull(e.getLocalizedMessage());
    assertNull(e.getCause());
}
 
Example #22
Source Project: grpc-java   Author: grpc   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static Status statusFromThrowable(Throwable t) {
  Status s = Status.fromThrowable(t);
  if (s.getCode() != Status.Code.UNKNOWN) {
    return s;
  }
  if (t instanceof ClosedChannelException) {
    // ClosedChannelException is used any time the Netty channel is closed. Proper error
    // processing requires remembering the error that occurred before this one and using it
    // instead.
    //
    // Netty uses an exception that has no stack trace, while we would never hope to show this to
    // users, if it happens having the extra information may provide a small hint of where to
    // look.
    ClosedChannelException extraT = new ClosedChannelException();
    extraT.initCause(t);
    return Status.UNKNOWN.withDescription("channel closed").withCause(extraT);
  }
  if (t instanceof IOException) {
    return Status.UNAVAILABLE.withDescription("io exception").withCause(t);
  }
  if (t instanceof UnresolvedAddressException) {
    return Status.UNAVAILABLE.withDescription("unresolved address").withCause(t);
  }
  if (t instanceof Http2Exception) {
    return Status.INTERNAL.withDescription("http2 exception").withCause(t);
  }
  return s;
}
 
Example #23
Source Project: swim   Author: swimos   File: IpStation.java    License: Apache License 2.0 4 votes vote down vote up
@Override
default IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
  try {
    final Station station = station();
    final SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    ipSettings.configure(channel.socket());

    final TlsSettings tlsSettings = ipSettings.tlsSettings();
    final SSLEngine sslEngine = tlsSettings.sslContext().createSSLEngine();
    sslEngine.setUseClientMode(true);
    final SNIHostName serverName = new SNIHostName(remoteAddress.getHostName());
    final List<SNIServerName> serverNames = new ArrayList<>(1);
    serverNames.add(serverName);
    final SSLParameters sslParameters = sslEngine.getSSLParameters();
    sslParameters.setServerNames(serverNames);
    sslEngine.setSSLParameters(sslParameters);
    switch (tlsSettings.clientAuth()) {
      case NEED:
        sslEngine.setNeedClientAuth(true);
        break;
      case WANT:
        sslEngine.setWantClientAuth(true);
        break;
      case NONE:
        sslEngine.setWantClientAuth(false);
        break;
      default:
    }
    final Collection<String> cipherSuites = tlsSettings.cipherSuites();
    if (cipherSuites != null) {
      sslEngine.setEnabledCipherSuites(cipherSuites.toArray(new String[cipherSuites.size()]));
    }
    final Collection<String> protocols = tlsSettings.protocols();
    if (protocols != null) {
      sslEngine.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
    }

    final boolean connected = channel.connect(remoteAddress);
    final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress();
    final TlsSocket context = new TlsSocket(localAddress, remoteAddress, channel, sslEngine, ipSettings, true);
    context.become(socket);
    if (connected) {
      station.transport(context, FlowControl.WAIT);
      context.didConnect();
    } else {
      context.willConnect();
      station.transport(context, FlowControl.CONNECT);
    }
    return context;
  } catch (IOException | UnresolvedAddressException error) {
    throw new StationException(remoteAddress.toString(), error);
  }
}
 
Example #24
Source Project: netty-4.1.22   Author: tianheframe   File: AbstractKQueueChannel.java    License: Apache License 2.0 4 votes vote down vote up
protected static void checkResolvable(InetSocketAddress addr) {
    if (addr.isUnresolved()) {
        throw new UnresolvedAddressException();
    }
}
 
Example #25
Source Project: netty-4.1.22   Author: tianheframe   File: AbstractEpollChannel.java    License: Apache License 2.0 4 votes vote down vote up
protected static void checkResolvable(InetSocketAddress addr) {
    if (addr.isUnresolved()) {
        throw new UnresolvedAddressException();
    }
}
 
Example #26
Source Project: directory-ldap-api   Author: apache   File: LdapNetworkConnection.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Process the connect. 
 * 
 * @exception LdapException If we weren't able to connect
 * @return A Future that can be used to check the status of the connection
 */
public ConnectFuture tryConnect() throws LdapException
{
    // Build the connection address
    SocketAddress address = new InetSocketAddress( config.getLdapHost(), config.getLdapPort() );
    ConnectFuture connectionFuture = connector.connect( address );
    boolean result = false;

    // Wait until it's established
    try
    {
        result = connectionFuture.await( timeout );
    }
    catch ( InterruptedException e )
    {
        connector.dispose();
        connector = null;

        if ( LOG.isDebugEnabled() )
        {
            LOG.debug( I18n.msg( I18n.MSG_04120_INTERRUPTED_WAITING_FOR_CONNECTION, 
                config.getLdapHost(),
                config.getLdapPort() ), e );
        }
        
        throw new LdapOtherException( e.getMessage(), e );
    }

    if ( !result )
    {
        // It may be an exception, or a timeout
        Throwable connectionException = connectionFuture.getException();

        connector = null;

        if ( connectionException == null )
        {
            // This was a timeout
            String message = I18n.msg( I18n.MSG_04177_CONNECTION_TIMEOUT, timeout );
            
            if ( LOG.isDebugEnabled() )
            {
                LOG.debug( message );
            }
            
            throw new LdapConnectionTimeOutException( message );
        }
        else
        {
            if ( LOG.isDebugEnabled() )
            {
                if ( ( connectionException instanceof ConnectException )
                    || ( connectionException instanceof UnresolvedAddressException ) )
                {
                    // No need to wait
                    // We know that there was a permanent error such as "connection refused".
                    LOG.debug( I18n.msg( I18n.MSG_04144_CONNECTION_ERROR, connectionFuture.getException().getMessage() ) );
                }

                LOG.debug( I18n.msg( I18n.MSG_04120_INTERRUPTED_WAITING_FOR_CONNECTION, 
                    config.getLdapHost(),
                    config.getLdapPort() ), connectionException );
            }
            
            throw new LdapOtherException( connectionException.getMessage(), connectionException );
        }
    }
    
    return connectionFuture;
}
 
Example #27
Source Project: r2cloud   Author: dernasherbrezon   File: UtilTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testLogErrorShortMessage() {
	Logger mock = Mockito.mock(Logger.class);
	Util.logIOException(mock, "unable to save", new CompletionException(createConnectException(new UnresolvedAddressException())));
	Mockito.verify(mock).error("{}: {}", "unable to save", "java.nio.channels.UnresolvedAddressException");
}
 
Example #28
public UnresolvedAddressException getException()
{
	return exception;
}
 
Example #29
Source Project: netty4.0.27Learn   Author: wuyinxian124   File: AbstractEpollChannel.java    License: Apache License 2.0 4 votes vote down vote up
protected static void checkResolvable(InetSocketAddress addr) {
    if (addr.isUnresolved()) {
        throw new UnresolvedAddressException();
    }
}
 
Example #30
Source Project: jlibs   Author: santhosh-tekuri   File: NIOUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isConnectionFailure(Throwable thr){
    return thr instanceof UnresolvedAddressException
            || thr instanceof ConnectException
            || thr instanceof PortUnreachableException;
}