List of usage examples for java.net ConnectException getMessage
public String getMessage()
From source file:client.ui.Container.java
private JSONObject getCert(SocketFactory factory, URL url) { JSONObject json = new JSONObject(); json.put("host", url.getHost()); json.put("port", url.getPort()); try {/*ww w . j a v a 2 s . co m*/ log("Get Certs: " + url.getHost() + ":" + url.getPort()); SSLSocket socket = (SSLSocket) factory.createSocket(url.getHost(), url.getPort()); socket.startHandshake(); Certificate[] certs = socket.getSession().getPeerCertificates(); String result = ""; for (Certificate cert : certs) { if (cert instanceof X509Certificate) { try { ((X509Certificate) cert).checkValidity(); result += "OK "; } catch (CertificateExpiredException cee) { result += "Expired "; } catch (CertificateNotYetValidException ex) { result += "NotYetValid "; } } } log("Result: " + result.trim()); json.put("result", result.trim()); } catch (SSLException se) { log("Error: SSLException (" + se.getMessage() + ")"); json.put("result", "SSLException: " + se.getMessage()); } catch (ConnectException ce) { log("Error: ConnectException (" + ce.getMessage() + ")"); json.put("result", "ConnectException: " + ce.getMessage()); } catch (IOException ioe) { log("Error: IOException (" + ioe.getMessage() + ")"); json.put("result", "IOException: " + ioe.getMessage()); } return json; }
From source file:ubic.gemma.core.loader.protein.StringBiomartGene2GeneProteinLoaderTest.java
@Test public void testDoLoadRemoteBiomartFileLocalStringFileOneTaxon() { // test pass in files so do not trigger fetcher // but make sure they get String fileNameStringZebraFish = "/data/loader/protein/string/protein.links.zebrafish.txt"; URL fileNameStringZebraFishURL = this.getClass().getResource(fileNameStringZebraFish); Collection<Taxon> taxaZebraFish = new ArrayList<>(); taxaZebraFish.add(zebraFish);/*w w w . java2 s . co m*/ Collection<Gene2GeneProteinAssociation> associationsBefore = gene2GeneProteinAssociationService.loadAll(); assertEquals(0, associationsBefore.size()); try { stringBiomartGene2GeneProteinAssociationLoader.load(new File(fileNameStringZebraFishURL.getFile()), null, null, taxaZebraFish); } catch (ConnectException e) { log.warn("Connection error, skipping test"); return; } catch (IOException e) { if (e.getMessage().startsWith("Error from BioMart")) { log.warn(e.getMessage()); return; } } Collection<Gene2GeneProteinAssociation> associations = gene2GeneProteinAssociationService.loadAll(); assertEquals(2, associations.size()); this.gene2GeneProteinAssociationService.removeAll(associations); associations = gene2GeneProteinAssociationService.loadAll(); assertTrue(associations.isEmpty()); }
From source file:io.ucoin.ucoinj.core.client.service.HttpServiceImpl.java
protected boolean executeRequest(HttpClient httpClient, HttpUriRequest request) { if (log.isDebugEnabled()) { log.debug("Executing request : " + request.getRequestLine()); }/*from w w w . j a va2 s . c o m*/ try { HttpResponse response = httpClient.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: { response.getEntity().consumeContent(); return true; } case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_FORBIDDEN: throw new TechnicalException("ucoin.client.authentication"); default: throw new TechnicalException("ucoin.client.status" + response.getStatusLine().toString()); } } catch (ConnectException e) { throw new TechnicalException("ucoin.client.core.connect", e); } catch (IOException e) { throw new TechnicalException(e.getMessage(), e); } }
From source file:com.claim.controller.FileTransferController.java
public boolean uploadMutiFilesWithFTP(ObjFileTransfer ftpObj) throws Exception { FTPClient ftpClient = new FTPClient(); int replyCode; boolean completed = false; try {// w ww .j av a 2s . c o m FtpProperties properties = new ResourcesProperties().loadFTPProperties(); try { ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); FtpUtil.showServerReply(ftpClient); } catch (ConnectException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("ConnectException: " + ex.getMessage()); ex.printStackTrace(); } catch (SocketException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("SocketException: " + ex.getMessage()); ex.printStackTrace(); } catch (UnknownHostException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("UnknownHostException: " + ex.getMessage()); ex.printStackTrace(); } replyCode = ftpClient.getReplyCode(); FtpUtil.showServerReply(ftpClient); if (!FTPReply.isPositiveCompletion(replyCode)) { FtpUtil.showServerReply(ftpClient); ftpClient.disconnect(); Console.LOG("Exception in connecting to FTP Serve ", 0); throw new Exception("Exception in connecting to FTP Server"); } else { FtpUtil.showServerReply(ftpClient); Console.LOG("Success in connecting to FTP Serve ", 1); } try { boolean success = ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); FtpUtil.showServerReply(ftpClient); if (!success) { throw new Exception("Could not login to the FTP server."); } else { Console.LOG("login to the FTP server. Successfully ", 1); } //ftpClient.enterLocalPassiveMode(); } catch (FTPConnectionClosedException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); // APPROACH #2: uploads second file using an OutputStream File files = new File(ftpObj.getFtp_directory_path()); String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator + ftpObj.getFtp_report_type(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryReportType); FtpUtil.showServerReply(ftpClient); String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryStmp); FtpUtil.showServerReply(ftpClient); for (File file : files.listFiles()) { if (file.isFile()) { System.out.println("file ::" + file.getName()); InputStream in = new FileInputStream(file); ftpClient.changeWorkingDirectory(workingDirectoryStmp); completed = ftpClient.storeFile(file.getName(), in); in.close(); Console.LOG( " " + file.getName() + " ", 1); FtpUtil.showServerReply(ftpClient); } } Console.LOG(" ?... ", 1); //completed = ftpClient.completePendingCommand(); FtpUtil.showServerReply(ftpClient); completed = true; ftpClient.disconnect(); } catch (IOException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); ex.printStackTrace(); } } return completed; }
From source file:com.claim.controller.FileTransferController.java
public boolean uploadMutiFilesWithFTPS(ObjFileTransfer ftpObj) throws Exception { FTPSClient ftpsClient = null;//from w ww . j a v a 2 s .c om int replyCode; boolean completed = false; try { FtpProperties properties = new ResourcesProperties().loadFTPProperties(); try { ftpsClient = new FTPSClient(properties.getFtp_protocal(), properties.isFtp_impicit()); //ftpsClient.setAuthValue(ConstantFtp.FTPS_PROTOCAL); ftpsClient.setDataTimeout(ConstantFtp.FTP_TIMEOUT); ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); System.out.print(ftpsClient.getReplyString()); ftpsClient.connect(properties.getFtp_server(), properties.getFtp_port()); FtpUtil.showServerReply(ftpsClient); } catch (ConnectException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); System.out.println("ConnectException: " + ex.getMessage()); ex.printStackTrace(); } catch (SocketException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); System.out.println("SocketException: " + ex.getMessage()); ex.printStackTrace(); } catch (UnknownHostException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); System.out.println("UnknownHostException: " + ex.getMessage()); ex.printStackTrace(); } replyCode = ftpsClient.getReplyCode(); FtpUtil.showServerReply(ftpsClient); if (!FTPReply.isPositiveCompletion(replyCode)) { ftpsClient.disconnect(); Console.LOG("Exception in connecting to FTP Serve ", 0); throw new Exception("Exception in connecting to FTP Server"); } else { Console.LOG("Success in connecting to FTP Serve ", 1); } try { boolean success = ftpsClient.login(properties.getFtp_username(), properties.getFtp_password()); FtpUtil.showServerReply(ftpsClient); if (!success) { throw new Exception("Could not login to the FTP server."); } else { Console.LOG("login to the FTP server. Successfully ", 1); } //ftpClient.enterLocalPassiveMode(); } catch (FTPConnectionClosedException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpsClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } ftpsClient.setFileType(FTP.BINARY_FILE_TYPE); ftpsClient.execPBSZ(0); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator + ftpObj.getFtp_report_type(); FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryReportType); FtpUtil.showServerReply(ftpsClient); String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp(); FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryStmp); FtpUtil.showServerReply(ftpsClient); // APPROACH #2: uploads second file using an OutputStream File files = new File(ftpObj.getFtp_directory_path()); for (File file : files.listFiles()) { if (file.isFile()) { System.out.println("file ::" + file.getName()); InputStream in = new FileInputStream(file); ftpsClient.changeWorkingDirectory(workingDirectoryStmp); completed = ftpsClient.storeFile(file.getName(), in); in.close(); Console.LOG( " " + file.getName() + " ", 1); FtpUtil.showServerReply(ftpsClient); } } Console.LOG(" ?... ", 1); //completed = ftpClient.completePendingCommand(); FtpUtil.showServerReply(ftpsClient); completed = true; ftpsClient.disconnect(); } catch (IOException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpsClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpsClient.isConnected()) { ftpsClient.logout(); ftpsClient.disconnect(); } } catch (IOException ex) { FtpUtil.showServerReply(ftpsClient); Console.LOG(ex.getMessage(), 0); ex.printStackTrace(); } } return completed; }
From source file:org.brutusin.rpc.client.http.HttpEndpoint.java
/** * * @param serviceId/*from w w w . j av a2 s . c o m*/ * @param input supports inputstreams * @param progressCallback * @return * @throws IOException */ public final HttpResponse exec(final String serviceId, final JsonNode input, final ProgressCallback progressCallback) throws IOException { if (!loaded) { synchronized (this) { if (!loaded) { loadServices(); loaded = true; } } } final HttpMethod method = getMethod(services.get(serviceId)); if (method == null) { throw new IllegalArgumentException("Invalid service id " + serviceId); } HttpResponse ret = new HttpResponse(); try { CloseableHttpResponse resp = doExec(serviceId, input, method, progressCallback); if (resp.getEntity() == null) { throw new RuntimeException(resp.getStatusLine().toString()); } Header cacheControl = resp.getFirstHeader("Cache-Control"); if (cacheControl != null) { HeaderElement[] elements = cacheControl.getElements(); if (elements != null) { for (HeaderElement element : elements) { if (element.getName().equals("no-cache")) { break; } if (ret.getCachingInfo() == null) { ret.setCachingInfo(new CachingInfo(0, true, false)); } if (element.getName().equals("max-age")) { ret.getCachingInfo().setMaxAge(Integer.valueOf(element.getValue())); } if (element.getName().equals("public")) { ret.getCachingInfo().setShared(true); } if (element.getName().equals("private")) { ret.getCachingInfo().setShared(false); } if (element.getName().equals("no-store")) { ret.getCachingInfo().setStore(false); } } } } if (!resp.getEntity().getContentType().getValue().startsWith(JSON_CONTENT_TYPE)) { MetaDataInputStream is = new MetaDataInputStream(resp.getEntity().getContent(), getAttachmentFileName(resp.getFirstHeader("Content-Disposition")), resp.getEntity().getContentType().getValue(), resp.getEntity().getContentLength(), null); ret.setInputStream(is); } else { JsonNode responseNode = JsonCodec.getInstance() .parse(Miscellaneous.toString(resp.getEntity().getContent(), "UTF-8")); RpcResponse<JsonNode> rpcResponse = new RpcResponse<JsonNode>(); if (responseNode.get("error") != null) { rpcResponse.setError( JsonCodec.getInstance().load(responseNode.get("error"), RpcResponse.Error.class)); } rpcResponse.setResult(responseNode.get("result")); ret.setRpcResponse(rpcResponse); } } catch (ConnectException ex) { RpcResponse<JsonNode> rpcResponse = new RpcResponse<JsonNode>(); rpcResponse.setError(new RpcResponse.Error(RpcErrorCode.connectionError, ex.getMessage())); ret.setRpcResponse(rpcResponse); } catch (Throwable t) { RpcResponse<JsonNode> rpcResponse = new RpcResponse<JsonNode>(); rpcResponse.setError(new RpcResponse.Error(RpcErrorCode.internalError, t.getMessage())); ret.setRpcResponse(rpcResponse); } return ret; }
From source file:io.ucoin.ucoinj.core.client.service.HttpServiceImpl.java
@SuppressWarnings("unchecked") protected <T> T executeRequest(HttpClient httpClient, HttpUriRequest request, Class<? extends T> resultClass) { T result = null;/*from www . j ava 2 s . co m*/ if (log.isDebugEnabled()) { log.debug("Executing request : " + request.getRequestLine()); } HttpResponse response = null; try { response = httpClient.execute(request); if (log.isDebugEnabled()) { log.debug("Received response : " + response.getStatusLine()); } switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: { result = (T) parseResponse(response, resultClass); response.getEntity().consumeContent(); break; } case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_FORBIDDEN: throw new TechnicalException("ucoinj.client.authentication"); case HttpStatus.SC_BAD_REQUEST: throw new HttpBadRequestException("ucoinj.client.status" + response.getStatusLine().toString()); default: throw new TechnicalException("ucoinj.client.status" + response.getStatusLine().toString()); } } catch (ConnectException e) { throw new TechnicalException("ucoinj.client.core.connect", e); } catch (SocketTimeoutException e) { throw new TechnicalException("ucoinj.client.core.timeout", e); } catch (IOException e) { throw new TechnicalException(e.getMessage(), e); } finally { // Close is need if (response instanceof CloseableHttpResponse) { try { ((CloseableHttpResponse) response).close(); } catch (IOException e) { // Silent is gold } } } return result; }
From source file:org.hyperic.hq.bizapp.client.AgentCallbackClient.java
protected LatherValue invokeLatherCall(ProviderInfo provider, String methodName, LatherValue args, final boolean acceptUnverifiedCertificates) throws AgentCallbackClientException { LatherHTTPClient client;//from w w w . ja v a2 s.co m final boolean debug = log.isDebugEnabled(); String addr = provider.getProviderAddress(); if (this.secureCommands.contains(methodName)) { final String agentToken = provider.getAgentToken(); ((SecureAgentLatherValue) args).setAgentToken(agentToken); } try { client = new LatherHTTPClient(addr, TIMEOUT_CONN, TIMEOUT_DATA, acceptUnverifiedCertificates); final long start = now(); LatherValue rtn = client.invoke(methodName, args); final long duration = now() - start; statsCollector.addStat(duration, LATHER_CMD); statsCollector.addStat(duration, LATHER_CMD + "_" + methodName.toUpperCase()); return rtn; } catch (SSLException e) { if (debug) log.debug(e, e); throw new AgentCallbackClientException(e); } catch (ConnectException exc) { // All exceptions are logged as debug. If the caller wants to // log the exception message, it can. final String eMsg = "Unable to contact server @ " + addr + ": " + exc; if (debug) log.debug(eMsg); throw new AgentCallbackClientException(eMsg); } catch (IOException exc) { String msg = exc.getMessage(); if (msg != null) { String eMsg; if (msg.indexOf("Service Unavailable") != -1) { eMsg = "Unable to contact server -- it has no more free connections"; if (debug) log.debug(eMsg); } else { eMsg = "IO error: " + exc.getMessage(); if (debug) log.debug(eMsg); } throw new AgentCallbackClientException(eMsg); } if (debug) log.debug("IO error", exc); throw new AgentCallbackClientException("IO error: " + exc.getMessage()); } catch (LatherRemoteException exc) { String eMsg; if (exc.getMessage().indexOf("Unauthorized agent denied") != -1) { eMsg = "Unable to invoke '" + methodName + "': Permission denied"; if (debug) log.debug(eMsg); } else { eMsg = "Remote error while invoking '" + methodName + ": " + exc; if (debug) log.debug(eMsg); } throw new AgentCallbackClientException(eMsg, exc); } catch (IllegalStateException e) { if (debug) log.debug("Could not create the LatherHTTPClient instance", e); throw new AgentCallbackClientException(e); } }
From source file:io.logspace.agent.hq.HqAgentController.java
protected void performCommit() { try {// w w w . ja va2s . co m do { List<Event> eventsForUpload = this.getEventsForUpload(); if (eventsForUpload == null || eventsForUpload.isEmpty()) { return; } this.uploadEvents(eventsForUpload); this.purgeUploadedEvents(eventsForUpload); } while (this.persistentQueue.size() >= UPLOAD_SIZE); } catch (NoRouteToHostException nrthex) { this.logger.error( "Could not upload events because the HQ was not available: {}. Trying again in {} seconds.", nrthex.getMessage(), RETRY_DELAY); new RetryThread(this.commitRunnable, RETRY_DELAY).start(); } catch (ConnectException cex) { this.logger.error( "Could not upload events because the HQ was not available: {}. Trying again in {} seconds.", cex.getMessage(), RETRY_DELAY); new RetryThread(this.commitRunnable, RETRY_DELAY).start(); } catch (IOException ioex) { this.logger.error("Failed to upload events. Trying again in {} seconds.", RETRY_DELAY, ioex); new RetryThread(this.commitRunnable, RETRY_DELAY).start(); } catch (UploadException uex) { this.logger.error("The HQ did not accept events: {} Trying again in {} seconds.", uex.getMessage(), RETRY_DELAY); new RetryThread(this.commitRunnable, RETRY_DELAY).start(); } }
From source file:com.predic8.membrane.core.transport.http.HttpClient.java
public Exchange call(Exchange exc, boolean adjustHostHeader, boolean failOverOn5XX) throws Exception { if (exc.getDestinations().isEmpty()) throw new IllegalStateException( "List of destinations is empty. Please specify at least one destination."); int counter = 0; Exception exception = null;/*from w w w .j a v a 2s . co m*/ while (counter < maxRetries) { Connection con = null; String dest = getDestination(exc, counter); HostColonPort target = null; try { log.debug("try # " + counter + " to " + dest); target = init(exc, dest, adjustHostHeader); InetAddress targetAddr = InetAddress.getByName(target.host); if (counter == 0) { con = exc.getTargetConnection(); if (con != null) { if (!con.isSame(targetAddr, target.port)) { con.close(); con = null; } else { con.setKeepAttachedToExchange(true); } } } if (con == null) { con = conMgr.getConnection(targetAddr, target.port, localAddr, getOutboundSSLProvider(exc, target), connectTimeout); con.setKeepAttachedToExchange(exc.getRequest().isBindTargetConnectionToIncoming()); exc.setTargetConnection(con); } Response response; String newProtocol = null; if (exc.getRequest().isCONNECTRequest()) { handleConnectRequest(exc, con); response = Response.ok().build(); newProtocol = "CONNECT"; } else { response = doCall(exc, con); if (exc.getProperty(Exchange.ALLOW_WEBSOCKET) == Boolean.TRUE && isUpgradeToWebSocketsResponse(response)) { log.debug("Upgrading to WebSocket protocol."); newProtocol = "WebSocket"; } } if (newProtocol != null) { setupConnectionForwarding(exc, con, newProtocol, streamPumpStats); exc.getDestinations().clear(); exc.getDestinations().add(dest); con.setExchange(exc); exc.setResponse(response); return exc; } boolean is5XX = 500 <= response.getStatusCode() && response.getStatusCode() < 600; if (!failOverOn5XX || !is5XX || counter == maxRetries - 1) { applyKeepAliveHeader(response, con); exc.getDestinations().clear(); exc.getDestinations().add(dest); con.setExchange(exc); response.addObserver(con); exc.setResponse(response); return exc; } // java.net.SocketException: Software caused connection abort: socket write error } catch (ConnectException e) { exception = e; log.info("Connection to " + (target == null ? dest : target) + " refused."); } catch (SocketException e) { if (e.getMessage().contains("Software caused connection abort")) { log.info("Connection to " + dest + " was aborted externally. Maybe by the server or the OS Membrane is running on."); } else if (e.getMessage().contains("Connection reset")) { log.info("Connection to " + dest + " was reset externally. Maybe by the server or the OS Membrane is running on."); } else { logException(exc, counter, e); } exception = e; } catch (UnknownHostException e) { log.warn("Unknown host: " + (target == null ? dest : target)); exception = e; if (exc.getDestinations().size() < 2) { //don't retry this host, it's useless. (it's very unlikely that it will work after timeBetweenTriesMs) break; } } catch (EOFWhileReadingFirstLineException e) { log.debug("Server connection to " + dest + " terminated before line was read. Line so far: " + e.getLineSoFar()); exception = e; } catch (NoResponseException e) { throw e; } catch (Exception e) { logException(exc, counter, e); exception = e; } counter++; if (exc.getDestinations().size() == 1) { //as documented above, the sleep timeout is only applied between successive calls to the same destination. Thread.sleep(timeBetweenTriesMs); } } throw exception; }