use of java.net.NoRouteToHostException in project ExoPlayer by google.
the class DefaultHttpDataSource method makeConnection.
/**
* Establishes a connection, following redirects to do so where permitted.
*/
private HttpURLConnection makeConnection(DataSpec dataSpec) throws IOException {
URL url = new URL(dataSpec.uri.toString());
byte[] postBody = dataSpec.postBody;
long position = dataSpec.position;
long length = dataSpec.length;
boolean allowGzip = dataSpec.isFlagSet(DataSpec.FLAG_ALLOW_GZIP);
if (!allowCrossProtocolRedirects) {
// automatically. This is the behavior we want, so use it.
return makeConnection(url, postBody, position, length, allowGzip, true);
}
// We need to handle redirects ourselves to allow cross-protocol redirects.
int redirectCount = 0;
while (redirectCount++ <= MAX_REDIRECTS) {
HttpURLConnection connection = makeConnection(url, postBody, position, length, allowGzip, false);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MULT_CHOICE || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER || (postBody == null && (responseCode == 307 || /* HTTP_TEMP_REDIRECT */
responseCode == 308))) {
// For 300, 301, 302, and 303 POST requests follow the redirect and are transformed into
// GET requests. For 307 and 308 POST requests are not redirected.
postBody = null;
String location = connection.getHeaderField("Location");
connection.disconnect();
url = handleRedirect(url, location);
} else {
return connection;
}
}
// If we get here we've been redirected more times than are permitted.
throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
use of java.net.NoRouteToHostException in project android_frameworks_base by AOSPA.
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;
}
}
use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class NrpeMonitor method poll.
/**
* {@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) {
String reason = null;
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
String command = ParameterMap.getKeyedString(parameters, "command", NrpePacket.HELLO_COMMAND);
int port = ParameterMap.getKeyedInteger(parameters, "port", CheckNrpe.DEFAULT_PORT);
int padding = ParameterMap.getKeyedInteger(parameters, "padding", NrpePacket.DEFAULT_PADDING);
boolean useSsl = ParameterMap.getKeyedBoolean(parameters, "usessl", DEFAULT_USE_SSL);
/*
// Port
//
int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
if (port == DEFAULT_PORT) {
throw new RuntimeException("NrpeMonitor: required parameter 'port' is not present in supplied properties.");
}
*/
// BannerMatch
//
//Commented out because it is not currently referenced in this monitor
//String strBannerMatch = (String) parameters.get("banner");
// Get the address instance.
//
InetAddress ipv4Addr = svc.getAddress();
final String hostAddress = InetAddressUtils.str(ipv4Addr);
LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
// Give it a whirl
//
int serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
Double responseTime = null;
for (tracker.reset(); tracker.shouldRetry() && serviceStatus != PollStatus.SERVICE_AVAILABLE; tracker.nextAttempt()) {
Socket socket = null;
try {
//
// create a connected socket
//
tracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipv4Addr, port), tracker.getConnectionTimeout());
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("NrpeMonitor: connected to host: {} on port: {}", ipv4Addr, port);
reason = "Perhaps check the value of 'usessl' for this monitor against the NRPE daemon configuration";
socket = wrapSocket(socket, useSsl);
// We're connected, so upgrade status to unresponsive
serviceStatus = PollStatus.SERVICE_UNRESPONSIVE;
reason = "Connected successfully, but no response received";
NrpePacket p = new NrpePacket(NrpePacket.QUERY_PACKET, (short) 0, command);
byte[] b = p.buildPacket(padding);
OutputStream o = socket.getOutputStream();
o.write(b);
/*
if (strBannerMatch == null || strBannerMatch.length() == 0 || strBannerMatch.equals("*")) {
if (true) {
serviceStatus = SERVICE_AVAILABLE;
// Store response time in RRD
if (responseTime >= 0 && rrdPath != null) {
try {
this.updateRRD(rrdPath, ipv4Addr, dsName, responseTime, pkg);
} catch (RuntimeException rex) {
LOG.debug("There was a problem writing the RRD: {}", rex);
}
}
break;
}
BufferedReader rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//
// Tokenize the Banner Line, and check the first
// line for a valid return.
//
String response = rdr.readLine();
responseTime = System.currentTimeMillis() - sentTime;
if (response == null)
continue;
LOG.debug("poll: banner = {}", response);
LOG.debug("poll: responseTime= {}ms", responseTime);
if (response.indexOf(strBannerMatch) > -1) {
*/
NrpePacket response = NrpePacket.receivePacket(socket.getInputStream(), padding);
responseTime = tracker.elapsedTimeInMillis();
if (response.getResultCode() == 0) {
serviceStatus = PollStatus.SERVICE_AVAILABLE;
reason = null;
} else {
serviceStatus = PollStatus.SERVICE_UNAVAILABLE;
reason = "NRPE command returned code " + response.getResultCode() + " and message: " + response.getBuffer();
}
} catch (NoRouteToHostException e) {
reason = "No route to host exception for address " + hostAddress;
LOG.warn("poll: {}", reason, e);
} catch (InterruptedIOException e) {
reason = "did not connect to host within " + tracker;
LOG.debug("NrpeMonitor: did not connect to host within {}", tracker);
} catch (ConnectException e) {
reason = "Connection exception for address: " + ipv4Addr;
//
if (LOG.isDebugEnabled()) {
e.fillInStackTrace();
LOG.debug("poll: {}", reason, e);
}
} catch (NrpeException e) {
reason = "NrpeException while polling address: " + ipv4Addr;
if (LOG.isDebugEnabled()) {
e.fillInStackTrace();
LOG.debug("poll: {}", reason, e);
}
} catch (IOException e) {
// Ignore
reason = "IOException while polling address: " + ipv4Addr;
if (LOG.isDebugEnabled()) {
e.fillInStackTrace();
LOG.debug("poll: {}", reason, e);
}
} finally {
try {
// Close the socket
if (socket != null) {
socket.close();
}
} catch (IOException e) {
if (LOG.isDebugEnabled()) {
e.fillInStackTrace();
LOG.debug("poll: Error closing socket.", e);
}
}
}
}
//
if (reason == null) {
return PollStatus.get(serviceStatus, responseTime);
} else {
return PollStatus.get(serviceStatus, reason);
}
}
use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class TcpMonitor method poll.
/**
* {@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
//
//
// Get interface address from NetworkInterface
//
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
// Port
//
int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
if (port == DEFAULT_PORT) {
throw new RuntimeException("TcpMonitor: required parameter 'port' is not present in supplied properties.");
}
// BannerMatch
//
String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
// Get the address instance.
//
InetAddress ipAddr = svc.getAddress();
final String hostAddress = InetAddressUtils.str(ipAddr);
LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
// Give it a whirl
//
PollStatus serviceStatus = PollStatus.unavailable();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
Socket socket = null;
try {
tracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("TcpMonitor: connected to host: {} on port: {}", ipAddr, port);
// We're connected, so upgrade status to unresponsive
serviceStatus = PollStatus.unresponsive();
if (strBannerMatch == null || strBannerMatch.length() == 0 || strBannerMatch.equals("*")) {
serviceStatus = PollStatus.available(tracker.elapsedTimeInMillis());
break;
}
BufferedReader rdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//
// Tokenize the Banner Line, and check the first
// line for a valid return.
//
String response = rdr.readLine();
double responseTime = tracker.elapsedTimeInMillis();
if (response == null)
continue;
LOG.debug("poll: banner = {}", response);
LOG.debug("poll: responseTime= {}ms", responseTime);
//Could it be a regex?
if (strBannerMatch.charAt(0) == '~') {
if (!response.matches(strBannerMatch.substring(1)))
serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
else
serviceStatus = PollStatus.available(responseTime);
} else {
if (response.indexOf(strBannerMatch) > -1) {
serviceStatus = PollStatus.available(responseTime);
} else {
serviceStatus = PollStatus.unavailable("Banner: '" + response + "' does not contain match string '" + strBannerMatch + "'");
}
}
} catch (NoRouteToHostException e) {
String reason = "No route to host exception for address " + hostAddress;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
// Break out of for(;;)
break;
} catch (InterruptedIOException e) {
String reason = "did not connect to host with " + tracker;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
} catch (ConnectException e) {
String reason = "Connection exception for address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "IOException while polling address: " + ipAddr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} finally {
try {
// Close the socket
if (socket != null)
socket.close();
} catch (IOException e) {
e.fillInStackTrace();
LOG.debug("poll: Error closing socket.", e);
}
}
}
//
return serviceStatus;
}
use of java.net.NoRouteToHostException in project opennms by OpenNMS.
the class TrivialTimeMonitor method pollTimeTcp.
/**
* <p>pollTimeTcp</p>
*
* @param svc a {@link org.opennms.netmgt.poller.MonitoredService} object.
* @param parameters a {@link java.util.Map} object.
* @param serviceStatus a {@link org.opennms.netmgt.poller.PollStatus} object.
* @param tracker a {@link org.opennms.core.utils.TimeoutTracker} object.
* @param ipv4Addr a {@link java.net.InetAddress} object.
* @param port a int.
* @param allowedSkew a int.
* @param persistSkew a boolean.
* @return a {@link org.opennms.netmgt.poller.PollStatus} object.
*/
public PollStatus pollTimeTcp(MonitoredService svc, Map<String, Object> parameters, PollStatus serviceStatus, TimeoutTracker tracker, InetAddress ipv4Addr, int port, int allowedSkew, boolean persistSkew) {
int localTime = 0;
int remoteTime = 0;
boolean gotTime = false;
for (tracker.reset(); tracker.shouldRetry() && !gotTime; tracker.nextAttempt()) {
Socket socket = null;
try {
tracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipv4Addr, port), tracker.getConnectionTimeout());
socket.setSoTimeout(tracker.getSoTimeout());
LOG.debug("Connected to host: {} on TCP port: {}", ipv4Addr, port);
//
// Try to read from the socket
//
byte[] timeBytes = new byte[4];
ByteBuffer timeByteBuffer = ByteBuffer.wrap(timeBytes);
int bytesRead = socket.getInputStream().read(timeBytes);
if (bytesRead != 4)
continue;
LOG.debug("pollTimeTcp: bytes read = {}", bytesRead);
try {
remoteTime = timeByteBuffer.getInt();
} catch (BufferUnderflowException bue) {
LOG.error("Encountered buffer underflow while reading time from remote socket.");
remoteTime = 0;
serviceStatus = PollStatus.unavailable("Failed to read a valid time from remote host.");
// to next iteration of for() loop
continue;
}
localTime = (int) (System.currentTimeMillis() / 1000) - EPOCH_ADJ_FACTOR;
gotTime = true;
serviceStatus = qualifyTime(remoteTime, localTime, allowedSkew, serviceStatus, tracker.elapsedTimeInMillis(), persistSkew);
} catch (NoRouteToHostException e) {
String reason = "No route to host exception for address " + InetAddressUtils.str(ipv4Addr);
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (InterruptedIOException e) {
String reason = "did not connect to host with " + tracker;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
} catch (ConnectException e) {
String reason = "Connection exception for address: " + ipv4Addr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "IOException while polling address: " + ipv4Addr;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} finally {
try {
// Close the socket
if (socket != null)
socket.close();
} catch (IOException e) {
e.fillInStackTrace();
LOG.debug("pollTimeTcp: Error closing socket.", e);
}
}
}
return serviceStatus;
}
Aggregations