List of usage examples for java.net UnknownHostException getMessage
public String getMessage()
From source file:org.pouzinsociety.socket.tcp.SocketClient.java
public void run() { log.info("SocketClient: Started"); try {/*from ww w . j ava 2 s. c o m*/ log.info("SocketClient: Sleeping for 1000ms to allow ServerStart"); Thread.sleep(1000); log.info("SocketClient: Waking Up for work"); SocketImplFactory sFactory = tcpTransport.getSocketImplFactory(); Socket.setSocketImplFactory(sFactory); Socket kkSocket = null; PrintWriter out = null; BufferedReader in = null; try { log.info("SocketClient: Attempting connect with Server"); kkSocket = new Socket("localhost", 4444); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); } catch (UnknownHostException e) { log.error("SocketClient: Don't know about host: localhost."); return; } catch (IOException e) { log.error("SocketClient: Couldn't get I/O for the connection to: localhost."); return; } String fromServer; int packetsRecv = 0; do { log.info("SocketClient: Send(Foo) to Server"); out.println("Foo"); while ((fromServer = in.readLine()) != null) { packetsRecv++; log.info("SocketClient: Recvd(" + packetsRecv + ") from Server : [" + fromServer + "]"); break; } Thread.sleep(1000); } while (kkSocket.isConnected() && (packetsRecv < 5)); out.close(); in.close(); } catch (Exception e) { log.error("SocketClient: Exception: " + e.getMessage()); } log.info("SocketClient: Finished"); }
From source file:com.example.wechatsample.library.http.AsyncHttpRequest.java
private void makeRequestWithRetries() throws ConnectException { // This is an additional layer of retry logic lifted from droid-fu // See:/*from ww w . j a va2s .c o m*/ // https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java boolean retry = true; IOException cause = null; HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, "can't resolve host"); } return; } catch (SocketException e) { // Added to detect host unreachable if (responseHandler != null) { responseHandler.sendFailureMessage(e, "can't resolve host"); } return; } catch (IOException e) { cause = e; 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); } } // no retries left, crap out with exception ConnectException ex = new ConnectException(); ex.initCause(cause); throw ex; }
From source file:com.clustercontrol.ping.factory.RunMonitorPing.java
/** * fping?ping?????<BR>/*from w ww. jav a 2s . c o m*/ * @param facilityId Ping?ID()collect?facilityID??? * @return ???????true * @throws HinemosUnknown */ private boolean collectFping(ArrayList<String> facilityList, ArrayList<Integer> priporityList) throws HinemosUnknown { //??? if (m_now != null) { m_nodeDate = m_now.getTime(); } //?????? // hosts[] IP(String ??) // hostsv6[] IPv6(String??) // node IP???? // target nodo? HashSet<String> hosts = new HashSet<String>(); HashSet<String> hostsv6 = new HashSet<String>(); m_Target = new Hashtable<String, String[]>(); String facilityId = null; int version = 4; String[] node; for (int index = 0; index < facilityList.size(); index++) { facilityId = facilityList.get(index); if (facilityId != null && !"".equals(facilityId)) { node = new String[2]; try { // ?? NodeInfo info = new RepositoryControllerBean().getNode(facilityId); //m_log.error(facilityAttrMap.get(FacilityAttributeConstant.IPPROTOCOLNUMBER)); //???????version? if (info.getIpAddressVersion() != null) { version = info.getIpAddressVersion(); } else { version = 4; } if (version == 6) { InetAddress[] ip = InetAddress.getAllByName(info.getIpAddressV6()); if (ip.length != 1) { //IPInetAddress??????1???????? //UnnownHostExcption UnknownHostException e = new UnknownHostException(); m_log.info("collectFping() : " + e.getClass().getSimpleName() + ", " + e.getMessage()); throw e; } node[0] = ip[0].getHostAddress(); if (node[0] != null && !node[0].equals("")) { //IPHashSet????? hostsv6.add(node[0]); } } else { node[0] = info.getIpAddressV4(); if (node[0] != null && !node[0].equals("")) { //IPHashSet????? hosts.add(node[0]); } } if (node[0] != null && !node[0].equals("")) { node[1] = info.getNodeName(); //target?????? m_Target.put(facilityId, node); } } catch (FacilityNotFound e) { m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES_PING.getMessage(); m_messageOrg = e.getMessage(); return false; } catch (UnknownHostException e) { // ??? } } } if (m_reachabilityFping == null) { m_reachabilityFping = new ReachAddressFping(m_runCount, m_runInterval, m_pingTimeout); } boolean result = true; boolean resultTmp = true; //IPv4???fping?? if (hosts.size() != 0) { result = m_reachabilityFping.isReachable(hosts, 4); m_MsgErr = m_reachabilityFping.getM_errMsg(); } //IPv6???fping6?? if (hostsv6.size() != 0) { resultTmp = m_reachabilityFping.isReachable(hostsv6, 6); m_MsgErrV6 = m_reachabilityFping.getM_errMsg(); //??&???? result = result & resultTmp; } return result; }
From source file:com.fihmi.tools.minet.MiHttpRequest.java
private void makeRequestWithRetries() throws ConnectException { boolean retry = true; IOException cause = null;/*from w ww. j ava 2 s . c o m*/ HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, "?", request_tag); } return; } catch (SocketException e) { // Added to detect host unreachable if (responseHandler != null) { responseHandler.sendFailureMessage(e, "?", request_tag); } return; } catch (SocketTimeoutException e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, "", request_tag); } 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) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, "?url?", request_tag); } return; } } // no retries left, crap out with exception ConnectException ex = new ConnectException(); ex.initCause(cause); throw ex; }
From source file:net.mybox.mybox.ClientStatus.java
/** * This is a helper function for ClientSetup that makes a quick connection to the server * just so the account can be determined. * @param serverName/* w ww .j a v a 2s . co m*/ * @param serverPort * @param email * @return The account */ public ClientAccount startGetAccountMode(String serverName, int serverPort, String email, String dataDir) { if (serverName == null) { System.err.println("Client not configured"); System.exit(1); } account.serverName = serverName; account.serverPort = serverPort; account.email = email; account.directory = dataDir; account.salt = "0"; // temp hack System.out.println("Establishing connection to port " + serverPort + ". Please wait ..."); try { serverConnectionSocket = new Socket(account.serverName, account.serverPort); System.out.println("Connected: " + serverConnectionSocket); dataOutStream = new DataOutputStream(serverConnectionSocket.getOutputStream()); } catch (UnknownHostException uhe) { System.err.println("Host unknown: " + uhe.getMessage()); System.exit(1); } catch (IOException ioe) { System.err.println("Unexpected exception: " + ioe.getMessage()); System.exit(1); } JSONObject jsonOut = new JSONObject(); jsonOut.put("email", account.email); // jsonOut.put("password", password); // client = new ClientServerReceiver(this, serverConnectionSocket); return account; }
From source file:com.rakesh.d4ty.YTDownloadThread.java
boolean downloadone(String sURL) { boolean rc = false; boolean rc204 = false; boolean rc302 = false; this.iRecursionCount++; // stop recursion try {/*from www. ja v a2 s . c o m*/ if (sURL.equals("")) return (false); } catch (NullPointerException npe) { return (false); } if (JFCMainClient.getbQuitrequested()) return (false); // try to get information about application shutdown debugoutput("start."); // TODO GUI option for proxy? // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube // using local squid to save download time for tests try { // determine http_proxy environment variable if (!this.getProxy().equals("")) { String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", ""); this.proxy = new HttpHost(sproxy.replaceFirst(":(.*)", ""), Integer.parseInt(sproxy.replaceFirst("(.*):", "")), "http"); SchemeRegistry supportedSchemes = new SchemeRegistry(); supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes); // with proxy this.httpclient = new DefaultHttpClient(ccm, params); this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy); this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); } else { // without proxy this.httpclient = new DefaultHttpClient(); this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); } this.httpget = new HttpGet(getURI(sURL)); if (sURL.toLowerCase().startsWith("https")) this.target = new HttpHost(getHost(sURL), 443, "https"); else this.target = new HttpHost(getHost(sURL), 80, "http"); } catch (Exception e) { debugoutput(e.getMessage()); } debugoutput("executing request: ".concat(this.httpget.getRequestLine().toString())); debugoutput("uri: ".concat(this.httpget.getURI().toString())); debugoutput("host: ".concat(this.target.getHostName())); debugoutput("using proxy: ".concat(this.getProxy())); // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work) /* this.localContext = new BasicHttpContext(); if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context) ((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient */ // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again? try { this.response = this.httpclient.execute(this.target, this.httpget, this.localContext); } catch (ClientProtocolException cpe) { debugoutput(cpe.getMessage()); } catch (UnknownHostException uhe) { output((JFCMainClient.isgerman() ? "Fehler bei der Verbindung zu: " : "error connecting to: ") .concat(uhe.getMessage())); debugoutput(uhe.getMessage()); } catch (IOException ioe) { debugoutput(ioe.getMessage()); } catch (IllegalStateException ise) { debugoutput(ise.getMessage()); } /* CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN); CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC); CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ; try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( ))); } catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute try { debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString())); debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString())); debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString())); } catch (NullPointerException npe) { } */ try { debugoutput("HTTP response status line:".concat(this.response.getStatusLine().toString())); //for (int i = 0; i < response.getAllHeaders().length; i++) { // debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue())); //} // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL? if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)")) & !(rc204 = this.response.getStatusLine().toString().toLowerCase() .matches("^(http)(.*)204(.*)")) & !(rc302 = this.response.getStatusLine().toString().toLowerCase() .matches("^(http)(.*)302(.*)"))) { debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL)); output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\"")); return (rc & rc204 & rc302); } if (rc204) { debugoutput("last response code==204 - download: ".concat(this.sNextVideoURL.get(0))); rc = downloadone(this.sNextVideoURL.get(0)); return (rc); } if (rc302) debugoutput( "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString())); } catch (NullPointerException npe) { // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because // response.getStatusLine() == null this.sVideoURL = null; } HttpEntity entity = null; try { entity = this.response.getEntity(); } catch (NullPointerException npe) { } // try to read HTTP response body if (entity != null) { try { if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)")) this.textreader = new BufferedReader(new InputStreamReader(entity.getContent())); else this.binaryreader = new BufferedInputStream(entity.getContent()); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { // test if we got a webpage this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase(); if (this.sContentType.matches("^text/html(.*)")) { savetextdata(); // test if we got the binary content } else if (this.sContentType.matches("video/(.)*")) { if (JFCMainClient.getbNODOWNLOAD()) reportheaderinfo(); else savebinarydata(); } else { // content-type is not video/ rc = false; this.sVideoURL = null; } } catch (IOException ex) { try { throw ex; } catch (IOException e) { e.printStackTrace(); } } catch (RuntimeException ex) { try { throw ex; } catch (Exception e) { e.printStackTrace(); } } } //if (entity != null) this.httpclient.getConnectionManager().shutdown(); debugoutput("done: ".concat(sURL)); try { if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) { debugoutput("cannot download video - URL does not seem to be valid: ".concat(this.sVideoURL)); output(JFCMainClient.isgerman() ? "es gab ein Problem die Video URL zu finden!" : "there was a problem getting the video URL!"); // deutsch output((JFCMainClient.isgerman() ? "erwge die URL dem Autor mitzuteilen!" : "consider reporting the URL to author! - ").concat(this.sURL)); rc = false; } else { debugoutput("try to download video from URL: ".concat(this.sVideoURL)); rc = downloadone(this.sVideoURL); } this.sVideoURL = null; } catch (NullPointerException npe) { } return (rc); }
From source file:vitro.vgw.wsiadapter.TCSWSIAdapter.java
public Observation getNodeObservation(Node node, Resource resource) throws WSIAdapterException { signal = new CountDownLatch(1); Observation observation = new Observation(); try {/*from w ww. j a va2s . c o m*/ logger.debug("arrivo qui"); 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)); 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); } return observation; }
From source file:vitro.vgw.wsiadapter.WSIAdapterCoapHAI.java
public Observation getNodeObservation(Node node, Resource resource) throws WSIAdapterException { signal = new CountDownLatch(1); Observation observation = new Observation(); try {//from w w w . j a v a 2 s . co m coapObservationRequest(node, resource); signal.await(); if (resourceValue != null) { observation.setNode(node); observation.setResource(resource); observation.setValue(formatResourceValue(resourceValue, resource)); 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); } return observation; }
From source file:ubic.gemma.core.loader.util.fetcher.FtpFetcher.java
protected Collection<LocalFile> fetch(String identifier, String seekFile) { File existingFile = null;/*w w w . j ava2 s . c om*/ try { File newDir = mkdir(identifier); String outputFileName = formLocalFilePath(identifier, newDir); existingFile = new File(outputFileName); // if ( this.avoidDownload || ( existingFile.canRead() && allowUseExisting ) ) { // // log.info( outputFileName + " already exists." ); // } if (ftpClient == null || !ftpClient.isConnected()) { ftpClient = this.getNetDataSourceUtil().connect(FTP.BINARY_FILE_TYPE); assert ftpClient != null; // otherwise should have gotten an exception from connect() } long expectedSize = getExpectedSize(seekFile); FutureTask<Boolean> future = this.defineTask(outputFileName, seekFile); return this.doTask(future, expectedSize, seekFile, outputFileName); } catch (UnknownHostException e) { if (force || !allowUseExisting || existingFile == null) throw new RuntimeException(e); if (!avoidDownload) throw new RuntimeException(e); log.warn("Could not connect to " + this.getNetDataSourceUtil().getHost() + " to check size of " + seekFile + ", using existing file"); return getExistingFile(existingFile, seekFile); } catch (IOException e) { /* * Note: this block can trigger if you cancel. */ if (force || !allowUseExisting || existingFile == null) { /* * Printing to log here because runtime error does not deliver message when passed through * java.util.concurrent.FutureTask (only throws InterruptedException and ExecutionException) */ log.error("Runtime exception thrown: " + e.getMessage() + ". \n Stack trace follows:", e); throw new RuntimeException( "Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server and permissions are granted.", e); } if (Thread.currentThread().isInterrupted()) { throw new CancellationException(); } log.warn("Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server.," + e + ", using existing file"); return getExistingFile(existingFile, seekFile); } finally { try { if (ftpClient != null && ftpClient.isConnected()) ftpClient.disconnect(); } catch (IOException e) { //noinspection ThrowFromFinallyBlock throw new RuntimeException("Could not disconnect: " + e.getMessage()); } } }