use of java.nio.channels.UnresolvedAddressException in project robovm by robovm.
the class OldSocketChannelTest method testOpenSocketAddress.
public void testOpenSocketAddress() throws IOException {
this.channel1 = SocketChannel.open(localAddr1);
assertTrue(this.channel1.isConnected());
SocketAddress newTypeAddress = new SubSocketAddress();
try {
this.channel1 = SocketChannel.open(newTypeAddress);
fail("Should throw UnexpectedAddressTypeException");
} catch (UnsupportedAddressTypeException e) {
// expected
}
SocketAddress unresolvedAddress = InetSocketAddress.createUnresolved("127.0.0.1", 8080);
try {
this.channel1 = SocketChannel.open(unresolvedAddress);
fail("Should throw UnresolvedAddressException");
} catch (UnresolvedAddressException e) {
// expected
}
SocketChannel channel1IP = null;
try {
channel1IP = SocketChannel.open(null);
fail("Should throw an IllegalArgumentException");
} catch (IllegalArgumentException e) {
// correct
}
assertNull(channel1IP);
}
use of java.nio.channels.UnresolvedAddressException in project zookeeper by apache.
the class QuorumCnxManager method connectOne.
/**
* Try to establish a connection to server with id sid using its electionAddr.
*
* @param sid server id
* @return boolean success indication
*/
private synchronized boolean connectOne(long sid, InetSocketAddress electionAddr) {
if (senderWorkerMap.get(sid) != null) {
LOG.debug("There is a connection already for server " + sid);
return true;
}
Socket sock = null;
try {
LOG.debug("Opening channel to server " + sid);
sock = new Socket();
setSockOpts(sock);
sock.connect(electionAddr, cnxTO);
LOG.debug("Connected to server " + sid);
// finish, this may delay next peer connection requests.
if (quorumSaslAuthEnabled) {
initiateConnectionAsync(sock, sid);
} else {
initiateConnection(sock, sid);
}
return true;
} catch (UnresolvedAddressException e) {
// Sun doesn't include the address that causes this
// exception to be thrown, also UAE cannot be wrapped cleanly
// so we log the exception in order to capture this critical
// detail.
LOG.warn("Cannot open channel to " + sid + " at election address " + electionAddr, e);
closeSocket(sock);
throw e;
} catch (IOException e) {
LOG.warn("Cannot open channel to " + sid + " at election address " + electionAddr, e);
closeSocket(sock);
return false;
}
}
use of java.nio.channels.UnresolvedAddressException in project directory-ldap-api by apache.
the class LdapNetworkConnection method connect.
// -------------------------- The methods ---------------------------//
/**
* {@inheritDoc}
*/
@Override
public boolean connect() throws LdapException {
if ((ldapSession != null) && connected.get()) {
// No need to connect if we already have a connected session
return true;
}
// Create the connector if needed
if (connector == null) {
createConnector();
}
// Build the connection address
SocketAddress address = new InetSocketAddress(config.getLdapHost(), config.getLdapPort());
// And create the connection future
timeout = config.getTimeout();
long maxRetry = System.currentTimeMillis() + timeout;
ConnectFuture connectionFuture = null;
boolean interrupted = false;
while (maxRetry > System.currentTimeMillis() && !interrupted) {
connectionFuture = connector.connect(address);
boolean result = false;
// Wait until it's established
try {
result = connectionFuture.await(timeout);
} catch (InterruptedException e) {
connector.dispose();
connector = null;
LOG.debug(I18n.msg(I18n.MSG_03221_INTERRUPTED_WAITING_FOR_CONNECTION, config.getLdapHost(), config.getLdapPort()), e);
interrupted = true;
throw new LdapOtherException(e.getMessage(), e);
} finally {
if (result) {
boolean isConnected = connectionFuture.isConnected();
if (!isConnected) {
Throwable connectionException = connectionFuture.getException();
if ((connectionException instanceof ConnectException) || (connectionException instanceof UnresolvedAddressException)) {
// We know that there was a permanent error such as "connection refused".
if (LOG.isDebugEnabled()) {
LOG.debug(I18n.msg(I18n.MSG_03245_CONNECTION_ERROR, connectionFuture.getException().getMessage()));
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(I18n.msg(I18n.MSG_03244_CONNECTION_RETRYING));
}
// Wait 500 ms and retry
try {
Thread.sleep(500);
} catch (InterruptedException e) {
connector = null;
LOG.debug(I18n.msg(I18n.MSG_03221_INTERRUPTED_WAITING_FOR_CONNECTION, config.getLdapHost(), config.getLdapPort()), e);
interrupted = true;
throw new LdapOtherException(e.getMessage(), e);
}
} else {
break;
}
}
}
}
if (connectionFuture == null) {
connector.dispose();
throw new InvalidConnectionException("Cannot connect");
}
boolean isConnected = connectionFuture.isConnected();
if (!isConnected) {
// disposing connector if not connected
try {
close();
} catch (IOException ioe) {
// Nothing to do
}
Throwable e = connectionFuture.getException();
if (e != null) {
StringBuilder message = new StringBuilder("Cannot connect to the server: ");
// (most of the time no message is associated with this exception)
if ((e instanceof UnresolvedAddressException) && (e.getMessage() == null)) {
message.append("Hostname '");
message.append(config.getLdapHost());
message.append("' could not be resolved.");
throw new InvalidConnectionException(message.toString(), e);
}
// Default case
message.append(e.getMessage());
throw new InvalidConnectionException(message.toString(), e);
}
return false;
}
// Get the close future for this session
CloseFuture closeFuture = connectionFuture.getSession().getCloseFuture();
// Add a listener to close the session in the session.
closeFuture.addListener(new IoFutureListener<IoFuture>() {
@Override
public void operationComplete(IoFuture future) {
// Process all the waiting operations and cancel them
LOG.debug(I18n.msg(I18n.MSG_03238_NOD_RECEIVED));
for (ResponseFuture<?> responseFuture : futureMap.values()) {
LOG.debug(I18n.msg(I18n.MSG_03235_CLOSING, responseFuture));
responseFuture.cancel();
try {
if (responseFuture instanceof AddFuture) {
((AddFuture) responseFuture).set(AddNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof BindFuture) {
((BindFuture) responseFuture).set(BindNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof CompareFuture) {
((CompareFuture) responseFuture).set(CompareNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof DeleteFuture) {
((DeleteFuture) responseFuture).set(DeleteNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof ExtendedFuture) {
((ExtendedFuture) responseFuture).set(ExtendedNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof ModifyFuture) {
((ModifyFuture) responseFuture).set(ModifyNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof ModifyDnFuture) {
((ModifyDnFuture) responseFuture).set(ModifyDnNoDResponse.PROTOCOLERROR);
} else if (responseFuture instanceof SearchFuture) {
((SearchFuture) responseFuture).set(SearchNoDResponse.PROTOCOLERROR);
}
} catch (InterruptedException e) {
LOG.error(I18n.err(I18n.ERR_03202_ERROR_PROCESSING_NOD, responseFuture), e);
}
futureMap.remove(messageId.get());
}
futureMap.clear();
}
});
// Get back the session
ldapSession = connectionFuture.getSession();
connected.set(true);
// Store the container into the session if we don't have one
@SuppressWarnings("unchecked") LdapMessageContainer<MessageDecorator<? extends Message>> container = (LdapMessageContainer<MessageDecorator<? extends Message>>) ldapSession.getAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR);
if (container != null) {
if ((schemaManager != null) && !(container.getBinaryAttributeDetector() instanceof SchemaBinaryAttributeDetector)) {
container.setBinaryAttributeDetector(new SchemaBinaryAttributeDetector(schemaManager));
}
} else {
BinaryAttributeDetector atDetector = new DefaultConfigurableBinaryAttributeDetector();
if (schemaManager != null) {
atDetector = new SchemaBinaryAttributeDetector(schemaManager);
}
ldapSession.setAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR, new LdapMessageContainer<MessageDecorator<? extends Message>>(codec, atDetector));
}
// Initialize the MessageId
messageId.set(0);
// And return
return true;
}
use of java.nio.channels.UnresolvedAddressException in project i2p.i2p by i2p.
the class EventPumper method runDelayedEvents.
/**
* Pull off the 4 _wants* queues and update the interest ops,
* which may, according to the javadocs, be a "naive" implementation and block.
* High-frequency path in thread.
*/
private void runDelayedEvents() {
NTCPConnection con;
while ((con = _wantsRead.poll()) != null) {
SelectionKey key = con.getKey();
try {
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
} catch (CancelledKeyException cke) {
// ignore, we remove/etc elsewhere
if (_log.shouldLog(Log.WARN))
_log.warn("RDE CKE 1", cke);
} catch (IllegalArgumentException iae) {
// ...4 more
if (_log.shouldLog(Log.WARN))
_log.warn("gnu?", iae);
}
}
// check before instantiating iterator for speed
if (!_wantsWrite.isEmpty()) {
for (Iterator<NTCPConnection> iter = _wantsWrite.iterator(); iter.hasNext(); ) {
con = iter.next();
SelectionKey key = con.getKey();
if (key == null)
continue;
iter.remove();
try {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
} catch (CancelledKeyException cke) {
if (_log.shouldLog(Log.WARN))
_log.warn("RDE CKE 2", cke);
// ignore
} catch (IllegalArgumentException iae) {
// see above
if (_log.shouldLog(Log.WARN))
_log.warn("gnu?", iae);
}
}
}
// only when address changes
ServerSocketChannel chan;
while ((chan = _wantsRegister.poll()) != null) {
try {
SelectionKey key = chan.register(_selector, SelectionKey.OP_ACCEPT);
key.attach(chan);
} catch (ClosedChannelException cce) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error registering", cce);
}
}
while ((con = _wantsConRegister.poll()) != null) {
try {
SelectionKey key = con.getChannel().register(_selector, SelectionKey.OP_CONNECT);
key.attach(con);
con.setKey(key);
RouterAddress naddr = con.getRemoteAddress();
try {
// no DNS lookups, do not use host names
int port = naddr.getPort();
byte[] ip = naddr.getIP();
if (port <= 0 || ip == null)
throw new IOException("Invalid NTCP address: " + naddr);
InetSocketAddress saddr = new InetSocketAddress(InetAddress.getByAddress(ip), port);
boolean connected = con.getChannel().connect(saddr);
if (connected) {
// Never happens, we use nonblocking
// _context.statManager().addRateData("ntcp.connectImmediate", 1);
key.interestOps(SelectionKey.OP_READ);
processConnect(key);
}
} catch (IOException ioe) {
if (_log.shouldLog(Log.WARN))
_log.warn("error connecting to " + Addresses.toString(naddr.getIP(), naddr.getPort()), ioe);
_context.statManager().addRateData("ntcp.connectFailedIOE", 1);
_transport.markUnreachable(con.getRemotePeer().calculateHash());
// if (ntcpOnly(con)) {
// _context.banlist().banlistRouter(con.getRemotePeer().calculateHash(), "unable to connect: " + ioe.getMessage());
// con.close(false);
// } else {
// _context.banlist().banlistRouter(con.getRemotePeer().calculateHash(), "unable to connect: " + ioe.getMessage(), NTCPTransport.STYLE);
con.close(true);
// }
} catch (UnresolvedAddressException uae) {
if (_log.shouldLog(Log.WARN))
_log.warn("unresolved address connecting", uae);
_context.statManager().addRateData("ntcp.connectFailedUnresolved", 1);
_transport.markUnreachable(con.getRemotePeer().calculateHash());
// if (ntcpOnly(con)) {
// _context.banlist().banlistRouter(con.getRemotePeer().calculateHash(), "unable to connect/resolve: " + uae.getMessage());
// con.close(false);
// } else {
// _context.banlist().banlistRouter(con.getRemotePeer().calculateHash(), "unable to connect/resolve: " + uae.getMessage(), NTCPTransport.STYLE);
con.close(true);
// }
} catch (CancelledKeyException cke) {
con.close(false);
}
} catch (ClosedChannelException cce) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error registering", cce);
}
}
long now = System.currentTimeMillis();
if (_lastExpired + 1000 <= now) {
expireTimedOut();
_lastExpired = now;
}
}
use of java.nio.channels.UnresolvedAddressException in project BiglyBT by BiglySoftware.
the class TCPConnectionManager method addNewRequest.
private void addNewRequest(final ConnectionRequest request) {
request.setConnectTimeout(request.listener.connectAttemptStarted(request.getConnectTimeout()));
boolean ipv6problem = false;
boolean bind_failed = false;
try {
request.channel = SocketChannel.open();
InetAddress bindIP = null;
try {
// advanced socket options
if (rcv_size > 0) {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Setting socket receive buffer size" + " for outgoing connection [" + request.address + "] to: " + rcv_size));
request.channel.socket().setReceiveBufferSize(rcv_size);
}
if (snd_size > 0) {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Setting socket send buffer size " + "for outgoing connection [" + request.address + "] to: " + snd_size));
request.channel.socket().setSendBufferSize(snd_size);
}
if (ip_tos.length() > 0) {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Setting socket TOS field " + "for outgoing connection [" + request.address + "] to: " + ip_tos));
request.channel.socket().setTrafficClass(Integer.decode(ip_tos).intValue());
}
if (local_bind_port > 0) {
request.channel.socket().setReuseAddress(true);
}
try {
bindIP = NetworkAdmin.getSingleton().getMultiHomedOutgoingRoundRobinBindAddress(request.address.getAddress());
if (bindIP != null) {
if (bindIP.isAnyLocalAddress() || !AEProxyFactory.isPluginProxy(request.address)) {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Binding outgoing connection [" + request.address + "] to local IP address: " + bindIP + ":" + local_bind_port));
request.channel.socket().bind(new InetSocketAddress(bindIP, local_bind_port));
}
} else if (local_bind_port > 0) {
if (Logger.isEnabled())
Logger.log(new LogEvent(LOGID, "Binding outgoing connection [" + request.address + "] to local port #: " + local_bind_port));
request.channel.socket().bind(new InetSocketAddress(local_bind_port));
}
} catch (SocketException e) {
bind_failed = true;
String msg = e.getMessage().toLowerCase();
if ((msg.contains("address family not supported by protocol family") || msg.contains("protocol family unavailable")) && !NetworkAdmin.getSingleton().hasIPV6Potential(true)) {
ipv6problem = true;
}
throw e;
}
} catch (Throwable t) {
if (bind_failed && NetworkAdmin.getSingleton().mustBind()) {
throw (t);
} else if (!ipv6problem) {
// dont pass the exception outwards, so we will continue processing connection without advanced options set
String msg = "Error while processing advanced socket options (rcv=" + rcv_size + ", snd=" + snd_size + ", tos=" + ip_tos + ", port=" + local_bind_port + ", bind=" + bindIP + ")";
// Debug.out( msg, t );
Logger.log(new LogAlert(LogAlert.UNREPEATABLE, msg, t));
} else {
throw (t);
}
}
request.channel.configureBlocking(false);
request.connect_start_time = SystemTime.getMonotonousTime();
if (request.channel.connect(request.address)) {
// already connected
finishConnect(request);
} else {
try {
new_canceled_mon.enter();
pending_attempts.put(request, null);
} finally {
new_canceled_mon.exit();
}
connect_selector.register(request.channel, new VirtualChannelSelector.VirtualSelectorListener() {
@Override
public boolean selectSuccess(VirtualChannelSelector selector, SocketChannel sc, Object attachment) {
try {
new_canceled_mon.enter();
pending_attempts.remove(request);
} finally {
new_canceled_mon.exit();
}
finishConnect(request);
return true;
}
@Override
public void selectFailure(VirtualChannelSelector selector, SocketChannel sc, Object attachment, Throwable msg) {
try {
new_canceled_mon.enter();
pending_attempts.remove(request);
} finally {
new_canceled_mon.exit();
}
closeConnection(request.channel);
request.listener.connectFailure(msg);
}
}, null);
}
} catch (Throwable t) {
String full = request.address.toString();
String hostname = request.address.getHostName();
int port = request.address.getPort();
boolean unresolved = request.address.isUnresolved();
InetAddress inet_address = request.address.getAddress();
String full_sub = inet_address == null ? request.address.toString() : inet_address.toString();
String host_address = inet_address == null ? request.address.toString() : inet_address.getHostAddress();
String msg = "ConnectDisconnectManager::address exception: full=" + full + ", hostname=" + hostname + ", port=" + port + ", unresolved=" + unresolved + ", full_sub=" + full_sub + ", host_address=" + host_address;
if (request.channel != null) {
String channel = request.channel.toString();
Socket socket = request.channel.socket();
String socket_string = socket.toString();
InetAddress local_address = socket.getLocalAddress();
String local_address_string = local_address == null ? "<null>" : local_address.toString();
int local_port = socket.getLocalPort();
SocketAddress ra = socket.getRemoteSocketAddress();
String remote_address;
if (ra != null)
remote_address = ra.toString();
else
remote_address = "<null>";
int remote_port = socket.getPort();
msg += "\n channel=" + channel + ", socket=" + socket_string + ", local_address=" + local_address_string + ", local_port=" + local_port + ", remote_address=" + remote_address + ", remote_port=" + remote_port;
} else {
msg += "\n channel=<null>";
}
if (ipv6problem || t instanceof UnresolvedAddressException || t instanceof NoRouteToHostException) {
Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, msg));
} else {
Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, msg, t));
}
if (request.channel != null) {
closeConnection(request.channel);
}
request.listener.connectFailure(t);
}
}
Aggregations