use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class CitrixMonitor method poll.
// read()
/**
* {@inheritDoc}
*
* Poll the specified address for Citrix service availability.
*
* During the poll an attempt is made to connect on the specified port (by
* default port 1494). If the connection request is successful, the banner
* line generated by the interface is parsed and if the extracted return
* code indicates that we are talking to an Citrix server ('ICA' appears in
* the response) we set the service status to SERVICE_AVAILABLE and return.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
// Get the category logger
//
// get the parameters
//
TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
// Extract the address
//
InetAddress ipv4Addr = svc.getAddress();
String host = InetAddressUtils.str(ipv4Addr);
LOG.debug("CitrixMonitor.poll: Polling interface: {} {}", host, timeoutTracker);
PollStatus serviceStatus = PollStatus.unavailable();
for (timeoutTracker.reset(); timeoutTracker.shouldRetry() && !serviceStatus.isAvailable(); timeoutTracker.nextAttempt()) {
Socket socket = null;
try {
timeoutTracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipv4Addr, port), timeoutTracker.getConnectionTimeout());
socket.setSoTimeout(timeoutTracker.getSoTimeout());
LOG.debug("CitrixMonitor: connected to host: {} on port: {}", host, port);
// We're connected, so upgrade status to unresponsive
// Allocate a line reader
//
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuffer buffer = new StringBuffer();
//
while (!serviceStatus.isAvailable()) {
buffer.append((char) reader.read());
if (buffer.toString().indexOf("ICA") > -1) {
serviceStatus = PollStatus.available(timeoutTracker.elapsedTimeInMillis());
} else {
serviceStatus = PollStatus.unavailable("magic cookie 'ICA' missing from service greeting.");
}
}
} catch (ConnectException e) {
// Connection refused!! Continue to retry.
String reason = "Connection refused by host " + host;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (NoRouteToHostException e) {
// No route to host!! Try retries anyway in case strict timeouts are enabled
String reason = "Unable to test host " + host + ", no route available";
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (InterruptedIOException e) {
String reason = "did not connect to host " + host + " within timeout: " + timeoutTracker;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "Error communicating with host " + host;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (Throwable t) {
String reason = "Undeclared throwable exception caught contacting host " + host;
LOG.debug(reason, t);
serviceStatus = PollStatus.unavailable(reason);
} finally {
try {
if (socket != null) {
socket.close();
socket = null;
}
} catch (IOException e) {
}
}
}
//
return serviceStatus;
}
use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class DominoIIOPMonitor method poll.
// read()
/**
* {@inheritDoc}
*
* Poll the specified address for service availability.
*
* During the poll an attempt is made to connect on the specified port. If
* the connection request is successful, the banner line generated by the
* interface is parsed and if the banner text indicates that we are talking
* to Provided that the interface's response is valid we set the service
* status to SERVICE_AVAILABLE and return.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
//
// Process parameters
//
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
int IORport = ParameterMap.getKeyedInteger(parameters, "ior-port", DEFAULT_IORPORT);
// Port
//
int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
// Get the address instance.
//
InetAddress ipAddr = svc.getAddress();
final String hostAddress = InetAddressUtils.str(ipAddr);
LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
//
try {
retrieveIORText(hostAddress, IORport);
} catch (Throwable e) {
String reason = "failed to get the corba IOR from " + ipAddr;
LOG.debug(reason, e);
return PollStatus.unavailable(reason);
}
PollStatus status = null;
for (tracker.reset(); tracker.shouldRetry() && !status.isAvailable(); tracker.nextAttempt()) {
Socket socket = null;
try {
//
// create a connected socket
//
tracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("DominoIIOPMonitor: connected to host: {} on port: {}", ipAddr, port);
return PollStatus.up(tracker.elapsedTimeInMillis());
} catch (NoRouteToHostException e) {
String reason = " No route to host exception for address " + hostAddress;
LOG.debug(reason, e);
status = PollStatus.unavailable(reason);
} catch (InterruptedIOException e) {
String reason = "did not connect to host with " + tracker;
LOG.debug(reason);
status = PollStatus.unavailable(reason);
} catch (ConnectException e) {
String reason = "Connection exception for address: " + ipAddr + " : " + e.getMessage();
LOG.debug(reason);
status = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "IOException while polling address: " + ipAddr + " : " + e.getMessage();
LOG.debug(reason);
status = PollStatus.unavailable(reason);
} finally {
try {
// Close the socket
if (socket != null)
socket.close();
} catch (IOException e) {
e.fillInStackTrace();
LOG.debug("DominoIIOPMonitor: Error closing socket.", e);
}
}
}
//
return status;
}
use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class NsclientManager method init.
/**
* This method creates a new socket and attempts to connect to the remote
* service. The input and output streams are created after the socket is
* connected.
*
* @throws org.opennms.protocols.nsclient.NsclientException
* if the hostname is unknown if the connection is refused if
* there is no route to the host if the host did not respond
* if there was an unexpected IO error. The thrown exception
* contains the causing exception.
*/
public void init() throws NsclientException {
try {
// set up socket
m_Socket = new Socket();
m_Socket.connect(new InetSocketAddress(m_HostName, m_PortNumber), m_Timeout);
m_Socket.setSoTimeout(m_Timeout);
// get buffer streams for read/write.
m_BufInStream = new BufferedInputStream(m_Socket.getInputStream());
m_ByteArrayOutStream = new ByteArrayOutputStream();
// handle exceptions.
} catch (UnknownHostException e) {
closeSocketAndThrow(new NsclientException("Unknown host: " + m_HostName, e));
} catch (ConnectException e) {
closeSocketAndThrow(new NsclientException("Connection refused to " + m_HostName + ":" + m_PortNumber, e));
} catch (NoRouteToHostException e) {
closeSocketAndThrow(new NsclientException("Unable to connect to host: " + m_HostName + ", no route to host.", e));
} catch (InterruptedIOException e) {
closeSocketAndThrow(new NsclientException("Unable to connect to host: " + m_HostName + ":" + m_PortNumber + ", exceeded timeout of " + m_Timeout, e));
} catch (IOException e) {
closeSocketAndThrow(new NsclientException("An unexpected I/O exception occured connecting to host: " + m_HostName + ":" + m_PortNumber, e));
}
}
use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class JMXDetector method isServiceDetected.
public final boolean isServiceDetected(final InetAddress address, Map<String, String> runtimeAttributes) {
final String ipAddr = InetAddressUtils.str(address);
final int port = getPort();
final int retries = getRetries();
final int timeout = getTimeout();
LOG.info("isServiceDetected: {}: Checking address: {} for capability on port {}", getServiceName(), ipAddr, port);
for (int attempts = 0; attempts < retries; attempts++) {
try (final JmxServerConnectionWrapper client = this.connect(address, port, timeout, runtimeAttributes)) {
LOG.info("isServiceDetected: {}: Attempting to connect to address: {}, port: {}, attempt: #{}", getServiceName(), ipAddr, port, attempts);
if (client.getMBeanServerConnection().getMBeanCount() <= 0) {
return false;
}
if (m_object != null) {
client.getMBeanServerConnection().getObjectInstance(new ObjectName(m_object));
}
return true;
} catch (ConnectException e) {
// Connection refused!! Continue to retry.
LOG.info("isServiceDetected: {}: Unable to connect to address: {} port {}, attempt #{}", getServiceName(), ipAddr, port, attempts, e);
} catch (NoRouteToHostException e) {
// No Route to host!!!
LOG.info("isServiceDetected: {}: No route to address {} was available", getServiceName(), ipAddr, e);
} catch (final PortUnreachableException e) {
// Port unreachable
LOG.info("isServiceDetected: {}: Port unreachable while connecting to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
} catch (InterruptedIOException e) {
// Expected exception
LOG.info("isServiceDetected: {}: Did not connect to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
} catch (MalformedObjectNameException e) {
LOG.info("isServiceDetected: {}: Object instance {} is not valid on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
} catch (InstanceNotFoundException e) {
LOG.info("isServiceDetected: {}: Object instance {} does not exists on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
} catch (IOException e) {
// NMS-8096: Because the JMX connections wrap lower-level exceptions in an IOException,
// we need to unwrap the exceptions to provide INFO log messages about failures
boolean loggedIt = false;
// Unwrap exception
Throwable cause = e.getCause();
while (cause != null && loggedIt == false) {
if (cause instanceof ConnectException) {
// Connection refused!! Continue to retry.
LOG.info("isServiceDetected: {}: Unable to connect to address: {} port {}, attempt #{}", getServiceName(), ipAddr, port, attempts, e);
loggedIt = true;
} else if (cause instanceof NoRouteToHostException) {
// No Route to host!!!
LOG.info("isServiceDetected: {}: No route to address {} was available", getServiceName(), ipAddr, e);
loggedIt = true;
} else if (cause instanceof PortUnreachableException) {
// Port unreachable
LOG.info("isServiceDetected: {}: Port unreachable while connecting to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof InterruptedIOException) {
// Expected exception
LOG.info("isServiceDetected: {}: Did not connect to address {} port {} within timeout: {} attempt: {}", getServiceName(), ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof NameNotFoundException) {
LOG.info("isServiceDetected: {}: Name {} not found on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof MalformedObjectNameException) {
LOG.info("isServiceDetected: {}: Object instance {} is not valid on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
loggedIt = true;
} else if (cause instanceof InstanceNotFoundException) {
LOG.info("isServiceDetected: {}: Object instance {} does not exists on address {} port {} within timeout: {} attempt: {}", getServiceName(), m_object, ipAddr, port, timeout, attempts, e);
loggedIt = true;
}
cause = cause.getCause();
}
if (!loggedIt) {
// If none of the causes are an expected type, log an error
LOG.error("isServiceDetected: {}: An unexpected I/O exception occured contacting address {} port {}", getServiceName(), ipAddr, port, e);
}
} catch (Throwable t) {
LOG.error("isServiceDetected: {}: Unexpected error trying to detect {} on address {} port {}", getServiceName(), getServiceName(), ipAddr, port, t);
}
}
return false;
}
use of java.net.NoRouteToHostException in project android_frameworks_base by DirtyUnicorns.
the class MediaHTTPConnection method seekTo.
private void seekTo(long offset) throws IOException {
teardownConnection();
try {
int response;
int redirectCount = 0;
URL url = mURL;
// do not use any proxy for localhost (127.0.0.1)
boolean noProxy = isLocalHost(url);
while (true) {
if (noProxy) {
mConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} else {
mConnection = (HttpURLConnection) url.openConnection();
}
mConnection.setConnectTimeout(CONNECT_TIMEOUT_MS);
// handle redirects ourselves if we do not allow cross-domain redirect
mConnection.setInstanceFollowRedirects(mAllowCrossDomainRedirect);
if (mHeaders != null) {
for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
mConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
if (offset > 0) {
mConnection.setRequestProperty("Range", "bytes=" + offset + "-");
}
response = mConnection.getResponseCode();
if (response != HttpURLConnection.HTTP_MULT_CHOICE && response != HttpURLConnection.HTTP_MOVED_PERM && response != HttpURLConnection.HTTP_MOVED_TEMP && response != HttpURLConnection.HTTP_SEE_OTHER && response != HTTP_TEMP_REDIRECT) {
// not a redirect, or redirect handled by HttpURLConnection
break;
}
if (++redirectCount > MAX_REDIRECTS) {
throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
String method = mConnection.getRequestMethod();
if (response == HTTP_TEMP_REDIRECT && !method.equals("GET") && !method.equals("HEAD")) {
// automatically redirect the request"
throw new NoRouteToHostException("Invalid redirect");
}
String location = mConnection.getHeaderField("Location");
if (location == null) {
throw new NoRouteToHostException("Invalid redirect");
}
url = new URL(mURL, /* TRICKY: don't use url! */
location);
if (!url.getProtocol().equals("https") && !url.getProtocol().equals("http")) {
throw new NoRouteToHostException("Unsupported protocol redirect");
}
boolean sameProtocol = mURL.getProtocol().equals(url.getProtocol());
if (!mAllowCrossProtocolRedirect && !sameProtocol) {
throw new NoRouteToHostException("Cross-protocol redirects are disallowed");
}
boolean sameHost = mURL.getHost().equals(url.getHost());
if (!mAllowCrossDomainRedirect && !sameHost) {
throw new NoRouteToHostException("Cross-domain redirects are disallowed");
}
if (response != HTTP_TEMP_REDIRECT) {
// update effective URL, unless it is a Temporary Redirect
mURL = url;
}
}
if (mAllowCrossDomainRedirect) {
// remember the current, potentially redirected URL if redirects
// were handled by HttpURLConnection
mURL = mConnection.getURL();
}
if (response == HttpURLConnection.HTTP_PARTIAL) {
// Partial content, we cannot just use getContentLength
// because what we want is not just the length of the range
// returned but the size of the full content if available.
String contentRange = mConnection.getHeaderField("Content-Range");
mTotalSize = -1;
if (contentRange != null) {
// format is "bytes xxx-yyy/zzz
// where "zzz" is the total number of bytes of the
// content or '*' if unknown.
int lastSlashPos = contentRange.lastIndexOf('/');
if (lastSlashPos >= 0) {
String total = contentRange.substring(lastSlashPos + 1);
try {
mTotalSize = Long.parseLong(total);
} catch (NumberFormatException e) {
}
}
}
} else if (response != HttpURLConnection.HTTP_OK) {
throw new IOException();
} else {
mTotalSize = mConnection.getContentLength();
}
if (offset > 0 && response != HttpURLConnection.HTTP_PARTIAL) {
// data from the start of the content.
throw new ProtocolException();
}
mInputStream = new BufferedInputStream(mConnection.getInputStream());
mCurrentOffset = offset;
} catch (IOException e) {
mTotalSize = -1;
mInputStream = null;
mConnection = null;
mCurrentOffset = -1;
throw e;
}
}
Aggregations