Java Code Examples for java.net.ConnectException
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project android-async-http, under directory /src/com/loopj/android/http/.
Source file: AsyncHttpRequest.java

private void makeRequestWithRetries() throws ConnectException { 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 ( 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); } } ConnectException ex=new ConnectException(); ex.initCause(cause); throw ex; }
Example 2
From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/util/.
Source file: HttpSupport.java

/** * Determine the proxy server (if any) needed to obtain a URL. * @param proxySelector proxy support for the caller. * @param u location of the server caller wants to talk to. * @return proxy to communicate with the supplied URL. * @throws ConnectException the proxy could not be computed as the supplied URL could not be read. This failure should never occur. */ public static Proxy proxyFor(final ProxySelector proxySelector,final URL u) throws ConnectException { try { return proxySelector.select(u.toURI()).get(0); } catch ( URISyntaxException e) { final ConnectException err; err=new ConnectException("Cannot determine proxy for " + u); err.initCause(e); throw err; } }
Example 3
From project OpenSettlers, under directory /src/java/soc/server/genericServer/.
Source file: LocalStringServerSocket.java

/** * Find and connect to stringport with this name. Intended to be called by client thread. Will block-wait until the server calls accept(). * @param name Stringport server name to connect to * @param client Existing unused connection object to connect with * @throws ConnectException If stringport name is not found, or is EOF,or if its connect/accept queue is full. * @throws IllegalArgumentException If name is null, client is null,or client is already peered/connected. * @return client parameter object, connected to a LocalStringServer */ public static LocalStringConnection connectTo(String name,LocalStringConnection client) throws ConnectException, IllegalArgumentException { if (name == null) throw new IllegalArgumentException("name null"); if (client == null) throw new IllegalArgumentException("client null"); if (client.getPeer() != null) throw new IllegalArgumentException("client already peered"); if (!allSockets.containsKey(name)) throw new ConnectException("LocalStringServerSocket name not found: " + name); LocalStringServerSocket ss=(LocalStringServerSocket)allSockets.get(name); if (ss.isOutEOF()) throw new ConnectException("LocalStringServerSocket name is EOF: " + name); LocalStringConnection servSidePeer; try { servSidePeer=ss.queueAcceptClient(client); } catch ( ConnectException ce) { throw ce; } catch ( Throwable t) { ConnectException ce=new ConnectException("Error queueing to accept for " + name); ce.initCause(t); throw ce; } synchronized (servSidePeer) { if (!servSidePeer.isAccepted()) { try { servSidePeer.wait(); } catch ( InterruptedException e) { } } } if (client != servSidePeer.getPeer()) throw new IllegalStateException("Internal error: Peer is wrong"); if (client.isOutEOF()) throw new ConnectException("Server at EOF, closed waiting to be accepted"); return client; }
Example 4
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: ClientSOContainer.java

protected Serializable processSynch(SynchEvent evt) throws IOException { synchronized (connectLock) { checkConnected(); final IConnection conn=evt.getConnection(); if (connection != conn) throw new ConnectException(Messages.ClientSOContainer_Not_Connected); return super.processSynch(evt); } }
Example 5
From project droid-fu, under directory /src/main/java/com/github/droidfu/http/.
Source file: BetterHttpRequestBase.java

public BetterHttpResponse send() throws ConnectException { BetterHttpRequestRetryHandler retryHandler=new BetterHttpRequestRetryHandler(maxRetries); httpClient.setHttpRequestRetryHandler(retryHandler); HttpContext context=new BasicHttpContext(); boolean retry=true; IOException cause=null; while (retry) { try { return httpClient.execute(request,this,context); } catch ( IOException e) { cause=e; retry=retryRequest(retryHandler,cause,context); } catch ( NullPointerException e) { cause=new IOException("NPE in HttpClient" + e.getMessage()); retry=retryRequest(retryHandler,cause,context); } finally { if (oldTimeout != BetterHttp.getSocketTimeout()) { BetterHttp.setSocketTimeout(oldTimeout); } } } ConnectException ex=new ConnectException(); ex.initCause(cause); throw ex; }
Example 6
From project Empire, under directory /sesame2/src/com/clarkparsia/empire/sesametwo/.
Source file: RepositoryDataSource.java

/** * @inheritDoc */ public void connect() throws ConnectException { if (!isConnected()) { setConnected(true); try { mConnection=mRepository.getConnection(); mConnection.setAutoCommit(true); } catch ( RepositoryException e) { throw (ConnectException)new ConnectException("There was an error establishing the connection").initCause(e); } } }
Example 7
From project ignition, under directory /ignition-support/ignition-support-lib/src/main/java/com/github/ignition/support/http/.
Source file: IgnitedHttpRequestBase.java

@Override public IgnitedHttpResponse send() throws ConnectException { IgnitedHttpRequestRetryHandler retryHandler=new IgnitedHttpRequestRetryHandler(maxRetries); httpClient.setHttpRequestRetryHandler(retryHandler); HttpContext context=new BasicHttpContext(); boolean retry=true; IOException cause=null; while (retry) { try { return httpClient.execute(request,this,context); } catch ( IOException e) { cause=e; retry=retryRequest(retryHandler,cause,context); } catch ( NullPointerException e) { cause=new IOException("NPE in HttpClient" + e.getMessage()); retry=retryRequest(retryHandler,cause,context); } finally { if (timeoutChanged) { ignitedHttp.setConnectionTimeout(oldConnTimeout); ignitedHttp.setSocketTimeout(oldSocketTimeout); } } } ConnectException ex=new ConnectException(); ex.initCause(cause); throw ex; }
Example 8
/** * Helper function for perforing a proxy CONNECT request. * @param proxy The proxy to use. * @param host The destination's hostname. * @param port The destination's port * @return An established socket connection to the proxy. * @throws ConnectException if the proxy response code is not 200 * @throws UnknownHostException * @throws IOException */ private Socket HttpProxyConnect(Proxy proxy,String host,int port) throws UnknownHostException, IOException, ConnectException { InetSocketAddress sa=(InetSocketAddress)proxy.address(); String phost=(sa.isUnresolved()) ? sa.getHostName() : sa.getAddress().getHostAddress(); int pport=sa.getPort(); Socket proxysock=new Socket(phost,pport); String req="CONNECT " + host + ":"+ port+ " "+ DEFAULT_PROTOCOL+ "\r\n\r\n"; proxysock.getOutputStream().write(req.getBytes()); BufferedReader proxyIn=new BufferedReader(new InputStreamReader(proxysock.getInputStream())); String line=proxyIn.readLine(); if (!line.matches("^HTTP/\\d\\.\\d\\s200\\s.*")) throw new ConnectException("Proxy response: " + line); this.uploadPolicy.displayDebug("Proxy response: " + line,40); proxyIn.readLine(); return proxysock; }
Example 9
From project OAK, under directory /oak-library/src/main/java/oak/external/com/github/droidfu/http/.
Source file: BetterHttpRequestBase.java

public BetterHttpResponse send() throws ConnectException { BetterHttpRequestRetryHandler retryHandler=new BetterHttpRequestRetryHandler(maxRetries); httpClient.setHttpRequestRetryHandler(retryHandler); HttpContext context=new BasicHttpContext(); boolean retry=true; IOException cause=null; while (retry) { try { return httpClient.execute(request,this,context); } catch ( IOException e) { cause=e; retry=retryRequest(retryHandler,cause,context); } catch ( NullPointerException e) { cause=new IOException("NPE in HttpClient" + e.getMessage()); retry=retryRequest(retryHandler,cause,context); } finally { if (oldTimeout != BetterHttp.getSocketTimeout()) { BetterHttp.setSocketTimeout(oldTimeout); } } } ConnectException ex=new ConnectException(); ex.initCause(cause); throw ex; }
Example 10
From project proxydroid, under directory /src/com/github/droidfu/http/.
Source file: BetterHttpRequestBase.java

@Override public BetterHttpResponse send() throws ConnectException { BetterHttpRequestRetryHandler retryHandler=new BetterHttpRequestRetryHandler(maxRetries); httpClient.setHttpRequestRetryHandler(retryHandler); HttpContext context=new BasicHttpContext(); boolean retry=true; IOException cause=null; while (retry) { try { return httpClient.execute(request,this,context); } catch ( IOException e) { cause=e; retry=retryRequest(retryHandler,cause,context); } catch ( NullPointerException e) { cause=new IOException("NPE in HttpClient" + e.getMessage()); retry=retryRequest(retryHandler,cause,context); } finally { if (oldTimeout != BetterHttp.getSocketTimeout()) { BetterHttp.setSocketTimeout(oldTimeout); } } } ConnectException ex=new ConnectException(); ex.initCause(cause); throw ex; }
Example 11
From project Solbase, under directory /src/org/apache/hadoop/hbase/ipc/.
Source file: HBaseClient.java

/** * Take an IOException and the address we were trying to connect to and return an IOException with the input exception as the cause. The new exception provides the stack trace of the place where the exception is thrown and some extra diagnostics information. If the exception is ConnectException or SocketTimeoutException, return a new one of the same type; Otherwise return an IOException. * @param addr target address * @param exception the relevant exception * @return an exception to throw */ @SuppressWarnings({"ThrowableInstanceNeverThrown"}) private IOException wrapException(InetSocketAddress addr,IOException exception){ if (exception instanceof ConnectException) { return (ConnectException)new ConnectException("Call to " + addr + " failed on connection exception: "+ exception).initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException)new SocketTimeoutException("Call to " + addr + " failed on socket timeout exception: "+ exception).initCause(exception); } else { return (IOException)new IOException("Call to " + addr + " failed on local exception: "+ exception).initCause(exception); } }
Example 12
From project Tanks_1, under directory /src/org/apache/mina/core/polling/.
Source file: AbstractPollingIoConnector.java

private void processTimedOutSessions(Iterator<H> handles){ long currentTime=System.currentTimeMillis(); while (handles.hasNext()) { H handle=handles.next(); ConnectionRequest connectionRequest=getConnectionRequest(handle); if ((connectionRequest != null) && (currentTime >= connectionRequest.deadline)) { connectionRequest.setException(new ConnectException("Connection timed out.")); cancelQueue.offer(connectionRequest); } } }
Example 13
From project teatrove, under directory /trove/src/main/java/org/teatrove/trove/net/.
Source file: SSLSocketFactory.java

public CheckedSocket createSocket(long timeout) throws ConnectException, SocketException { Socket socket=SocketConnector.connect(mAddr,mPort,mLocalAddr,mLocalPort,timeout); if (socket == null) { throw new ConnectException("Connect timeout expired: " + timeout); } try { socket=mSSLFactory.createSocket(socket,mAddr.getHostAddress(),mPort,true); } catch ( IOException e) { throw new SocketException(e.toString()); } return CheckedSocket.check(socket); }
Example 14
From project accent, under directory /src/test/java/net/lshift/accent/.
Source file: ConnectionBehaviourTest.java

@Test public void shouldKeepAttemptingToReconnect() throws Exception { ConnectionFactory unconnectableFactory=createMock(ConnectionFactory.class); expect(unconnectableFactory.newConnection()).andStubThrow(new ConnectException("Boom")); replay(unconnectableFactory); final CountDownLatch attemptLatch=new CountDownLatch(4); ConnectionFailureListener eventingListener=new ConnectionFailureListener(){ @Override public void connectionFailure( Exception e){ if (e instanceof ConnectException) { attemptLatch.countDown(); } else { System.out.println("WARNING: Received unexpected exception - " + e); } } } ; AccentConnection conn=new AccentConnection(unconnectableFactory,eventingListener); assertTrue(attemptLatch.await(5000,TimeUnit.MILLISECONDS)); }
Example 15
From project harmony, under directory /harmony.ui.topologygui/src/main/java/org/opennaas/ui/topology/ws/.
Source file: WSProxy.java

/** * Sends the domain creation message. * @param dom * @return Successful result or not * @throws ConnectException */ public static boolean addDomain(final DomainInformationType dom) throws ConnectException { final ObjectFactory of=new ObjectFactory(); final AddDomainType adddomtype=of.createAddDomainType(); final AddDomain adddom=of.createAddDomain(); adddomtype.setDomain(dom); adddom.setAddDomain(adddomtype); AddDomainResponse domResp=of.createAddDomainResponse(); AddDomainResponseType domRespType=of.createAddDomainResponseType(); boolean res=true; WSProxy.logger.info("Adding Domain..."); try { final Element e=WSProxy.getProxy().addDomain(WSProxy.jaxbSerializer.objectToElement(adddom)); domResp=(AddDomainResponse)WSProxy.jaxbSerializer.elementToObject(e); domRespType=domResp.getAddDomainResponse(); res=domRespType.isSuccess(); WSProxy.logger.info("Domain added!"); } catch ( final SoapFault sf) { res=false; WSProxy.logger.error("Couldn't add domain. A SoapFault occurred... "); sf.printStackTrace(); throw new ConnectException(sf.getMessage()); } return res; }
Example 16
From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/client/integration/.
Source file: TestAbortHandling.java

/** * Tests that if a socket fails to connect, the allocated connection is properly released back to the connection manager. */ @Test public void testSocketConnectFailureReleasesConnection() throws Exception { ManagedClientConnection conn=Mockito.mock(ManagedClientConnection.class); Mockito.doThrow(new ConnectException()).when(conn).open(Mockito.any(HttpRoute.class),Mockito.any(HttpContext.class),Mockito.any(HttpParams.class)); ClientConnectionRequest connrequest=Mockito.mock(ClientConnectionRequest.class); Mockito.when(connrequest.getConnection(Mockito.anyInt(),Mockito.any(TimeUnit.class))).thenReturn(conn); ClientConnectionManager connmgr=Mockito.mock(ClientConnectionManager.class); SchemeRegistry schemeRegistry=SchemeRegistryFactory.createDefault(); Mockito.when(connmgr.requestConnection(Mockito.any(HttpRoute.class),Mockito.any())).thenReturn(connrequest); Mockito.when(connmgr.getSchemeRegistry()).thenReturn(schemeRegistry); final HttpClient client=new HttpClientBuilder().setConnectionManager(connmgr).build(); final HttpContext context=new BasicHttpContext(); final HttpGet httpget=new HttpGet("http://www.example.com/a"); try { client.execute(httpget,context); Assert.fail("expected IOException"); } catch ( IOException expected) { } Mockito.verify(conn).abortConnection(); }
Example 17
From project jodconverter, under directory /jodconverter-core/src/main/java/org/artofsolving/jodconverter/office/.
Source file: OfficeConnection.java

public void connect() throws ConnectException { logger.fine(String.format("connecting with connectString '%s'",unoUrl)); try { XComponentContext localContext=Bootstrap.createInitialComponentContext(null); XMultiComponentFactory localServiceManager=localContext.getServiceManager(); XConnector connector=OfficeUtils.cast(XConnector.class,localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector",localContext)); XConnection connection=connector.connect(unoUrl.getConnectString()); XBridgeFactory bridgeFactory=OfficeUtils.cast(XBridgeFactory.class,localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory",localContext)); String bridgeName="jodconverter_" + bridgeIndex.getAndIncrement(); XBridge bridge=bridgeFactory.createBridge(bridgeName,"urp",connection,null); bridgeComponent=OfficeUtils.cast(XComponent.class,bridge); bridgeComponent.addEventListener(bridgeListener); serviceManager=OfficeUtils.cast(XMultiComponentFactory.class,bridge.getInstance("StarOffice.ServiceManager")); XPropertySet properties=OfficeUtils.cast(XPropertySet.class,serviceManager); componentContext=OfficeUtils.cast(XComponentContext.class,properties.getPropertyValue("DefaultContext")); connected=true; logger.info(String.format("connected: '%s'",unoUrl)); OfficeConnectionEvent connectionEvent=new OfficeConnectionEvent(this); for ( OfficeConnectionEventListener listener : connectionEventListeners) { listener.connected(connectionEvent); } } catch ( NoConnectException connectException) { throw new ConnectException(String.format("connection failed: '%s'; %s",unoUrl,connectException.getMessage())); } catch ( Exception exception) { throw new OfficeException("connection failed: " + unoUrl,exception); } }
Example 18
From project jodconverter_1, under directory /jodconverter-core/src/main/java/org/artofsolving/jodconverter/office/.
Source file: OfficeConnection.java

public void connect() throws ConnectException { logger.fine(String.format("connecting with connectString '%s'",unoUrl)); try { XComponentContext localContext=Bootstrap.createInitialComponentContext(null); XMultiComponentFactory localServiceManager=localContext.getServiceManager(); XConnector connector=OfficeUtils.cast(XConnector.class,localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector",localContext)); XConnection connection=connector.connect(unoUrl.getConnectString()); XBridgeFactory bridgeFactory=OfficeUtils.cast(XBridgeFactory.class,localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory",localContext)); String bridgeName="jodconverter_" + bridgeIndex.getAndIncrement(); XBridge bridge=bridgeFactory.createBridge(bridgeName,"urp",connection,null); bridgeComponent=OfficeUtils.cast(XComponent.class,bridge); bridgeComponent.addEventListener(bridgeListener); serviceManager=OfficeUtils.cast(XMultiComponentFactory.class,bridge.getInstance("StarOffice.ServiceManager")); XPropertySet properties=OfficeUtils.cast(XPropertySet.class,serviceManager); componentContext=OfficeUtils.cast(XComponentContext.class,properties.getPropertyValue("DefaultContext")); connected=true; logger.info(String.format("connected: '%s'",unoUrl)); OfficeConnectionEvent connectionEvent=new OfficeConnectionEvent(this); for ( OfficeConnectionEventListener listener : connectionEventListeners) { listener.connected(connectionEvent); } } catch ( NoConnectException connectException) { throw new ConnectException(String.format("connection failed: '%s'; %s",unoUrl,connectException.getMessage())); } catch ( Exception exception) { throw new OfficeException("connection failed: " + unoUrl,exception); } }
Example 19
From project PixelController, under directory /src/main/java/com/neophob/sematrix/cli/.
Source file: PixConClient.java

/** * @param cmd * @return * @throws ConnectException */ private static Client connectToServer(ParsedArgument cmd) throws ConnectException { Client client=null; Socket socket=new Socket(); try { socket.connect(new InetSocketAddress(cmd.getHostname(),cmd.getPort()),2000); client=new Client(new PApplet(),socket); System.out.println("Connected to " + cmd.getTarget()); return client; } catch ( Exception e) { System.err.println("Failed to connect Server at " + cmd.getTarget()); if (socket != null) { try { socket.close(); } catch ( Exception e2) { } } } throw new ConnectException("Failed to connect " + cmd.getTarget()); }
Example 20
From project processFlowProvision, under directory /pfpServices/knowledgeSessionService/src/main/java/org/jboss/processFlow/knowledgeService/.
Source file: KnowledgeSessionService.java

private synchronized void createKnowledgeBaseViaKnowledgeAgent(boolean force) throws ConnectException { if (kbase != null && !force) return; if (!guvnorUtils.guvnorExists()) { StringBuilder sBuilder=new StringBuilder(); sBuilder.append(guvnorUtils.getGuvnorProtocol()); sBuilder.append("://"); sBuilder.append(guvnorUtils.getGuvnorHost()); sBuilder.append("/"); sBuilder.append(guvnorUtils.getGuvnorSubdomain()); sBuilder.append("/rest/packages/"); throw new ConnectException("createKnowledgeBase() cannot connect to guvnor at URL : " + sBuilder.toString()); } ResourceChangeScannerConfiguration sconf=ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration(); sconf.setProperty("drools.resource.scanner.interval",droolsResourceScannerInterval); ResourceFactory.getResourceChangeScannerService().configure(sconf); ResourceFactory.getResourceChangeScannerService().start(); ResourceFactory.getResourceChangeNotifierService().start(); KnowledgeAgentConfiguration aconf=KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); aconf.setProperty("drools.agent.newInstance","false"); KnowledgeAgent kagent=KnowledgeAgentFactory.newKnowledgeAgent("Guvnor default",aconf); StringReader sReader=guvnorUtils.createChangeSet(); try { guvnorChangeSet=IOUtils.toString(sReader); sReader.close(); } catch ( Exception x) { x.printStackTrace(); } kagent.applyChangeSet(ResourceFactory.newByteArrayResource(guvnorChangeSet.getBytes())); kbase=kagent.getKnowledgeBase(); }
Example 21
From project soja, under directory /soja-client/src/main/java/com/excilys/soja/client/.
Source file: StompClient.java

/** * Connect and login to the server with a timeout value. Once the network connection is up the STOMP shakehand phase will begin. * @param username * @param password * @param connectTimeout * @throws SocketException * @throws TimeoutException */ public void connect(String username,String password,long connectTimeout) throws SocketException, TimeoutException { ChannelFuture channelFuture=clientBootstrap.connect(new InetSocketAddress(hostname,port)); if (!channelFuture.awaitUninterruptibly(connectTimeout)) { clientBootstrap.releaseExternalResources(); throw new TimeoutException("Connection timeout to server " + hostname + ":"+ port); } if (!channelFuture.isSuccess()) { clientBootstrap.releaseExternalResources(); throw new ConnectException("Client failed to connect to " + hostname + ":"+ port); } channel=channelFuture.getChannel(); if (channel.isConnected()) { LOGGER.debug("Connected to {}:{}. Login with username {}...",new Object[]{hostname,port,username}); clientHandler.connect(channel,SUPPORTED_STOMP_VERSION,hostname,username,password); } }
Example 22
From project tinos, under directory /projects/org.pouzinsociety.org.jnode.net.ipv4.tcp/src/main/java/org/jnode/net/ipv4/tcp/.
Source file: TCPControlBlock.java

/** * Active connect to a foreign address. This method blocks until the connection has been established. * @throws SocketException */ public synchronized void appConnect(IPv4Address fAddr,int fPort) throws SocketException { if (!isState(TCPS_CLOSED)) { throw new SocketException("Invalid connection state " + getStateName()); } super.connect(getLocalAddress(),fAddr,fPort); for (int attempt=0; attempt < TCP_MAXCONNECT; attempt++) { try { sendSYN(); setState(TCPS_SYN_SENT); waitUntilState(TCPS_ESTABLISHED,timeout); if (isRefused()) { throw new ConnectException("Connection refused"); } if (DEBUG) { log.debug("Connected to " + fAddr + ":"+ fPort); } return; } catch ( TimeoutException ex) { } } throw new ConnectException("Connection request timeout"); }
Example 23
From project aether-core, under directory /aether-connector-asynchttpclient/src/main/java/org/eclipse/aether/connector/async/.
Source file: AsyncRepositoryConnector.java

private boolean isResumeWorthy(Throwable t){ if (t instanceof IOException) { if (t instanceof ConnectException) { return false; } return true; } return false; }
Example 24
From project airlift, under directory /discovery/src/main/java/io/airlift/discovery/client/.
Source file: Announcer.java

@PreDestroy public void destroy(){ executor.shutdownNow(); try { executor.awaitTermination(30,TimeUnit.SECONDS); } catch ( InterruptedException e) { Thread.currentThread().interrupt(); } try { announcementClient.unannounce().checkedGet(); } catch ( DiscoveryException e) { if (e.getCause() instanceof ConnectException) { log.error("Cannot connect to discovery server for unannounce: %s",e.getCause().getMessage()); } else { log.error(e); } } }
Example 25
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/.
Source file: DefaultHttpRequestRetryHandler.java

/** * Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine if the given method should be retried. */ public boolean retryRequest(final IOException exception,int executionCount,final HttpContext context){ if (exception == null) { throw new IllegalArgumentException("Exception parameter may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } if (executionCount > this.retryCount) { return false; } if (exception instanceof InterruptedIOException) { return false; } if (exception instanceof UnknownHostException) { return false; } if (exception instanceof ConnectException) { return false; } if (exception instanceof SSLException) { return false; } HttpRequest request=(HttpRequest)context.getAttribute(ExecutionContext.HTTP_REQUEST); if (handleAsIdempotent(request)) { return true; } Boolean b=(Boolean)context.getAttribute(ExecutionContext.HTTP_REQ_SENT); boolean sent=(b != null && b.booleanValue()); if (!sent || this.requestSentRetryEnabled) { return true; } return false; }
Example 26
From project anarchyape, under directory /src/main/java/ape/.
Source file: DenialOfServiceRunner.java

public void run(){ long currentTime=System.currentTimeMillis(); long endTime=currentTime + (duration * 1000); while (System.currentTimeMillis() < endTime) { try { Socket net=new Socket(target,port); sendRawLine("GET / HTTP/1.1",net); } catch ( UnknownHostException e) { System.out.println("Could not resolve hostname."); e.printStackTrace(); Main.logger.info("Could not resolve hostname."); Main.logger.info(e); break; } catch ( ConnectException e) { System.out.println("The connection was refused. Make sure that port " + port + " is open and receiving connections on host "+ target); Main.logger.info("The connection was refused. Make sure that port " + port + " is open and receiving connections on host "+ target); e.printStackTrace(); Main.logger.info(e); break; } catch ( SocketException e) { if (Main.VERBOSE) { System.out.println("VERBOSE: Client says too many files open. This is expected in a DoS attack. Continuing..."); e.printStackTrace(); } } catch ( IOException e) { e.printStackTrace(); Main.logger.info(e); break; } } }
Example 27
From project andlytics, under directory /src/com/github/andlyticsproject/.
Source file: DeveloperConsole.java

private String grapAppStatistics(String startApp,long lenght) throws DeveloperConsoleException, NetworkException { String developerPostData=Preferences.getRequestFullAssetInfo(context); if (developerPostData == null) { developerPostData=GET_FULL_ASSET_INFO_FOR_USER_REQUEST; } String lengthString="" + lenght; String xsrfToken=((AndlyticsApp)context.getApplicationContext()).getXsrfToken(); developerPostData=developerPostData.replace(PARAM_APPNAME,startApp != null ? startApp : ""); developerPostData=developerPostData.replace(PARAM_LENGTH,lengthString); developerPostData=developerPostData.replace(PARAM_XSRFTOKEN,xsrfToken != null ? xsrfToken : ""); String result=null; try { URL aURL=new java.net.URL(URL_DEVELOPER_EDIT_APP + "?dev_acc=" + devacc); result=getGwtRpcResponse(developerPostData,aURL); } catch ( ConnectException ex) { throw new NetworkException(ex); } catch ( Exception f) { throw new DeveloperConsoleException(result,f); } return result; }
Example 28
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.
Source file: URLConnectionHttpClient.java

/** * Throw an exception if the connection failed * @param connection */ final void processError(HttpURLConnection connection){ try { int code=connection.getResponseCode(); if (code == 200) return; URL url=connection.getURL(); String error=processError2_reason(connection); if (code == 401) { if (error.contains("Basic authentication is not supported")) throw new TwitterException.UpdateToOAuth(); throw new TwitterException.E401(error + "\n" + url+ " ("+ (name == null ? "anonymous" : name)+ ")"); } if (code == 403) { processError2_403(url,error); } if (code == 404) { if (error != null && error.contains("deleted")) throw new TwitterException.SuspendedUser(error + "\n" + url); throw new TwitterException.E404(error + "\n" + url); } if (code == 406) throw new TwitterException.E406(error + "\n" + url); if (code == 413) throw new TwitterException.E413(error + "\n" + url); if (code == 416) throw new TwitterException.E416(error + "\n" + url); if (code == 420) throw new TwitterException.TooManyLogins(error + "\n" + url); if (code >= 500 && code < 600) throw new TwitterException.E50X(error + "\n" + url); processError2_rateLimit(connection,code,error); throw new TwitterException(code + " " + error+ " "+ url); } catch ( SocketTimeoutException e) { URL url=connection.getURL(); throw new TwitterException.Timeout(timeout + "milli-secs for " + url); } catch ( ConnectException e) { URL url=connection.getURL(); throw new TwitterException.Timeout(url.toString()); } catch ( SocketException e) { throw new TwitterException.E50X(e.toString()); } catch ( IOException e) { throw new TwitterException(e); } }
Example 29
From project arquillian-container-glassfish, under directory /glassfish-common/src/main/java/org/jboss/arquillian/container/glassfish/clientutils/.
Source file: GlassFishClientService.java

/** * Verify if the DAS is running or not. */ public boolean isDASRunning(){ try { getClientUtil().GETRequest(""); } catch ( ClientHandlerException clientEx) { if (clientEx.getCause().getClass().equals(ConnectException.class)) { return false; } } return true; }
Example 30
From project autopsy, under directory /KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/.
Source file: Server.java

/** * Tests if there's a Solr server running by sending it a core-status request. * @return false if the request failed with a connection error, otherwisetrue */ synchronized boolean isRunning() throws KeywordSearchModuleException { try { CoreAdminRequest.getStatus(null,solrServer); logger.log(Level.INFO,"Solr server is running"); } catch ( SolrServerException ex) { Throwable cause=ex.getRootCause(); if (cause instanceof ConnectException || cause instanceof SocketException || cause instanceof NoHttpResponseException) { logger.log(Level.INFO,"Solr server is not running, cause: " + cause.getMessage()); return false; } else { throw new KeywordSearchModuleException("Error checking if Solr server is running",ex); } } catch ( IOException ex) { throw new KeywordSearchModuleException("Error checking if Solr server is running",ex); } return true; }
Example 31
From project Cafe, under directory /webapp/src/org/openqa/selenium/net/.
Source file: PortProber.java

public static boolean pollPort(int port,int timeout,TimeUnit unit){ long end=System.currentTimeMillis() + unit.toMillis(timeout); while (System.currentTimeMillis() < end) { try { Socket socket=new Socket(); socket.setReuseAddress(true); socket.bind(new InetSocketAddress("localhost",port)); socket.close(); return true; } catch ( ConnectException e) { } catch ( UnknownHostException e) { throw new RuntimeException(e); } catch ( IOException e) { throw new RuntimeException(e); } } return false; }
Example 32
From project CamelInAction-source, under directory /chapter12/notifier/src/test/java/camelinaction/.
Source file: RiderEventNotifierTest.java

@Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder(){ @Override public void configure() throws Exception { from("direct:ok").to("mock:ok"); from("direct:fail").throwException(new ConnectException("Simulated exception")); } } ; }
Example 33
@SuppressWarnings("unchecked") public boolean configure(String url) throws Exception { try { interactive=new Connection(url); toolConnection=new Connection(url); setCurrentNamespace(currentNamespace); prepareView(); logPanel.append(";; Clojure " + toolConnection.send("op","eval","code","(clojure-version)").values().get(0) + "\n"); NamespaceBrowser.setREPLConnection(toolConnection); return true; } catch ( ConnectException e) { closeView(); MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),"Could not connect",String.format("Could not connect to REPL @ %s",url)); return false; } }
Example 34
From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/.
Source file: BayeuxClientTest.java

@Test public void testURLWithImplicitPort() throws Exception { final AtomicBoolean listening=new AtomicBoolean(); try { Socket socket=new Socket("localhost",80); socket.close(); listening.set(true); } catch ( ConnectException x) { listening.set(false); } final CountDownLatch latch=new CountDownLatch(1); BayeuxClient client=new BayeuxClient("http://localhost/cometd",LongPollingTransport.create(null,httpClient)){ @Override public void onFailure( Throwable x, Message[] messages){ } } ; client.setDebugEnabled(debugTests()); client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener(){ public void onMessage( ClientSessionChannel channel, Message message){ Assert.assertFalse(message.isSuccessful()); if (listening.get()) Assert.assertTrue(message.get("exception") instanceof ProtocolException); else Assert.assertTrue(message.get("exception") instanceof ConnectException); latch.countDown(); } } ); client.handshake(); Assert.assertTrue(latch.await(5000,TimeUnit.MILLISECONDS)); disconnectBayeuxClient(client); }
Example 35
From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.
Source file: RoundRobinReconnectHandler.java

@Override public void exceptionCaught(final ChannelHandlerContext ctx,final ExceptionEvent ee) throws Exception { final Throwable cause=ee.getCause(); if (cause instanceof ConnectException) logger.warn("Unable to establish connection to {}",currentRemoteAddress.get()); final Channel c=currentChannel.getAndSet(null); if (c != null) c.close(); super.exceptionCaught(ctx,ee); }
Example 36
From project connectbot, under directory /src/com/trilead/ssh2/channel/.
Source file: DynamicAcceptThread.java

public void run(){ try { startSession(); } catch ( IOException ioe) { int error_code=Proxy.SOCKS_FAILURE; if (ioe instanceof SocksException) error_code=((SocksException)ioe).errCode; else if (ioe instanceof NoRouteToHostException) error_code=Proxy.SOCKS_HOST_UNREACHABLE; else if (ioe instanceof ConnectException) error_code=Proxy.SOCKS_CONNECTION_REFUSED; else if (ioe instanceof InterruptedIOException) error_code=Proxy.SOCKS_TTL_EXPIRE; if (error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0) { error_code=Proxy.SOCKS_FAILURE; } sendErrorMessage(error_code); } finally { if (auth != null) auth.endSession(); } }
Example 37
From project EasySOA, under directory /easysoa-distribution/easysoa-distribution-startup-monitor/src/main/java/org/easysoa/startup/.
Source file: StartupMonitor.java

/** * @param url * @param timeout in ms * @return */ public static boolean isAvailable(String url,int timeout,boolean expectRequestSuccess){ try { URLConnection connection=new URL(url).openConnection(); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.connect(); InputStream is=connection.getInputStream(); is.close(); } catch ( ConnectException e) { return false; } catch ( IOException e) { return !expectRequestSuccess; } return true; }
Example 38
From project echo2, under directory /src/testapp/interactive/eclipse/.
Source file: TestAppRun.java

public static void main(String[] arguments) throws Exception { try { URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/"); URLConnection conn=url.openConnection(); InputStream in=conn.getInputStream(); in.close(); } catch ( ConnectException ex) { } Server server=new Server(PORT); final Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS); testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC); Context shutdownContext=new Context(server,"/__SHUTDOWN__"); shutdownContext.addServlet(new ServletHolder(new HttpServlet(){ private static final long serialVersionUID=1L; protected void service( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { testContext.getSessionHandler().stop(); System.out.println("Shutdown request received: terminating."); System.exit(0); } catch ( Exception ex) { ex.printStackTrace(); } } } ),"/"); System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC); server.start(); server.join(); }
Example 39
From project echo3, under directory /src/server-java/testapp-interactive/eclipse/.
Source file: TestAppRun.java

public static void main(String[] arguments) throws Exception { try { URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/"); URLConnection conn=url.openConnection(); InputStream in=conn.getInputStream(); in.close(); } catch ( ConnectException ex) { } Server server=new Server(PORT); final Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS); testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC); Context shutdownContext=new Context(server,"/__SHUTDOWN__"); shutdownContext.addServlet(new ServletHolder(new HttpServlet(){ private static final long serialVersionUID=1L; protected void service( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { testContext.getSessionHandler().stop(); System.out.println("Shutdown request received: terminating."); System.exit(0); } catch ( Exception ex) { ex.printStackTrace(); } } } ),"/"); System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC); server.start(); server.join(); }
Example 40
From project echo3extras, under directory /src/server-java/testapp-interactive/eclipse/.
Source file: TestAppRun.java

public static void main(String[] arguments) throws Exception { try { URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/"); URLConnection conn=url.openConnection(); InputStream in=conn.getInputStream(); in.close(); } catch ( ConnectException ex) { } Server server=new Server(PORT); Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS); testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC); Context shutdownContext=new Context(server,"/__SHUTDOWN__"); shutdownContext.addServlet(new ServletHolder(new HttpServlet(){ private static final long serialVersionUID=1L; protected void service( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Shutdown request received: terminating."); System.exit(0); } } ),"/"); System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC); server.start(); server.join(); }
Example 41
From project eclipsefp, under directory /net.sf.eclipsefp.haskell.scion.client/src/net/sf/eclipsefp/haskell/scion/internal/client/.
Source file: ScionServer.java

/** * Attempts to connect to the open TCP socket of the Scion server process. Returns as soon as a successful connection is made. If a connection cannot be established within a second or so, an exception is thrown. */ private Socket connectToServer(String host,int port) throws UnknownHostException, IOException { int count=0; Socket socket=null; do { try { socket=new Socket(host,port); } catch ( ConnectException ex) { ++count; if (count == MAX_RETRIES) { throw ex; } } try { Thread.sleep(128 * count); } catch ( InterruptedException ex) { } } while (socket == null); return socket; }
Example 42
/** * @param e * @return */ public static int exception_to_posix_code(IOException e){ if (e instanceof java.nio.channels.ClosedChannelException) { return Posix.ENOTCONN; } if ("Broken pipe".equals(e.getMessage()) || "Connection reset by peer".equals(e.getMessage())) { return Posix.ENOTCONN; } if (e instanceof ConnectException) { if ("Connection refused".equals(e.getMessage())) { return Posix.ECONNREFUSED; } } if (e instanceof BindException) { if ("Can't assign requested address".equals(e.getMessage())) { return Posix.EADDRNOTAVAIL; } } if (e instanceof java.net.SocketException) { if ("Network is unreachable".equals(e.getMessage())) { return Posix.ENETUNREACH; } } ERT.log.warning("unknown exception: " + e.getMessage()); ERT.log.log(Level.FINE,"details: ",e); return Posix.EUNKNOWN; }
Example 43
From project flume_1, under directory /flume-log4j-appender/src/main/java/com/cloudera/flume/log4j/appender/.
Source file: FlumeLog4jAvroAppender.java

@Override protected void append(LoggingEvent event){ if (client == null) { connect(); } int attempt=1; while (reconnectAttempts == 0 || attempt <= reconnectAttempts) { try { client.append(AvroEventConvertUtil.toAvroEvent(new Log4JEventAdaptor(event))); break; } catch ( UndeclaredThrowableException e) { if (reconnectAttempts > 0 && attempt >= reconnectAttempts) { throw e; } Throwable cause=e.getCause(); if (cause instanceof ConnectException) { LogLog.warn("Failed to communicate with server. reconnectAttempts:" + reconnectAttempts + " attempt:"+ attempt,cause); try { Thread.sleep(1000); } catch ( InterruptedException e1) { Thread.currentThread().interrupt(); } client=null; connect(); } else { throw e; } } attempt++; } }
Example 44
From project Foglyn, under directory /com.foglyn.fogbugz/src/com/foglyn/fogbugz/.
Source file: Request.java

private FogBugzCommunicationException ioError(IOException e,String url){ if (e instanceof ConnectException) { return new FogBugzCommunicationException("Unable to connect to FogBugz server, server is down",e,url); } if (e instanceof NoRouteToHostException) { return new FogBugzCommunicationException("Unable to connect to FogBugz server, no route to host",e,url); } if (e instanceof UnknownHostException) { return new FogBugzCommunicationException("Unable to connect to FogBugz server, unknown host: " + e.getMessage(),e,url); } return new FogBugzCommunicationException("IO Error while communicating with FogBugz",e,url); }
Example 45
From project gmc, under directory /src/org.gluster.storage.management.client/src/org/gluster/storage/management/client/.
Source file: AbstractClient.java

private GlusterRuntimeException createGlusterException(Exception e){ if (e instanceof GlusterRuntimeException) { return (GlusterRuntimeException)e; } if (e instanceof UniformInterfaceException) { UniformInterfaceException uie=(UniformInterfaceException)e; if ((uie.getResponse().getStatus() == Response.Status.UNAUTHORIZED.getStatusCode())) { setSecurityToken(null); return new GlusterRuntimeException("Invalid credentials!"); } else { return new GlusterRuntimeException("[" + uie.getResponse().getStatus() + "]["+ uie.getResponse().getEntity(String.class)+ "]"); } } else { Throwable cause=e.getCause(); if (cause != null && cause instanceof ConnectException) { return new GlusterRuntimeException("Couldn't connect to Gluster Management Gateway!"); } return new GlusterRuntimeException("Exception in REST communication! [" + e.getMessage() + "]",e); } }
Example 46
From project idigi-java-monitor-api, under directory /netty/src/main/java/com/idigi/api/monitor/netty/.
Source file: ReconnectHandler.java

@Override public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e){ Throwable cause=e.getCause(); if (cause instanceof ConnectException) { logger.error("Failed to connect: {}",cause.getMessage()); } if (cause instanceof IOException) { logger.warn("Disconnecting due to IOException: {}",cause.getMessage()); } else { logger.error("Another error occurred: {}",cause.getMessage()); cause.printStackTrace(); } ctx.getChannel().close(); }
Example 47
From project incubator-s4, under directory /subprojects/s4-comm/src/main/java/org/apache/s4/comm/tcp/.
Source file: TCPEmitter.java

@Override public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e) throws Exception { Throwable t=e.getCause(); if (t instanceof ClosedChannelException) { partitionChannelMap.inverse().remove(e.getChannel()); return; } else if (t instanceof ConnectException) { partitionChannelMap.inverse().remove(e.getChannel()); return; } else { logger.error("Unexpected exception",t); } }
Example 48
From project Ivory, under directory /common/src/main/java/org/apache/ivory/entity/parser/.
Source file: ProcessEntityParser.java

private void validateHDFSpaths(Process process,String clusterName) throws IvoryException { org.apache.ivory.entity.v0.cluster.Cluster cluster=ConfigurationStore.get().get(EntityType.CLUSTER,clusterName); String workflowPath=process.getWorkflow().getPath(); String libPath=process.getWorkflow().getLib(); String nameNode=getNameNode(cluster,clusterName); try { Configuration configuration=new Configuration(); configuration.set("fs.default.name",nameNode); FileSystem fs=FileSystem.get(configuration); if (!fs.exists(new Path(workflowPath))) { throw new ValidationException("Workflow path: " + workflowPath + " does not exists in HDFS: "+ nameNode); } if (libPath != null && !fs.exists(new Path(libPath))) { throw new ValidationException("Lib path: " + libPath + " does not exists in HDFS: "+ nameNode); } } catch ( ValidationException e) { throw new ValidationException(e); } catch ( ConnectException e) { throw new ValidationException("Unable to connect to Namenode: " + nameNode + " referenced in cluster: "+ clusterName); } catch ( Exception e) { throw new IvoryException(e); } }
Example 49
From project jentrata-msh, under directory /Clients/Corvus.WSClient/src/main/java/hk/hku/cecid/corvus/http/.
Source file: PartnershipOpVerifer.java

/** * Validate the HTML content received after executed partnership operation. The content is passed as a input stream <code>ins</code>. <br/><br/> This operation is quite expensive because it first transform the whole HTML content received to a well-formed XHTML before parsing by the SAX Parser. * @param ins The HTML content to validate the result of partnership operation * @throws SAXException <ol> <li>When unable to down-load the HTML DTD from the web. Check your Internet connectivity</li> <li>When IO related problems occur</li> </ol> * @throws ParserConfigurationException When SAX parser mis-configures. */ public void validate(InputStream ins) throws SAXException, ParserConfigurationException { if (ins == null) throw new NullPointerException("Missing 'input stream' for validation"); try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); Tidy t=new Tidy(); t.setXHTML(true); t.setQuiet(true); t.setShowWarnings(false); t.parse(ins,baos); ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray()); PageletContentVerifer verifer=new PageletContentVerifer(); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); SAXParser parser=spf.newSAXParser(); parser.parse(bais,verifer); boolean result=verifer.getIsVerifiedWithNoError(); if (!result) throw new SAXException("Fail to execute partnership operation as : " + verifer.getVerifiedMessage()); } catch ( ConnectException cex) { cex.printStackTrace(); throw new SAXException("Seems unable to download correct DTD from the web, behind proxy/firewall?",cex); } catch ( IOException ioex) { throw new SAXException("IO Error during SAX parsing.",ioex); } }
Example 50
From project jetty-maven-plugin, under directory /src/main/java/org/mortbay/jetty/plugin/.
Source file: JettyStopMojo.java

public void execute() throws MojoExecutionException, MojoFailureException { if (stopPort <= 0) throw new MojoExecutionException("Please specify a valid port"); if (stopKey == null) throw new MojoExecutionException("Please specify a valid stopKey"); try { Socket s=new Socket(InetAddress.getByName("127.0.0.1"),stopPort); s.setSoLinger(false,0); OutputStream out=s.getOutputStream(); out.write((stopKey + "\r\nstop\r\n").getBytes()); out.flush(); s.close(); } catch ( ConnectException e) { getLog().info("Jetty not running!"); } catch ( Exception e) { getLog().error(e); } }
Example 51
From project jetty-project, under directory /jetty-maven-plugin/src/main/java/org/mortbay/jetty/plugin/.
Source file: JettyStopMojo.java

public void execute() throws MojoExecutionException, MojoFailureException { if (stopPort <= 0) throw new MojoExecutionException("Please specify a valid port"); if (stopKey == null) throw new MojoExecutionException("Please specify a valid stopKey"); try { Socket s=new Socket(InetAddress.getByName("127.0.0.1"),stopPort); s.setSoLinger(false,0); OutputStream out=s.getOutputStream(); out.write((stopKey + "\r\nstop\r\n").getBytes()); out.flush(); s.close(); } catch ( ConnectException e) { getLog().info("Jetty not running!"); } catch ( Exception e) { getLog().error(e); } }
Example 52
From project jspwiki, under directory /tests/org/apache/wiki/util/.
Source file: MailUtilTest.java

/** * This test sends a message to the local user's mailbox on this host. It assumes that there is a locally-listening SMTP server on port 25, and that the current runtime user has a mailbox on the local machine. For Unix-based systems such as Linux and OS X, you can verify that this test ran successfully simply by typing "mail" at the command line. */ public void testSendMail(){ m_props.setProperty("jspwiki.usePageCache","true"); String user=System.getProperty("user.name") + "@localhost"; try { MailUtil.sendMessage(m_context.getEngine(),user,"Mail test","This is a test mail generated by MailUtilTest."); } catch ( MessagingException e) { if (e.getCause() instanceof ConnectException) { System.out.println("I could not test whether mail sending works, since I could not connect to your SMTP server."); System.out.println("Reason: " + e.getMessage()); return; } e.printStackTrace(); fail("Unknown problem (check the console for error report)"); } catch ( Exception e) { e.printStackTrace(); fail("Could not send mail: " + e.getMessage()); } }
Example 53
From project JsTestDriver, under directory /idea-plugin/src/com/google/jstestdriver/idea/.
Source file: TestRunner.java

public static void main(String[] args) throws Exception { String serverURL=args[0]; String settingsFile=args[1]; int port=Integer.parseInt(args[2]); try { Socket socket=connectToServer(port); ObjectOutputStream outputStream=new ObjectOutputStream(socket.getOutputStream()); new TestRunner(serverURL,settingsFile,new File(""),outputStream).execute(); } catch ( RuntimeException ex) { if (ex.getCause() != null && ex.getCause() instanceof ConnectException) { System.err.println("\nCould not connect to a JSTD server running at " + serverURL + "\n"+ "Check that the server is running."); } else { System.err.println("JSTestDriver crashed!"); throw ex; } } }
Example 54
From project KeyboardTerm, under directory /src/tw/kenshinn/keyboardTerm/.
Source file: TerminalActivity.java

public void close(Exception e){ TerminalView currentView=TerminalManager.getInstance().getView(currentViewId); if (currentView == null) return; try { currentView.connection.disconnect(); } catch ( Exception _e) { } if (e != null) { String msg=e.getLocalizedMessage(); Host currentHost=currentView.host; if (UnknownHostException.class.isInstance(e)) { msg=String.format(getText(R.string.terminal_error_unknownhost).toString(),currentHost.getName()); } else if (ConnectException.class.isInstance(e)) { msg=String.format(getText(R.string.terminal_error_connect).toString(),currentHost.getName()); } Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } TerminalManager.getInstance().removeView(currentViewId); currentViewId=-1; finish(); }
Example 55
From project LunaTerm, under directory /src/tw/loli/lunaTerm/.
Source file: TerminalActivity.java

public void close(Exception e){ TerminalView currentView=TerminalManager.getInstance().getView(currentViewId); if (currentView == null) return; try { currentView.connection.disconnect(); } catch ( Exception _e) { } if (e != null) { String msg=e.getLocalizedMessage(); Host currentHost=currentView.host; if (UnknownHostException.class.isInstance(e)) { msg=String.format(getText(R.string.terminal_error_unknownhost).toString(),currentHost.getName()); } else if (ConnectException.class.isInstance(e)) { msg=String.format(getText(R.string.terminal_error_connect).toString(),currentHost.getName()); } Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } TerminalManager.getInstance().removeView(currentViewId); currentViewId=-1; finish(); }
Example 56
From project maven-gae-plugin, under directory /maven-gae-plugin/src/main/java/net/kindleit/gae/.
Source file: StopGoal.java

public void execute() throws MojoExecutionException, MojoFailureException { if (monitorPort <= 0) { throw new MojoExecutionException(SPECIFY_PORT); } if (monitorKey == null) { throw new MojoExecutionException(SPECIFY_KEY); } try { final Socket s=new Socket(InetAddress.getByName("127.0.0.1"),monitorPort); s.setSoLinger(false,0); final OutputStream out=s.getOutputStream(); out.write((monitorKey + NL + Commands.STOP+ NL).getBytes()); out.flush(); s.close(); } catch ( final ConnectException e) { getLog().info(CONNECTION_ERROR); } catch ( final Exception e) { getLog().error(e); } }
Example 57
From project maven-hudson-dev-plugin, under directory /src/main/java/org/mortbay/jetty/plugin/.
Source file: JettyStopMojo.java

public void execute() throws MojoExecutionException, MojoFailureException { if (stopPort <= 0) throw new MojoExecutionException("Please specify a valid port"); if (stopKey == null) throw new MojoExecutionException("Please specify a valid stopKey"); try { Socket s=new Socket(InetAddress.getByName("127.0.0.1"),stopPort); s.setSoLinger(false,0); OutputStream out=s.getOutputStream(); out.write((stopKey + "\r\nstop\r\n").getBytes()); out.flush(); s.close(); } catch ( ConnectException e) { getLog().info("Jetty not running!"); } catch ( Exception e) { getLog().error(e); } }
Example 58
From project mwe, under directory /plugins/org.eclipse.emf.mwe.core/src/org/eclipse/emf/mwe/internal/core/debug/processing/.
Source file: DebugMonitor.java

/** * open the connection to a debug server framework (e.g. eclipse) and instantiate and start the RuntimeHandlerManager listener. * @param args arg[1] must be the port to be connected with * @throws IOException */ public void init(final String[] args) throws IOException { final int port=findPort(args); try { connection.connect(port); } catch ( final ConnectException e) { throw new IOException("Couldn't establish connection to Debugger on port " + port); } try { final RuntimeHandlerManager handler=new RuntimeHandlerManager(this); handler.setConnection(connection); handler.startListener(); } catch ( final Exception e) { connection.close(); if (e instanceof RuntimeException) { throw (RuntimeException)e; } throw (IOException)e; } }
Example 59
From project narya, under directory /core/src/main/java/com/threerings/presents/client/.
Source file: ClientCommunicator.java

@Override protected void openChannel(InetAddress host) throws IOException { String pportKey=_client.getHostname() + ".preferred_port"; int[] ports=_client.getPorts(); int pport=getPrefPort(pportKey,ports[0]); int ppidx=Math.max(0,IntListUtil.indexOf(ports,pport)); for (int ii=0; ii < ports.length; ii++) { int port=ports[(ii + ppidx) % ports.length]; int nextPort=ports[(ii + ppidx + 1) % ports.length]; log.info("Connecting","host",host,"port",port); InetSocketAddress addr=new InetSocketAddress(host,port); try { synchronized (this) { clearPPI(true); _prefPortInterval=new PrefPortInterval(pportKey,port,nextPort); _channel=SocketChannel.open(addr); _prefPortInterval.schedule(PREF_PORT_DELAY); } break; } catch ( IOException ioe) { if (ioe instanceof ConnectException && ii < (ports.length - 1)) { _client.reportLogonTribulations(new LogonException(AuthCodes.TRYING_NEXT_PORT,true)); continue; } throw ioe; } } }
Example 60
From project netifera, under directory /platform/com.netifera.platform.net.dns/com.netifera.platform.net.dns.tools/src/com/netifera/platform/net/dns/tools/.
Source file: DNSZoneTransfer.java

public void toolRun(IToolContext context) throws ToolException { this.context=context; IProbe probe=Activator.getInstance().getProbeManager().getLocalProbe(); realm=probe.getEntity().getId(); context.setTitle("Zone transfer"); setupToolOptions(); context.setTitle("Zone transfer of " + domain + " from "+ dns.getLocator()); try { transferZone(); } catch ( ConnectException e) { context.error("Cannot connect to " + dns); } catch ( SocketTimeoutException e) { context.error("Connection to " + dns + " timed out"); } catch ( ZoneTransferException e) { context.error(dns + " doesnt allow zone transfer of " + domain); } catch ( IOException e) { context.exception("I/O Exception",e); } finally { context.done(); } }
Example 61
public static boolean testIPv6Support(){ try { InetAddress ipv6Localhost=InetAddress.getByAddress(new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}); Socket socket=new Socket(ipv6Localhost,4242); socket.close(); } catch ( ConnectException e) { return true; } catch ( Exception e) { return false; } return true; }
Example 62
From project netty, under directory /example/src/main/java/io/netty/example/uptime/.
Source file: UptimeClientHandler.java

@Override public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception { if (cause instanceof ConnectException) { startTime=-1; println("Failed to connect: " + cause.getMessage()); } cause.printStackTrace(); ctx.close(); }
Example 63
From project nexus-p2-repository-plugin, under directory /src/main/java/org/sonatype/nexus/plugins/p2/repository/metadata/.
Source file: AbstractP2MetadataSource.java

/** * If the given RuntimeException turns out to be a P2 server error, try to retrieve the item locally, else rethrow exception. */ private StorageItem doRetrieveLocalOnTransferError(final ResourceStoreRequest request,final E repository,final P2RuntimeExceptionMaskedAsINFException e) throws LocalStorageException, ItemNotFoundException { final Throwable cause=e.getCause().getCause(); if (cause != null && (cause.getMessage().startsWith("HTTP Server 'Service Unavailable'") || cause.getCause() instanceof ConnectException)) { return doRetrieveLocalItem(request,repository); } throw e; }
Example 64
From project niosmtp, under directory /src/main/java/me/normanmaurer/niosmtp/transport/.
Source file: FutureResult.java

/** * Create a new {@link FutureResult} by taking care to wrap or cast the given {@link Throwable} to the right {@link SMTPException} * @param t * @return result */ @SuppressWarnings("rawtypes") public static FutureResult create(Throwable t){ final SMTPException exception; if (t instanceof SMTPException) { exception=(SMTPException)t; } else if (t instanceof ConnectException) { exception=new SMTPConnectionException(t); } else { exception=new SMTPException("Exception while try to deliver msg",t); } return new FutureResult(exception){ @Override public Object getResult(){ return null; } } ; }
Example 65
From project org.openscada.orilla, under directory /org.openscada.core.ui.connection.login/src/org/openscada/core/ui/connection/login/dialog/.
Source file: ConnectionAnalyzer.java

public static String makeError(Throwable error){ if (error == null) { return null; } final Set<Throwable> causes=new HashSet<Throwable>(1); while (error.getCause() != null && !causes.contains(error)) { causes.add(error); error=error.getCause(); } if (error instanceof ConnectException || error instanceof java.rmi.ConnectException) { return String.format(Messages.ConnectionAnalyzer_Error_ConnectException,error.getLocalizedMessage()); } final String msg=error.getLocalizedMessage(); if (msg == null) { return error.getClass().getName(); } if ("Bad credentials".equals(msg)) { return Messages.ConnectionAnalyzer_Error_BadCredentials; } return msg; }
Example 66
From project Orweb, under directory /src/info/guardianproject/browser/workaround/.
Source file: MyDefaultClientConnectionOperator.java

@Override public void openConnection(OperatedClientConnection conn,HttpHost target,InetAddress local,HttpContext context,HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection must not be null."); } if (target == null) { throw new IllegalArgumentException("Target host must not be null."); } if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } if (conn.isOpen()) { throw new IllegalArgumentException("Connection must not be open."); } final Scheme schm=schemeRegistry.getScheme(target.getSchemeName()); final SocketFactory sf=schm.getSocketFactory(); Socket sock=sf.createSocket(); conn.opening(sock,target); try { Socket connsock=sf.connectSocket(sock,target.getHostName(),schm.resolvePort(target.getPort()),local,0,params); if (sock != connsock) { sock=connsock; conn.opening(sock,target); } } catch ( ConnectException ex) { throw new HttpHostConnectException(target,ex); } prepareSocket(sock,context,params); conn.openCompleted(sf.isSecure(sock),params); }
Example 67
From project paho.mqtt.java, under directory /org.eclipse.paho.client.mqttv3/src/org/eclipse/paho/client/mqttv3/internal/.
Source file: TCPNetworkModule.java

/** * Starts the module, by creating a TCP socket to the server. */ public void start() throws IOException, MqttException { try { socket=factory.createSocket(host,port); } catch ( ConnectException ex) { trace.trace(Trace.FINE,250,null,ex); throw ExceptionHelper.createMqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR); } }
Example 68
From project PenguinCMS, under directory /PenguinCMS/tests/vendor/sahi/src/net/sf/sahi/test/.
Source file: TestRunner.java

public static void main(String[] args){ try { if (args.length == 0) { help(); } if (mainCLIParams(args)) return; String suiteName=args[0]; String base=getBase(args); String browser=getBrowser(args); String logDir=args[3]; if ("default".equalsIgnoreCase(logDir)) { logDir=""; } String sahiHost=args[4]; String port=args[5]; String threads=args[6]; String browserOption=""; String browserProcessName=args[7]; if (args.length == 9) { browserOption=args[8]; } TestRunner testRunner=new TestRunner(suiteName,browser,base,sahiHost,port,threads,browserOption,browserProcessName); testRunner.addReport(new Report("html",logDir)); String status=testRunner.execute(); System.out.println("Status:" + status); } catch ( ConnectException ce) { System.err.println(ce.getMessage()); System.err.println("Could not connect to Sahi Proxy.\nVerify that the Sahi Proxy is running on the specified host and port."); help(); } catch ( Exception e) { e.printStackTrace(); help(); } }
Example 69
From project PhonePledge, under directory /src/phonepledge/client/.
Source file: PledgeClient.java

private boolean connect(){ try { System.out.println("Connecting to server on port " + PledgeServer.SERVER_PORT); sock=new Socket(serverAddress,PledgeServer.SERVER_PORT); System.out.println("Connected to server"); isConnected=true; } catch ( ConnectException e) { System.err.printf("Could not connect to server at %s:%d. Is it running?\n",serverAddress,PledgeServer.SERVER_PORT); } catch ( SocketTimeoutException e) { System.err.println("Timeout connecting to Visualizer: " + e.getMessage()); return false; } catch ( IOException e) { e.printStackTrace(); } return isConnected; }
Example 70
From project platform_3, under directory /discovery/src/main/java/com/proofpoint/discovery/client/.
Source file: Announcer.java

@PreDestroy public void destroy(){ executor.shutdownNow(); try { executor.awaitTermination(30,TimeUnit.SECONDS); } catch ( InterruptedException e) { Thread.currentThread().interrupt(); } try { announcementClient.unannounce().checkedGet(); } catch ( DiscoveryException e) { if (e.getCause() instanceof ConnectException) { log.error("Cannot connect to discovery server for unannounce: %s",e.getCause().getMessage()); } else { log.error(e); } } }
Example 71
From project platform_external_apache-http, under directory /src/org/apache/http/impl/conn/.
Source file: DefaultClientConnectionOperator.java

public void updateSecureConnection(OperatedClientConnection conn,HttpHost target,HttpContext context,HttpParams params) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection must not be null."); } if (target == null) { throw new IllegalArgumentException("Target host must not be null."); } if (params == null) { throw new IllegalArgumentException("Parameters must not be null."); } if (!conn.isOpen()) { throw new IllegalArgumentException("Connection must be open."); } final Scheme schm=schemeRegistry.getScheme(target.getSchemeName()); if (!(schm.getSocketFactory() instanceof LayeredSocketFactory)) { throw new IllegalArgumentException("Target scheme (" + schm.getName() + ") must have layered socket factory."); } final LayeredSocketFactory lsf=(LayeredSocketFactory)schm.getSocketFactory(); final Socket sock; try { sock=lsf.createSocket(conn.getSocket(),target.getHostName(),schm.resolvePort(target.getPort()),true); } catch ( ConnectException ex) { throw new HttpHostConnectException(target,ex); } prepareSocket(sock,context,params); conn.update(sock,target,lsf.isSecure(sock),params); }
Example 72
From project Possom, under directory /httpclient-api/src/main/java/no/sesat/search/http/.
Source file: HTTPClient.java

private static IOException interceptIOException(final String id,final URLConnection urlConn,final IOException ioe){ if (ioe instanceof SocketTimeoutException) { Statistic.getStatistic(id).addReadTimeout(); } else if (ioe instanceof ConnectException) { Statistic.getStatistic(id).addConnectTimeout(); } else { Statistic.getStatistic(id).addFailure(); } if (urlConn instanceof HttpURLConnection) { cleanErrorStream((HttpURLConnection)urlConn); } LOG.error("IOException occured for server at: " + id + " ("+ urlConn.getURL()+ ") ["+ ioe.getMessage()+ ']'); return ioe; }
Example 73
From project qi4j-libraries, under directory /sql/src/main/java/org/qi4j/library/sql/liquibase/.
Source file: LiquibaseService.java

public void activate() throws Exception { Logger log=LoggerFactory.getLogger(LiquibaseService.class.getName()); boolean enabled=config.configuration().enabled().get(); if (!enabled || !dataSource.isAvailable()) { return; } Connection c=null; try { c=dataSource.get().getConnection(); DatabaseConnection dc=new JdbcConnection(c); Liquibase liquibase=new Liquibase(config.configuration().changeLog().get(),new ClassLoaderResourceAccessor(),dc); liquibase.update(config.configuration().contexts().get()); } catch ( SQLException e) { Throwable ex=e; while (ex.getCause() != null) ex=ex.getCause(); if (ex instanceof ConnectException) { log.warn("Could not connect to database; Liquibase should be disabled"); return; } log.error("Liquibase could not perform database migration",e); if (c != null) try { c.rollback(); c.close(); } catch ( SQLException ex1) { } } catch ( ServiceImporterException ex) { log.warn("DataSource is not available - database refactoring skipped"); } }
Example 74
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences,String key){ final Preference p=setSummaries(sharedPreferences,key); if (key.equals("password")) { new TalkToServerTask(this,new FinishCallback(){ @Override public void onSuccess( JsonNode result){ setPasswordSummary(sharedPreferences,p); } @Override public void onFailure( Exception e){ if (e instanceof ConnectException) { if (e.getMessage().contains("Authentication")) { p.setSummary(R.string.invalid); Toast.makeText(getApplicationContext(),"Invalid user/password",Toast.LENGTH_SHORT).show(); } else if (e.getMessage().contains("unknown")) { Toast.makeText(getApplicationContext(),"If this is a RHQ 4.4 / JON 3.1 server, the password may be valid",Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(),"Error: " + e.getLocalizedMessage(),Toast.LENGTH_LONG).show(); } } } } ,"/status/server").execute(); } }
Example 75
From project Sage-Mobile-Calc, under directory /src/com/trilead/ssh2/channel/.
Source file: DynamicAcceptThread.java

public void run(){ try { startSession(); } catch ( IOException ioe) { int error_code=Proxy.SOCKS_FAILURE; if (ioe instanceof SocksException) error_code=((SocksException)ioe).errCode; else if (ioe instanceof NoRouteToHostException) error_code=Proxy.SOCKS_HOST_UNREACHABLE; else if (ioe instanceof ConnectException) error_code=Proxy.SOCKS_CONNECTION_REFUSED; else if (ioe instanceof InterruptedIOException) error_code=Proxy.SOCKS_TTL_EXPIRE; if (error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0) { error_code=Proxy.SOCKS_FAILURE; } sendErrorMessage(error_code); } finally { if (auth != null) auth.endSession(); } }
Example 76
From project serfj, under directory /src/test/java/net/sf/serfj/client/.
Source file: ClientTest.java

@Test public void testServerDown() throws IOException, WebServiceException { try { Client client=new Client("http://localhost:1234"); client.getRequest("",null); fail("Server doesn't exist, you can't reach this line"); } catch ( ConnectException e) { assertTrue(true); } }
Example 77
From project sonatype-aether, under directory /aether-connector-asynchttpclient/src/main/java/org/sonatype/aether/connector/async/.
Source file: AsyncRepositoryConnector.java

private boolean isResumeWorthy(Throwable t){ if (t instanceof IOException) { if (t instanceof ConnectException) { return false; } return true; } return false; }
Example 78
From project spring-amqp, under directory /spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/.
Source file: RabbitUtils.java

public static RuntimeException convertRabbitAccessException(Throwable ex){ Assert.notNull(ex,"Exception must not be null"); if (ex instanceof AmqpException) { return (AmqpException)ex; } if (ex instanceof ShutdownSignalException) { return new AmqpConnectException((ShutdownSignalException)ex); } if (ex instanceof ConnectException) { return new AmqpConnectException((ConnectException)ex); } if (ex instanceof IOException) { return new AmqpIOException((IOException)ex); } if (ex instanceof UnsupportedEncodingException) { return new AmqpUnsupportedEncodingException(ex); } return new UncategorizedAmqpException(ex); }
Example 79
From project tika, under directory /tika-core/src/test/java/org/apache/tika/sax/.
Source file: OfflineContentHandlerTest.java

public void testExternalDTD() throws Exception { String xml="<!DOCTYPE foo SYSTEM \"http://127.234.172.38:7845/bar\"><foo/>"; try { parser.parse(new InputSource(new StringReader(xml)),offline); } catch ( ConnectException e) { fail("Parser tried to access the external DTD:" + e); } }
Example 80
From project twistDemo, under directory /twist-libs/com.thoughtworks.webdriver.recorder_1.0.0.11288/sahi/src/net/sf/sahi/test/.
Source file: TestRunner.java

public static void main(String[] args){ try { if (args.length == 0) { help(); } if (mainCLIParams(args)) return; String suiteName=args[0]; String base=getBase(args); String browser=getBrowser(args); String logDir=args[3]; if ("default".equalsIgnoreCase(logDir)) { logDir=""; } String sahiHost=args[4]; String port=args[5]; String threads=args[6]; String browserOption=""; String browserProcessName=args[7]; if (args.length == 9) { browserOption=args[8]; } TestRunner testRunner=new TestRunner(suiteName,browser,base,sahiHost,port,threads,browserOption,browserProcessName); testRunner.addReport(new Report("html",logDir)); String status=testRunner.execute(); System.out.println("Status:" + status); } catch ( ConnectException ce) { System.err.println(ce.getMessage()); System.err.println("Could not connect to Sahi Proxy.\nVerify that the Sahi Proxy is running on the specified host and port."); help(); } catch ( Exception e) { e.printStackTrace(); help(); } }
Example 81
@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); cache=new DataCache(this,1000 * 60 * 60* 12); splash=new SplashDialog(this); splash.showCancelButton(cache.hasCachedFile(DATA_XML)); splash.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel( DialogInterface dialog){ cache.cancel(); } } ); splash.setBackButtonPressedListener(new OnBackButtonPressed(){ @Override public void onPressed(){ finish(); } } ); splash.show(); bar=getSupportActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); bar.setDisplayShowTitleEnabled(false); bar.setDisplayShowHomeEnabled(false); try { cache.get(DATA_XML,DATA_URL,this); } catch ( ConnectException e) { errorShowConnectionErrorAndExitButton(); } }
Example 82
From project Vega, under directory /platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/connection/.
Source file: SocksModeClientConnectionOperator.java

@Override public void openConnection(OperatedClientConnection conn,HttpHost target,InetAddress local,HttpContext context,HttpParams params) throws IOException { if (!isSocksMode) { super.openConnection(conn,target,local,context,params); return; } final Scheme scheme=schemeRegistry.getScheme(target.getSchemeName()); final SchemeSocketFactory sf=scheme.getSchemeSocketFactory(); final int port=scheme.resolvePort(target.getPort()); Socket sock=sf.createSocket(params); conn.opening(sock,target); InetSocketAddress remoteAddress=InetSocketAddress.createUnresolved(target.getHostName(),port); InetSocketAddress localAddress=null; if (local != null) { localAddress=new InetSocketAddress(local,0); } try { Socket connsock=sf.connectSocket(sock,remoteAddress,localAddress,params); if (sock != connsock) { sock=connsock; conn.opening(sock,target); } prepareSocket(sock,context,params); conn.openCompleted(sf.isSecure(sock),params); return; } catch ( ConnectException ex) { throw new HttpHostConnectException(target,ex); } }
Example 83
From project warlock2, under directory /core/cc.warlock.core/src/main/cc/warlock/core/network/.
Source file: Connection.java

public void connect(String host,int port) throws IOException { try { socket=new Socket(host,port); reader=createReader(socket); new Thread(createPollingRunnable()).start(); } catch ( IOException e) { if (e instanceof ConnectException && e.getMessage().contains("refused")) { connectionError(ErrorType.ConnectionRefused); } else if (e instanceof UnknownHostException) { connectionError(ErrorType.UnknownHost); } else throw e; } }
Example 84
From project wayback, under directory /wayback-access-control/access-control/src/main/java/org/archive/accesscontrol/robotstxt/.
Source file: HttpRobotClient.java

public RobotRules getRulesForUrl(String url,String userAgent) throws IOException, RobotsUnavailableException { String robotsUrl=robotsUrlForUrl(url); HttpMethod method=new GetMethod(robotsUrl); method.addRequestHeader("User-Agent",userAgent); try { int code=http.executeMethod(method); if (code != 200) { throw new RobotsUnavailableException(robotsUrl); } } catch ( HttpException e) { e.printStackTrace(); throw new RobotsUnavailableException(robotsUrl); } catch ( UnknownHostException e) { LOGGER.info("Unknown host for URL " + robotsUrl); throw new RobotsUnavailableException(robotsUrl); } catch ( ConnectTimeoutException e) { LOGGER.info("Connection Timeout for URL " + robotsUrl); throw new RobotsUnavailableException(robotsUrl); } catch ( NoRouteToHostException e) { LOGGER.info("No route to host for URL " + robotsUrl); throw new RobotsUnavailableException(robotsUrl); } catch ( ConnectException e) { LOGGER.info("ConnectException URL " + robotsUrl); throw new RobotsUnavailableException(robotsUrl); } RobotRules rules=new RobotRules(); rules.parse(method.getResponseBodyAsStream()); return rules; }
Example 85
From project winstone, under directory /src/java/winstone/cluster/.
Source file: SimpleCluster.java

/** * Given an address, retrieve the list of cluster nodes and initialise dates * @param address The address to request a node list from */ private void askClusterNodeForNodeList(String address){ try { int colonPos=address.indexOf(':'); String ipAddress=address.substring(0,colonPos); String port=address.substring(colonPos + 1); Socket clusterListSocket=new Socket(ipAddress,Integer.parseInt(port)); this.clusterAddresses.put(clusterListSocket.getInetAddress().getHostAddress() + ":" + port,new Date()); InputStream in=clusterListSocket.getInputStream(); OutputStream out=clusterListSocket.getOutputStream(); out.write(NODELIST_DOWNLOAD_TYPE); out.flush(); ObjectOutputStream outControl=new ObjectOutputStream(out); outControl.writeInt(this.controlPort); outControl.flush(); ObjectInputStream inData=new ObjectInputStream(in); int nodeCount=inData.readInt(); for (int n=0; n < nodeCount; n++) this.clusterAddresses.put(inData.readUTF(),new Date()); inData.close(); outControl.close(); out.close(); in.close(); clusterListSocket.close(); } catch ( ConnectException err) { Logger.log(Logger.DEBUG,CLUSTER_RESOURCES,"SimpleCluster.NoNodeListResponse",address); } catch ( Throwable err) { Logger.log(Logger.ERROR,CLUSTER_RESOURCES,"SimpleCluster.ErrorGetNodeList",address,err); } }
Example 86
From project zapcat, under directory /src/org/kjkoster/zapcat/test/.
Source file: ZabbixAgentConfigurationTest.java

private void assertAgentDown(final int port) throws Exception { try { JMXHelper.query(new ObjectName("org.kjkoster.zapcat:type=Agent,port=" + port),"Port"); fail(); } catch ( InstanceNotFoundException e) { } try { new Socket(InetAddress.getLocalHost(),port); fail(); } catch ( ConnectException e) { } }
Example 87
From project zk-service-registry-server, under directory /lib/zk-service-registry-server/zookeeper-3.3.3/src/java/main/org/apache/zookeeper/server/quorum/.
Source file: Learner.java

/** * Establish a connection with the Leader found by findLeader. Retries 5 times before giving up. * @param addr - the address of the Leader to connect to. * @throws IOException - if the socket connection fails on the 5th attempt * @throws ConnectException * @throws InterruptedException */ protected void connectToLeader(InetSocketAddress addr) throws IOException, ConnectException, InterruptedException { sock=new Socket(); sock.setSoTimeout(self.tickTime * self.initLimit); for (int tries=0; tries < 5; tries++) { try { sock.connect(addr,self.tickTime * self.syncLimit); sock.setTcpNoDelay(nodelay); break; } catch ( IOException e) { if (tries == 4) { LOG.error("Unexpected exception",e); throw e; } else { LOG.warn("Unexpected exception, tries=" + tries + ", connecting to "+ addr,e); sock=new Socket(); sock.setSoTimeout(self.tickTime * self.initLimit); } } Thread.sleep(1000); } leaderIs=BinaryInputArchive.getArchive(new BufferedInputStream(sock.getInputStream())); bufferedOutput=new BufferedOutputStream(sock.getOutputStream()); leaderOs=BinaryOutputArchive.getArchive(bufferedOutput); }
Example 88
From project zkclient, under directory /src/main/java/org/I0Itec/zkclient/.
Source file: NetworkUtil.java

public static boolean isPortFree(int port){ try { Socket socket=new Socket("localhost",port); socket.close(); return false; } catch ( ConnectException e) { return true; } catch ( SocketException e) { if (e.getMessage().equals("Connection reset by peer")) { return true; } throw new RuntimeException(e); } catch ( UnknownHostException e) { throw new RuntimeException(e); } catch ( IOException e) { throw new RuntimeException(e); } }
Example 89
From project zkclient_1, under directory /src/main/java/com/github/zkclient/.
Source file: NetworkUtil.java

public static boolean isPortFree(int port){ try { Socket socket=new Socket(); socket.connect(new InetSocketAddress("localhost",port),200); socket.close(); return false; } catch ( SocketTimeoutException e) { return true; } catch ( ConnectException e) { return true; } catch ( SocketException e) { if (e.getMessage().equals("Connection reset by peer")) { return true; } throw new RuntimeException(e); } catch ( UnknownHostException e) { throw new RuntimeException(e); } catch ( IOException e) { throw new RuntimeException(e); } }
Example 90
From project zookeeper, under directory /src/java/main/org/apache/zookeeper/.
Source file: ClientCnxn.java

private void pingRwServer() throws RWServerFoundException { String result=null; InetSocketAddress addr=hostProvider.next(0); LOG.info("Checking server " + addr + " for being r/w."+ " Timeout "+ pingRwTimeout); try { Socket sock=new Socket(addr.getHostName(),addr.getPort()); sock.setSoLinger(false,-1); sock.setSoTimeout(1000); sock.setTcpNoDelay(true); sock.getOutputStream().write("isro".getBytes()); sock.getOutputStream().flush(); sock.shutdownOutput(); BufferedReader br=new BufferedReader(new InputStreamReader(sock.getInputStream())); result=br.readLine(); sock.close(); br.close(); } catch ( ConnectException e) { } catch ( IOException e) { LOG.warn("Exception while seeking for r/w server " + e.getMessage(),e); } if ("rw".equals(result)) { pingRwTimeout=minPingRwTimeout; rwServerAddress=addr; throw new RWServerFoundException("Majority server found at " + addr.getHostName() + ":"+ addr.getPort()); } }