类java.nio.channels.UnresolvedAddressException源码实例Demo

下面列出了怎么用java.nio.channels.UnresolvedAddressException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: swim   文件: IpStation.java
@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);
  }
}
 
源代码2 项目: swim   文件: IpStation.java
@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);
  }
}
 
源代码3 项目: swim   文件: IpStation.java
@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);
  }
}
 
源代码4 项目: whiskey   文件: Socket.java
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;
}
 
源代码5 项目: xenqtt   文件: SyncMqttClientIT.java
@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);
}
 
源代码6 项目: xenqtt   文件: AsyncMqttClientIT.java
@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);
}
 
源代码7 项目: kafka-spark-consumer   文件: KafkaUtils.java
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;
}
 
/**
 * 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 );
}
 
源代码9 项目: neoscada   文件: AutoConnectClient.java
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 );
            }
        } );
    }
}
 
源代码10 项目: twister2   文件: TCPChannel.java
/**
 * 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);
    }
  }
}
 
源代码11 项目: r2cloud   文件: Util.java
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;
}
 
源代码12 项目: Bytecoder   文件: Net.java
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;
}
 
源代码13 项目: Bytecoder   文件: Net.java
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);
}
 
public UnresolvedHostnameErrorEventImpl
(
	Session session, 
	String rawEventData, 
	String hostName, 
	UnresolvedAddressException exception
)
{
	this.session = session;
	this.rawEventData = rawEventData;
	this.hostName = hostName;
	this.exception = exception;
}
 
@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());
    }
}
 
源代码16 项目: datacollector   文件: OAuth2ConfigBean.java
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;
}
 
源代码17 项目: xenqtt   文件: AbstractMqttChannelTest.java
@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);
	}
}
 
源代码18 项目: tajo   文件: NettyClientBase.java
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());
  }
}
 
源代码19 项目: j2objc   文件: DatagramChannelTest.java
/**
 * 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.
    }
}
 
源代码20 项目: j2objc   文件: SocketChannelTest.java
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.
    }
}
 
源代码21 项目: j2objc   文件: UnresolvedAddressExceptionTest.java
/**
 * @tests {@link java.nio.channels.UnresolvedAddressException#UnresolvedAddressException()}
 */
public void test_Constructor() {
    UnresolvedAddressException e = new UnresolvedAddressException();
    assertNull(e.getMessage());
    assertNull(e.getLocalizedMessage());
    assertNull(e.getCause());
}
 
源代码22 项目: grpc-java   文件: Utils.java
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;
}
 
源代码23 项目: swim   文件: IpStation.java
@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);
  }
}
 
源代码24 项目: netty-4.1.22   文件: AbstractKQueueChannel.java
protected static void checkResolvable(InetSocketAddress addr) {
    if (addr.isUnresolved()) {
        throw new UnresolvedAddressException();
    }
}
 
源代码25 项目: netty-4.1.22   文件: AbstractEpollChannel.java
protected static void checkResolvable(InetSocketAddress addr) {
    if (addr.isUnresolved()) {
        throw new UnresolvedAddressException();
    }
}
 
源代码26 项目: directory-ldap-api   文件: LdapNetworkConnection.java
/**
 * 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;
}
 
源代码27 项目: r2cloud   文件: UtilTest.java
@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");
}
 
public UnresolvedAddressException getException()
{
	return exception;
}
 
源代码29 项目: netty4.0.27Learn   文件: AbstractEpollChannel.java
protected static void checkResolvable(InetSocketAddress addr) {
    if (addr.isUnresolved()) {
        throw new UnresolvedAddressException();
    }
}
 
源代码30 项目: jlibs   文件: NIOUtil.java
public static boolean isConnectionFailure(Throwable thr){
    return thr instanceof UnresolvedAddressException
            || thr instanceof ConnectException
            || thr instanceof PortUnreachableException;
}
 
 类所在包
 类方法
 同包方法