下面列出了怎么用java.nio.channels.UnresolvedAddressException的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
}
@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);
}
}
@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);
}
}
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;
}
@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);
}
@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);
}
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 );
}
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 );
}
} );
}
}
/**
* 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);
}
}
}
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;
}
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;
}
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());
}
}
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;
}
@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);
}
}
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());
}
}
/**
* 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.
}
}
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.
}
}
/**
* @tests {@link java.nio.channels.UnresolvedAddressException#UnresolvedAddressException()}
*/
public void test_Constructor() {
UnresolvedAddressException e = new UnresolvedAddressException();
assertNull(e.getMessage());
assertNull(e.getLocalizedMessage());
assertNull(e.getCause());
}
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;
}
@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);
}
}
protected static void checkResolvable(InetSocketAddress addr) {
if (addr.isUnresolved()) {
throw new UnresolvedAddressException();
}
}
protected static void checkResolvable(InetSocketAddress addr) {
if (addr.isUnresolved()) {
throw new UnresolvedAddressException();
}
}
/**
* 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;
}
@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;
}
protected static void checkResolvable(InetSocketAddress addr) {
if (addr.isUnresolved()) {
throw new UnresolvedAddressException();
}
}
public static boolean isConnectionFailure(Throwable thr){
return thr instanceof UnresolvedAddressException
|| thr instanceof ConnectException
|| thr instanceof PortUnreachableException;
}