List of usage examples for java.net UnknownHostException getMessage
public String getMessage()
From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java
public Observation getNodeObservation(Node node, Resource resource) throws WSIAdapterException { signal = new CountDownLatch(1); Observation observation = new Observation(); try {//from w w w.ja v a 2 s . c om int requestMessageID = UNDEFINED_COAP_MESSAGE_ID; boolean requestWasRespondedWithinTimelimit = false; if (isDtnEnabled) { requestMessageID = dtnObservationRequest(node, resource); requestWasRespondedWithinTimelimit = signal.await(Constants.DTN_REQUEST_TIMEOUT, TimeUnit.MINUTES); } else { requestMessageID = coapObservationRequest(node, resource); // TODO: the signal await function will return FALSE if the timeout has expired. // This allows to manage the timeout case, and possibly the re-sending of messages that the coap gateway will do (until receiving a response) // The plan is that if this request times out, the ID of the request is logged in a static/global table and we further ignore messages for this ID (we don't handle them anymore). requestWasRespondedWithinTimelimit = signal.await(Constants.SIMPLE_COAP_REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); } if (!requestWasRespondedWithinTimelimit) { //if we had timeout if (isDtnEnabled) //for DTN mode, we add it to a separate list (different callback function and messages ) { if (requestMessageID != UNDEFINED_COAP_MESSAGE_ID && !timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(requestMessageID))) { timedOut_DTN_CoapMessageIDsList.add(Integer.valueOf(requestMessageID)); } } else { //add the messageId to the list of IDs to ignore in the future (the check will be done in the callback function if (requestMessageID != UNDEFINED_COAP_MESSAGE_ID && !timedOutCoapMessageIDsList.contains(Integer.valueOf(requestMessageID))) { timedOutCoapMessageIDsList.add(Integer.valueOf(requestMessageID)); } } } else { if (resourceValue != null) { observation.setNode(node); observation.setResource(resource); observation.setValue(formatResourceValue(resourceValue, resource)); logger.debug("Retrieved and stored observation value: " + observation.getValue()); observation.setTimestamp(System.currentTimeMillis()); resourceValue = null; } else { String error = ""; if (!exceptionError.equals("")) { error = exceptionError; exceptionError = ""; } else { error = "No available resources for Node " + node.getId() + " and Resource " + resource.getName(); } throw new WSIAdapterException(error); } } } catch (UnknownHostException e) { throw new WSIAdapterException(e.getMessage(), e); } catch (InterruptedException e) { throw new WSIAdapterException(e.getMessage(), e); } catch (VitroGatewayException e) { throw new WSIAdapterException(e.getMessage(), e); } catch (IOException e) { throw new WSIAdapterException(e.getMessage(), e); } return observation; }
From source file:org.apache.cassandra.tools.Shuffle.java
/** * Create and distribute a new, randomized token to endpoint mapping. * * @throws ShuffleError on handled exceptions *///from w ww . j av a 2 s . co m public void shuffle(boolean enable, String onlyDc) throws ShuffleError { CassandraClient seedClient = null; Map<String, String> tokenMap = null; IPartitioner<?> partitioner = null; Multimap<String, String> endpointMap = HashMultimap.create(); EndpointSnitchInfoMBean epSnitchProxy = getEpSnitchProxy(jmxConn.getMbeanServerConn()); try { seedClient = getThriftClient(thriftHost, thriftPort, thriftFramed); tokenMap = seedClient.describe_token_map(); for (Map.Entry<String, String> entry : tokenMap.entrySet()) { String endpoint = entry.getValue(), token = entry.getKey(); try { if (onlyDc != null) { if (onlyDc.equals(epSnitchProxy.getDatacenter(endpoint))) endpointMap.put(endpoint, token); } else endpointMap.put(endpoint, token); } catch (UnknownHostException e) { writeln("Warning: %s unknown to EndpointSnitch!", endpoint); } } } catch (InvalidRequestException ire) { throw new RuntimeException("What that...?", ire); } catch (TException e) { throw new ShuffleError( String.format("Thrift request to %s:%d failed: %s", thriftHost, thriftPort, e.getMessage())); } partitioner = getPartitioner(thriftHost, thriftPort, thriftFramed); Multimap<String, String> relocations = calculateRelocations(endpointMap); writeln("%-42s %-15s %-15s", "Token", "From", "To"); writeln("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~"); // Store relocations on remote nodes. for (String endpoint : relocations.keySet()) { for (String tok : relocations.get(endpoint)) writeln("%-42s %-15s %-15s", tok, tokenMap.get(tok), endpoint); String cqlQuery = createShuffleBatchInsert(relocations.get(endpoint), partitioner); executeCqlQuery(endpoint, thriftPort, thriftFramed, cqlQuery); } if (enable) enableRelocations(relocations.keySet()); }
From source file:it.ventuland.ytd.YTDownloadThread.java
/** * Recursive function that perform video download * @param pVideo the video url//w w w.j a v a 2s.c o m * @return true if all ok, false otherwise */ private boolean downloadone(String pUrl, VideoElement pVideo) { BufferedReader textreader = null; BufferedInputStream binaryreader = null; YTDHttpConfig httpclient = null; boolean rc = false; // stop recursion String sURL = pUrl; try { if (sURL.equals("")) { return (false); } } catch (NullPointerException npe) { return (false); } if (isWorkerInterrupted()) { return (false); // try to get information about application shutdown } try { boolean rc204 = false; boolean rc302 = false; IYtdResponse response = null; iRecursionCount++; debugoutput("start."); httpclient = new YTDHttpConfig(sURL, GUIClient.getProxy()); response = httpclient.connect(); this.sVideoURL = null; this.sContentType = response.getFirstHeaderValue("Content-Type").toLowerCase(); debugoutput("HTTP response status line:".concat(response.getStatusLine())); // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL? if (!(rc = response.getStatusLine().matches("^(http)(.*)200(.*)")) & !(rc204 = response.getStatusLine().matches("^(http)(.*)204(.*)")) & !(rc302 = response.getStatusLine().matches("^(http)(.*)302(.*)"))) { debugoutput(response.getStatusLine().concat(" ").concat(sURL)); output(response.getStatusLine().concat(" \"").concat(this.sTitle).concat("\"")); return (rc & rc204 & rc302); } if (rc204) { debugoutput("last response code==204 - download: ".concat(this.vNextVideoURL.get(0).getsYTID())); rc = downloadone(this.vNextVideoURL.get(0).getsURL(), pVideo); return (rc); } if (rc302) { debugoutput("location from HTTP Header: ".concat(response.getFirstHeaderString("Location"))); } // real file download InputStream lResponseStream = response.getEntityContent(); if (lResponseStream != null) { if (this.sContentType.matches("^text/html(.*)")) { textreader = new BufferedReader(new InputStreamReader(lResponseStream)); rc = savetextdata(textreader, iRecursionCount, pVideo); } else if (this.sContentType.matches("video/(.)*")) { binaryreader = new BufferedInputStream(lResponseStream); if (mForceNoDownload) { reportheaderinfo(response.getNativeResponse()); } else { Long lByteMax = Long.parseLong(response.getFirstHeaderValue("Content-Length")); savebinarydata(binaryreader, lByteMax); } } else { // content-type is not video/ rc = false; this.sVideoURL = null; } } httpclient.close(); debugoutput("done: ".concat(sURL)); if (this.sVideoURL == null) { this.sVideoURL = ""; // to prevent NPE } if (!this.sVideoURL.matches(GUIClient.szURLREGEX)) { // no more recursion - html source hase been read // test !rc than video could not downloaded because of some error (like wrong protocol or restriction) if (!rc) { debugoutput("cannot download video - URL does not seem to be valid or could not be found: " .concat(this.sURL)); output("there was a problem getting the video URL! perhaps not allowed in your country?!"); output(("consider reporting the URL to author! - ").concat(this.sURL)); this.sVideoURL = null; } } else { // enter recursion - download video resource debugoutput("try to download video from URL: ".concat(this.sVideoURL)); rc = downloadone(this.sVideoURL, pVideo); } this.sVideoURL = null; } catch (UnknownHostException uhe) { output(("error connecting to: ").concat(uhe.getMessage())); debugoutput(uhe.getMessage()); rc = false; } catch (Throwable t) { debugoutput(t.getMessage()); rc = false; } finally { try { if (textreader != null) { textreader.close(); } } catch (Exception e) { } try { if (binaryreader != null) { binaryreader.close(); } } catch (Exception e) { } try { if (httpclient != null) { httpclient.close(); } } catch (Exception e) { } } return (rc); }
From source file:com.lfrj.diancan.http.AsyncHttpRequest.java
private void makeRequestWithRetries() throws IOException { boolean retry = true; IOException cause = null;// w ww .j av a 2 s. co m HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); try { while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { GSLog.LogI("info", "?" + request.getURI().toString() + "Retries[" + executionCount + "]....." + e); // switching between WI-FI and mobile data networks can // cause a retry which then results in an // UnknownHostException // while the WI-FI is initialising. The retry logic will be // invoked here, if this is NOT the first retry // (to assist in genuine cases of unknown host) which seems // better than outright failure cause = new IOException("UnknownHostException exception: " + e.getMessage()); retry = (executionCount > 0) && retryHandler.retryRequest(cause, ++executionCount, context); } catch (NullPointerException e) { GSLog.LogI("info", "?" + request.getURI().toString() + "Retries[" + executionCount + "]....." + e); // there's a bug in HttpClient 4.0.x that on some occasions // causes // DefaultRequestExecutor to throw an NPE, see // http://code.google.com/p/android/issues/detail?id=5255 cause = new IOException("NPE in HttpClient: " + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (IOException e) { GSLog.LogI("info", "?" + request.getURI().toString() + "Retries[" + executionCount + "]....." + e); if (isCancelled()) { GSLog.LogI("info", "?" + request.getURI().toString() + "?!"); // Eating exception, as the request was cancelled return; } cause = e; retry = retryHandler.retryRequest(cause, ++executionCount, context); } if (retry && (responseHandler != null)) { responseHandler.sendRetryMessage(executionCount); } } } catch (Exception e) { GSLog.LogI("info", "?" + request.getURI().toString() + "Retries[" + executionCount + "]....." + e); // catch anything else to ensure failure message is propagated Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e); cause = new IOException("Unhandled exception: " + e.getMessage()); } // cleaned up to throw IOException throw (cause); }
From source file:org.apache.manifoldcf.crawler.connectors.gridfs.GridFSRepositoryConnector.java
/** * Setup a session.// w w w.j a v a 2 s.c o m * * @throws ManifoldCFException */ protected void getSession() throws ManifoldCFException { if (session == null) { if (StringUtils.isEmpty(db) || StringUtils.isEmpty(bucket)) { throw new ManifoldCFException("GridFS: Database or bucket name cannot be empty."); } if (StringUtils.isEmpty(url)) { throw new ManifoldCFException("GridFS: Metadata URL field cannot be empty."); } if (StringUtils.isEmpty(host) && StringUtils.isEmpty(port)) { try { session = new MongoClient().getDB(db); } catch (UnknownHostException ex) { throw new ManifoldCFException( "GridFS: Default host is not found. Does mongod process run?" + ex.getMessage(), ex); } } else if (!StringUtils.isEmpty(host) && StringUtils.isEmpty(port)) { try { session = new MongoClient(host).getDB(db); } catch (UnknownHostException ex) { throw new ManifoldCFException( "GridFS: Given host information is not valid or mongod process doesn't run" + ex.getMessage(), ex); } } else if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(port)) { try { int integerPort = Integer.parseInt(port); session = new MongoClient(host, integerPort).getDB(db); } catch (UnknownHostException ex) { throw new ManifoldCFException( "GridFS: Given information is not valid or mongod process doesn't run" + ex.getMessage(), ex); } catch (NumberFormatException ex) { throw new ManifoldCFException("GridFS: Given port is not valid number. " + ex.getMessage(), ex); } } else if (StringUtils.isEmpty(host) && !StringUtils.isEmpty(port)) { try { int integerPort = Integer.parseInt(port); session = new MongoClient(host, integerPort).getDB(db); } catch (UnknownHostException ex) { throw new ManifoldCFException( "GridFS: Given information is not valid or mongod process doesn't run" + ex.getMessage(), ex); } catch (NumberFormatException ex) { throw new ManifoldCFException("GridFS: Given port is not valid number. " + ex.getMessage(), ex); } } if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { boolean auth = session.authenticate(username, password.toCharArray()); if (!auth) { throw new ManifoldCFException("GridFS: Given database username and password doesn't match."); } } lastSessionFetch = System.currentTimeMillis(); } }
From source file:com.myJava.file.driver.remote.ftp.FTPProxy.java
/** * Enforce server reconnection (closes the current connection if it is still alive) *//*ww w. j av a 2 s . c o m*/ public synchronized void connect() throws FTPConnectionException { checkLocked(); try { int reply; // Try to disconnect this.disconnect(); // Open new connection if (isSecured()) { this.client = new FTPSClient(protocol, protection, impliciteSec, null, // TODO null, // TODO ignorePsvErrors); } else { this.client = new FTPClient(ignorePsvErrors); } if (this.controlEncoding != null) { this.client.setControlEncoding(this.controlEncoding); debug("control encoding : ", controlEncoding); } //InetAddress adr = InetAddress.getByName(this.remoteServer); Logger.defaultLogger().info("Trying to connect to server : " + this.remoteServer + " ..."); debug("connect : connect", remoteServer); client.connect(remoteServer, this.remotePort); //RemoteConnectionMonitor.getInstance().registerNewConnection(client, this); Logger.defaultLogger() .info("Received FTP server response : " + formatFTPReplyString(client.getReplyString())); this.connectionId = Util.getRndLong(); reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { String msg = formatFTPReplyString(client.getReplyString()); this.disconnect(); throw new FTPConnectionException( "Unable to communicate with remote FTP server. Got message : " + msg); } else { // CONNECTION OK Logger.defaultLogger().info("Trying to log in with user : " + this.login + " ..."); debug("connect : login", login + "/" + password); if (!client.login(this.login, this.password)) { String msg = formatFTPReplyString(client.getReplyString()); this.disconnect(); throw new FTPConnectionException("Unable to login on FTP server (" + login + "/" + password + "). Received response : " + msg); } else { Logger.defaultLogger().info("Logged in with user : " + this.login + ". Received response : " + formatFTPReplyString(client.getReplyString())); // LOGIN OK if (this.passivMode) { Logger.defaultLogger().info("Switching to passive mode ..."); // PASSIVE MODE REQUESTED debug("connect : pasv"); client.enterLocalPassiveMode(); reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { String msg = formatFTPReplyString(client.getReplyString()); this.disconnect(); throw new FTPConnectionException( "Unable to switch to passive mode. Received response : " + msg); } else { this.updateOpTime(); } // PASSIV MODE OK } else { this.updateOpTime(); } debug("connect : bin"); client.setFileType(FTP.BINARY_FILE_TYPE); Logger.defaultLogger().info("Connected to server : " + this.remoteServer); } } } catch (UnknownHostException e) { resetClient(e); throw new FTPConnectionException("Unknown server : " + this.remoteServer); } catch (SocketException e) { resetClient(e); throw new FTPConnectionException("Error during FTP connection : " + e.getMessage()); } catch (IOException e) { resetClient(e); throw new FTPConnectionException("Error during FTP connection : " + e.getMessage()); } finally { clearCache(); } }
From source file:org.opensmartgridplatform.adapter.protocol.dlms.domain.factories.Hls5Connector.java
@Override public DlmsConnection connect(final DlmsDevice device, final DlmsMessageListener dlmsMessageListener) throws OsgpException { // Make sure neither device or device.getIpAddress() is null. this.checkDevice(device); this.checkIpAddress(device); try {/*from www. j a v a 2s . c om*/ return this.createConnection(device, dlmsMessageListener); } catch (final UnknownHostException e) { LOGGER.error("The IP address is not found: {}", device.getIpAddress(), e); // Unknown IP, unrecoverable. throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + device.getIpAddress()); } catch (final IOException e) { if (device.hasNewSecurityKey()) { // Queue key recovery process. this.recoverKeyProcessInitiator.initiate(device.getDeviceIdentification(), device.getIpAddress()); } final String msg = String.format( "Error creating connection for device %s with Ip address:%s Port:%d UseHdlc:%b UseSn:%b Message:%s", device.getDeviceIdentification(), device.getIpAddress(), device.getPort(), device.isUseHdlc(), device.isUseSn(), e.getMessage()); LOGGER.error(msg); throw new ConnectionException(msg, e); } catch (final EncrypterException e) { LOGGER.error("decryption on security keys went wrong for device: {}", device.getDeviceIdentification(), e); throw new FunctionalException(FunctionalExceptionType.INVALID_DLMS_KEY_FORMAT, ComponentType.PROTOCOL_DLMS, e); } }
From source file:com.chuannuo.tangguo.net.TGHttpRequest.java
private void makeRequestWithRetries() throws ConnectException { boolean retry = true; IOException cause = null;/*from w w w .j a va 2 s. c om*/ HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, "?"); } return; } catch (SocketException e) { // Added to detect host unreachable if (responseHandler != null) { responseHandler.sendFailureMessage(e, "?"); } return; } catch (SocketTimeoutException e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, ""); } return; } catch (IOException e) { cause = e; retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (NullPointerException e) { cause = new IOException("NPE in HttpClient" + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (Exception e) { retry = false; responseHandler.sendFailureMessage(e, "url?"); } } ConnectException ex = new ConnectException(); ex.initCause(cause); throw ex; }
From source file:com.enjoy.nerd.http.AsyncHttpRequest.java
private void makeRequestWithRetries() throws IOException { boolean retry = true; IOException cause = null;//from ww w .j a va2 s. c o m executionCount = 0; HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); try { while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { // switching between WI-FI and mobile data networks can cause a retry which then results in an UnknownHostException // while the WI-FI is initialising. The retry logic will be invoked here, if this is NOT the first retry // (to assist in genuine cases of unknown host) which seems better than outright failure cause = e;//new IOException("UnknownHostException exception: " + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (NullPointerException e) { // there's a bug in HttpClient 4.0.x that on some occasions causes // DefaultRequestExecutor to throw an NPE, see // http://code.google.com/p/android/issues/detail?id=5255 cause = new IOException("NPE in HttpClient: " + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (IOException e) { cause = e; retry = retryHandler.retryRequest(cause, ++executionCount, context); } if (retry && responseHandler != null) { responseHandler.sendRetryMessage(executionCount); } } } catch (Exception e) { // catch anything else to ensure failure message is propagated Log.e("AsyncHttpRequest", "Unhandled exception origin cause", e); cause = new IOException("Unhandled exception: " + e.getMessage()); } // cleaned up to throw IOException throw (cause); }
From source file:org.bml.util.server.BClient.java
/** *The Connect method creates a connection to a specified *host and port, and opens an object input and object ouput *stream.//from w w w. jav a 2 s . co m *@param aHost String - A host name or ip *@param aPort int - The port the host server is running on *@return boolean - true if connected successfully */ public boolean connect(String aHost, int aPort) { if (LOG.isDebugEnabled()) { LOG.debug("Attempting to connect to server: " + aHost + " on port: " + aPort); } try { theClientSocket = new Socket(aHost, aPort); } catch (UnknownHostException e) { System.out.println(e); return false; } catch (IOException e) { System.out.println(e); return false; } if (LOG.isDebugEnabled()) { LOG.debug("Connected to host: " + aHost + " Now trying to open Object input and output streams: " + theClientSocket); } try { theObjectIn = new ObjectInputStream(theClientSocket.getInputStream()); if (LOG.isDebugEnabled()) { LOG.debug( "Openned input stream....attempting to open output stream for socket: " + theClientSocket); } theObjectOut = new ObjectOutputStream(theClientSocket.getOutputStream()); theObjectOut.flush(); } catch (SocketException e) { if (e.getMessage().contains("Too many open files")) { if (LOG.isWarnEnabled()) { LOG.warn( "THIS IS OK.... Too many open socket connections.... waiting 1 second and trying again(1): " + e); } try { Thread.sleep(1000); } catch (InterruptedException f) { } this.connect(aHost, aPort); } else { if (LOG.isWarnEnabled()) { LOG.warn(e); } } } catch (Exception e1) { if (e1 != null && e1.getMessage() != null) { if (e1.getMessage().contains("(too many open files)")) { try { Thread.sleep(1000); } catch (InterruptedException f) { } if (LOG.isWarnEnabled()) { LOG.warn("Too many open files....I'm going to try to reopen the connection"); } this.connect(aHost, aPort); } else if (e1.getMessage().contains("Too many open files")) { if (LOG.isWarnEnabled()) { LOG.warn( "THIS IS OK.... Too many open socket connections.... waiting 1 second and trying again(2): " + e1); } try { Thread.sleep(1000); } catch (InterruptedException f) { } this.connect(aHost, aPort); } else { System.out.println("FClient: " + e1); return false; } } else { System.out.println("FClient: " + e1); return false; } } if (LOG.isDebugEnabled()) { LOG.debug("Streams open to host: " + aHost); } return true; }