Java Code Examples for java.net.ConnectException

The following are top voted examples for showing how to use java.net.ConnectException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AppServiceRestFul   File: HttpSubscriber.java   View source code 9 votes vote down vote up
@Override
public void onError(Throwable e) {
    if(subscriberOnListener != null && context != null)
    {
        if (e instanceof SocketTimeoutException) {
            subscriberOnListener.onError(-1001, "网络超时,请检查您的网络状态");
        } else if (e instanceof ConnectException) {
            subscriberOnListener.onError(-1002, "网络链接中断,请检查您的网络状态");
        } else if(e instanceof ExceptionApi){
            subscriberOnListener.onError(((ExceptionApi)e).getCode(), ((ExceptionApi)e).getMsg());
        }
        else
        {
            subscriberOnListener.onError(-1003, "未知错误:" + e.getMessage());
        }
    }
    else
    {
        if(disposable != null && !disposable.isDisposed())
            disposable.dispose();
    }
}
 
Example 2
Project: wechat-api-java   File: HttpRequestUtil.java   View source code 8 votes vote down vote up
public static String doPost(String url, String json) throws Exception {
    try {
        CloseableHttpClient client = getHttpClient(url);
        HttpPost post = new HttpPost(url);
        config(post);
        logger.info("====> Executing request: " + post.getRequestLine());
        if (!StringUtils.isEmpty(json)) {
            StringEntity s = new StringEntity(json, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
        }
        String responseBody = client.execute(post, getStringResponseHandler());
        logger.info("====> Getting response from request " + post.getRequestLine() + " The responseBody: " + responseBody);
        return responseBody;
    } catch (Exception e) {
        if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) {
            throw new ConnectException("====> 连接服务器" + url + "失败: " + e.getMessage());
        }
        logger.error("====> HttpRequestUtil.doPost: " + e.getMessage(), e);
    }
    return null;
}
 
Example 3
Project: oscm   File: ProductProvisioningServiceFactoryBeanTest.java   View source code 6 votes vote down vote up
@Ignore
@Test(expected = ConnectException.class)
public void test_NoUser() throws Throwable {
    ServiceInstance instance = new ServiceInstance();
    ArrayList<InstanceParameter> params = new ArrayList<InstanceParameter>();
    params.add(PUBLIC_IP);
    params.add(WSDL);
    params.add(PROTOCOL);
    params.add(PORT);
    instance.setInstanceParameters(params);
    try {
        getInstance(instance);
    } catch (BadResultException e) {
        throw e.getCause();
    }
}
 
Example 4
Project: GitHub   File: RealConnection.java   View source code 6 votes vote down vote up
/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout) throws IOException {
  Proxy proxy = route.proxy();
  Address address = route.address();

  rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
      ? address.socketFactory().createSocket()
      : new Socket(proxy);

  rawSocket.setSoTimeout(readTimeout);
  try {
    Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
  } catch (ConnectException e) {
    ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
    ce.initCause(e);
    throw ce;
  }
  source = Okio.buffer(Okio.source(rawSocket));
  sink = Okio.buffer(Okio.sink(rawSocket));
}
 
Example 5
Project: GitHub   File: URLConnectionTest.java   View source code 6 votes vote down vote up
@Test public void getKeepAlive() throws Exception {
  server.enqueue(new MockResponse().setBody("ABC"));

  // The request should work once and then fail
  HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
  connection1.setReadTimeout(100);
  InputStream input = connection1.getInputStream();
  assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
  server.shutdown();
  try {
    HttpURLConnection connection2 = urlFactory.open(server.url("").url());
    connection2.setReadTimeout(100);
    connection2.getInputStream();
    fail();
  } catch (ConnectException expected) {
  }
}
 
Example 6
Project: hadoop   File: ExceptionDiags.java   View source code 6 votes vote down vote up
/**
 * Take an IOException and a URI, wrap it where possible with
 * something that includes the URI
 *
 * @param dest target URI
 * @param operation operation
 * @param exception the caught exception.
 * @return an exception to throw
 */
public static IOException wrapException(final String dest,
                                        final String operation,
                                        final IOException exception) {
  String action = operation + " " + dest;
  String xref = null;

  if (exception instanceof ConnectException) {
    xref = "ConnectionRefused";
  } else if (exception instanceof UnknownHostException) {
    xref = "UnknownHost";
  } else if (exception instanceof SocketTimeoutException) {
    xref = "SocketTimeout";
  } else if (exception instanceof NoRouteToHostException) {
    xref = "NoRouteToHost";
  }
  String msg = action
               + " failed on exception: "
               + exception;
  if (xref != null) {
     msg = msg + ";" + see(xref);
  }
  return wrapWithMessage(exception, msg);
}
 
Example 7
Project: netty-connection-pool   File: BasicMultiNodeConnPool.java   View source code 6 votes vote down vote up
@Override
public void preCreateConnections(final int count)
throws ConnectException, IllegalArgumentException {
	if(count > 0) {
		for(int i = 0; i < count; i ++) {
			final Channel conn = connectToAnyNode();
			if(conn == null) {
				throw new ConnectException(
					"Failed to pre-create the connections to the target nodes"
				);
			}
			final String nodeAddr = conn.attr(ATTR_KEY_NODE).get();
			if(conn.isActive()) {
				final Queue<Channel> connQueue = availableConns.get(nodeAddr);
				if(connQueue != null) {
					connQueue.add(conn);
				}
			} else {
				conn.close();
			}
		}
		LOG.info("Pre-created " + count + " connections");
	} else {
		throw new IllegalArgumentException("Connection count should be > 0, but got " + count);
	}
}
 
Example 8
Project: uavstack   File: AppHubBaseRestService.java   View source code 6 votes vote down vote up
@Override
public void failed(HttpClientCallbackResult result) {

    /**
     * auto fail record
     */
    HttpAsyncException e = result.getException();

    if (e != null && ((e.getCause() instanceof java.net.ConnectException)
            && e.getCause().getMessage().indexOf("Connection refused") > -1)) {

        getLogger().err(this, "Connection[" + postURL + "] is Unavailable. ", e);

        cfm.putFailConnection(url);
        /**
         * let's retry
         */
        doHttpPost(serverAddress, subPath, data, contentType, encoding, callBack);
        return;
    }

    if (callBack != null) {
        callBack.failed(result);
    }
}
 
Example 9
Project: AndroidSourceViewer   File: SearchDownload.java   View source code 6 votes vote down vote up
@Override
public Pair<Boolean, List<File>> onDownload(@NotNull ClassEntity[] classEntities, @NotNull File outputFolder) {
    String newUrl = null;
    try {
        newUrl = androidOnlineSearch(classEntities[0]);
    } catch (ConnectException | UnknownHostException e1) {
        if (timeoutListener != null) {
            timeoutListener.run();
        }
    } catch (Exception e) {
        Log.e(e);
    }
    if (!Utils.isEmpty(newUrl)) {
        for (ClassEntity entity : classEntities) {
            entity.setDownloadUrl(newUrl);
        }
        Log.debug("SearchDownload => " + newUrl);
        return new XrefDownload().onDownload(classEntities, outputFolder);
    }
    return Pair.create(false, Collections.<File>emptyList());
}
 
Example 10
Project: oscm   File: BssClient.java   View source code 6 votes vote down vote up
public String logoutUser(String saasId) throws ServletException,
        RemoteException {
    SessionServiceStub stub = new SessionServiceStub(getEndPoint(false));
    setBasicAuth(stub);
    SessionServiceStub.DeleteServiceSessionE dss = new SessionServiceStub.DeleteServiceSessionE();
    SessionServiceStub.DeleteServiceSession param = new SessionServiceStub.DeleteServiceSession();
    param.setSessionId(getSessionId(saasId));
    param.setSubscriptionKey(getSubscriptionKey(saasId));
    dss.setDeleteServiceSession(param);
    try {
        DeleteServiceSessionResponseE response = stub
                .deleteServiceSession(dss);
        return response.getDeleteServiceSessionResponse().get_return();
    } catch (AxisFault e) {
        if (port < 8185 && searchPort
                && e.getDetail() instanceof ConnectException) {
            // try again with another port
            port++;
            return logoutUser(saasId);
        }
        throw new ServletException(e);
    }
}
 
Example 11
Project: hekate   File: NetworkClientTest.java   View source code 6 votes vote down vote up
@Test
public void testConnectToUnknown() throws Exception {
    NetworkClient<String> client = createClient(f -> f.setConnectTimeout(Integer.MAX_VALUE));

    repeat(3, i -> {
        NetworkClientCallbackMock<String> callback = new NetworkClientCallbackMock<>();

        assertSame(NetworkClient.State.DISCONNECTED, client.state());

        try {
            client.connect(new InetSocketAddress(InetAddress.getLocalHost(), 15001), callback).get();

            fail("Error was expected");
        } catch (ExecutionException e) {
            assertTrue(e.getCause().toString(), ErrorUtils.isCausedBy(ConnectException.class, e));
        }

        assertSame(NetworkClient.State.DISCONNECTED, client.state());
        assertNull(client.remoteAddress());
        assertNull(client.localAddress());
        callback.assertConnects(0);
        callback.assertDisconnects(1);
        callback.assertErrors(1);
        callback.getErrors().forEach(e -> assertTrue(e.toString(), e instanceof ConnectException));
    });
}
 
Example 12
Project: AppServiceRestFul   File: HttpSubscriber.java   View source code 6 votes vote down vote up
@Override
public void onError(Throwable e) {
    if(subscriberOnListener != null && context != null)
    {
        if (e instanceof SocketTimeoutException) {
            subscriberOnListener.onError(-1001, "网络超时,请检查您的网络状态");
        } else if (e instanceof ConnectException) {
            subscriberOnListener.onError(-1002, "网络链接中断,请检查您的网络状态");
        } else if(e instanceof ExceptionApi){
            subscriberOnListener.onError(((ExceptionApi)e).getCode(), ((ExceptionApi)e).getMsg());
        }
        else
        {
            subscriberOnListener.onError(-1003, "未知错误:" + e.getMessage());
        }
    }
    else
    {
        if(disposable != null && !disposable.isDisposed())
            disposable.dispose();
    }
}
 
Example 13
Project: incubator-netbeans   File: NativeExecutionTestSupport.java   View source code 6 votes vote down vote up
private static RcFile createRemoteRcFile(ExecutionEnvironment env)
        throws IOException, RcFile.FormatException, ConnectException, CancellationException, InterruptedException, ExecutionException {
    if (!ConnectionManager.getInstance().isConnectedTo(env)) {
        new Exception("WARNING: getRemoteRcFile changes connection state for " + env).printStackTrace();
        ConnectionManager.getInstance().connectTo(env);
    }
    String envText = ExecutionEnvironmentFactory.toUniqueID(env).replace(':', '-').replace('@', '-');
    String tmpName = "cnd_remote_test_rc_" + envText;
    File tmpFile = File.createTempFile(tmpName, "");
    tmpFile.deleteOnExit();
    String remoteFilePath = HostInfoUtils.getHostInfo(env).getUserDir() + "/.cnd-remote-test-rc";
    if (fileExists(env, remoteFilePath)) {
        int rc = CommonTasksSupport.downloadFile(remoteFilePath, env, tmpFile, new PrintWriter(System.err)).get();
        if (rc != 0) {
            throw new IOException("Can't download file " + remoteFilePath + " from " + env);
        }
        return RcFile.create(tmpFile);
    } else {
        return RcFile.createDummy();
    }
}
 
Example 14
Project: incubator-netbeans   File: BugzillaExecutor.java   View source code 6 votes vote down vote up
private static String getNotFoundError(CoreException ce) {
    IStatus status = ce.getStatus();
    Throwable t = status.getException();
    if(t instanceof UnknownHostException ||
       // XXX maybe a different msg ?     
       t instanceof SocketTimeoutException || 
       t instanceof NoRouteToHostException ||
       t instanceof ConnectException) 
    {
        Bugzilla.LOG.log(Level.FINER, null, t);
        return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND");                   // NOI18N
    }
    String msg = getMessage(ce);
    if(msg != null) {
        msg = msg.trim().toLowerCase();
        if(HTTP_ERROR_NOT_FOUND.equals(msg)) {
            Bugzilla.LOG.log(Level.FINER, "returned error message [{0}]", msg);                     // NOI18N
            return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND");               // NOI18N
        }
    }
    return null;
}
 
Example 15
Project: oscm   File: ProductProvisioningServiceFactoryBeanTest.java   View source code 6 votes vote down vote up
@Ignore
@Test(expected = ConnectException.class)
public void test_NoUser() throws Throwable {
    ServiceInstance instance = new ServiceInstance();
    ArrayList<InstanceParameter> params = new ArrayList<InstanceParameter>();
    params.add(PUBLIC_IP);
    params.add(WSDL);
    params.add(PROTOCOL);
    params.add(PORT);
    instance.setInstanceParameters(params);
    try {
        getInstance(instance);
    } catch (BadResultException e) {
        throw e.getCause();
    }
}
 
Example 16
Project: hekate   File: NettyClientHandler.java   View source code 6 votes vote down vote up
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if (metrics != null) {
        metrics.onDisconnect();
    }

    if (state == CONNECTING) {
        state = DISCONNECTED;

        ctx.fireExceptionCaught(new ConnectException("Got disconnected on handshake [channel=" + id + ']'));
    } else {
        state = DISCONNECTED;

        super.channelInactive(ctx);
    }
}
 
Example 17
Project: okwallet   File: PeerSocketHandler.java   View source code 6 votes vote down vote up
/** Catch any exceptions, logging them and then closing the channel. */
private void exceptionCaught(Exception e) {
    PeerAddress addr = getAddress();
    String s = addr == null ? "?" : addr.toString();
    if (e instanceof ConnectException || e instanceof IOException) {
        // Short message for network errors
        log.info(s + " - " + e.getMessage());
    } else {
        log.warn(s + " - ", e);
        Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
        if (handler != null)
            handler.uncaughtException(Thread.currentThread(), e);
    }

    close();
}
 
Example 18
Project: hadoop-oss   File: TestRPC.java   View source code 6 votes vote down vote up
@Test
public void testClientWithoutServer() throws Exception {
  TestRpcService proxy;

  short invalidPort = 20;
  InetSocketAddress invalidAddress = new InetSocketAddress(ADDRESS,
      invalidPort);
  long invalidClientVersion = 1L;
  try {
    proxy = RPC.getProxy(TestRpcService.class,
        invalidClientVersion, invalidAddress, conf);
    // Test echo method
    proxy.echo(null, newEchoRequest("hello"));
    fail("We should not have reached here");
  } catch (ServiceException ioe) {
    //this is what we expected
    if (!(ioe.getCause() instanceof ConnectException)) {
      fail("We should not have reached here");
    }
  }
}
 
Example 19
Project: RxRetrofit-tokean   File: RetryWhenNetworkException.java   View source code 6 votes vote down vote up
@Override
public Observable<?> call(Observable<? extends Throwable> observable) {
    return observable
            .zipWith(Observable.range(1, count + 1), new Func2<Throwable, Integer, Wrapper>() {
                @Override
                public Wrapper call(Throwable throwable, Integer integer) {
                    return new Wrapper(throwable, integer);
                }
            }).flatMap(new Func1<Wrapper, Observable<?>>() {
                @Override
                public Observable<?> call(Wrapper wrapper) {
                    if ((wrapper.throwable instanceof ConnectException
                            || wrapper.throwable instanceof SocketTimeoutException
                            || wrapper.throwable instanceof TimeoutException)
                            && wrapper.index < count + 1) { //如果超出重试次数也抛出错误,否则默认是会进入onCompleted
                        return Observable.timer(delay + (wrapper.index - 1) * increaseDelay, TimeUnit.MILLISECONDS);

                    }
                    return Observable.error(wrapper.throwable);
                }
            });
}
 
Example 20
Project: TestChat   File: RetryWhenNetWorkException.java   View source code 6 votes vote down vote up
@Override
public Observable<?> call(Observable<? extends Throwable> observable) {

        return observable.zipWith(Observable.range(1, retryCount + 1), new Func2<Throwable, Integer, ExceptionWrapper>() {
                @Override
                public ExceptionWrapper call(Throwable throwable, Integer integer) {
                        return new ExceptionWrapper(integer, throwable);
                }
        }).flatMap(new Func1<ExceptionWrapper, Observable<?>>() {
                @Override
                public Observable<?> call(ExceptionWrapper exceptionWrapper) {
                        if ((exceptionWrapper.throwable instanceof ConnectException ||
                                exceptionWrapper.throwable instanceof SocketException ||
                                exceptionWrapper.throwable instanceof TimeoutException) && exceptionWrapper.index < retryCount + 1) {
                                return Observable.timer(delayTime + (exceptionWrapper.index - 1) * delayTime, java.util.concurrent.TimeUnit.MILLISECONDS);
                        }
                        return Observable.error(exceptionWrapper.throwable);
                }
        });
}
 
Example 21
Project: AntCloud   File: AntSubscriber.java   View source code 6 votes vote down vote up
@Override
public void onError(Throwable t) {
    if (t instanceof SocketTimeoutException
            || t instanceof InterruptedIOException) {
        error(AntError.TIMEOUT_ERROR_CODE, "链接超时", t);
    } else if (t instanceof UnknownHostException
            || t instanceof HttpException
            || t instanceof ConnectException) {
        error(AntError.NETWORK_ERROR_CODE, "网络异常", t);
    } else if (t instanceof JSONException
            || t instanceof JsonParseException
            || t instanceof ParseException) {
        error(AntError.PARSE_ERROR_CODE, "解析异常", t);
    } else {
        error(AntError.OTHER_ERROR_CODE, "其他异常", t);
    }
}
 
Example 22
Project: oscm   File: BssClient.java   View source code 6 votes vote down vote up
public String resolveUsertoken(String usertoken, String saasId)
        throws ServletException, RemoteException {
    SessionServiceStub stub = new SessionServiceStub(getEndPoint(false));
    setBasicAuth(stub);
    SessionServiceStub.ResolveUserTokenE rut = new SessionServiceStub.ResolveUserTokenE();
    SessionServiceStub.ResolveUserToken param = new SessionServiceStub.ResolveUserToken();
    param.setSessionId(getSessionId(saasId));
    param.setUserToken(usertoken);
    param.setSubscriptionKey(getSubscriptionKey(saasId));
    rut.setResolveUserToken(param);
    try {
        ResolveUserTokenResponseE response = stub.resolveUserToken(rut);
        return response.getResolveUserTokenResponse().get_return();
    } catch (AxisFault e) {
        if (port < 8185 && searchPort
                && e.getDetail() instanceof ConnectException) {
            // try again with another port
            port++;
            return resolveUsertoken(usertoken, saasId);
        }
        throw new ServletException(e);
    }
}
 
Example 23
Project: openjdk-jdk10   File: JMXStartStopTest.java   View source code 6 votes vote down vote up
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof RemoteException ||
                t instanceof SSLHandshakeException ||
                t instanceof ConnectException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
 
Example 24
Project: oscm-app   File: ProductProvisioningServiceFactoryBeanTest.java   View source code 6 votes vote down vote up
@Ignore
@Test(expected = ConnectException.class)
public void test_NoUser() throws Throwable {
    ServiceInstance instance = new ServiceInstance();
    ArrayList<InstanceParameter> params = new ArrayList<InstanceParameter>();
    params.add(PUBLIC_IP);
    params.add(WSDL);
    params.add(PROTOCOL);
    params.add(PORT);
    instance.setInstanceParameters(params);
    try {
        getInstance(instance);
    } catch (BadResultException e) {
        throw e.getCause();
    }
}
 
Example 25
Project: oscm-app   File: ProductProvisioningServiceFactoryBeanTest.java   View source code 6 votes vote down vote up
@Ignore
@Test(expected = ConnectException.class)
public void test_NoPassword() throws Throwable {
    ServiceInstance instance = new ServiceInstance();
    ArrayList<InstanceParameter> params = new ArrayList<InstanceParameter>();
    params.add(PUBLIC_IP);
    params.add(WSDL);
    params.add(PROTOCOL);
    params.add(PORT);
    params.add(USER);
    instance.setInstanceParameters(params);
    try {
        getInstance(instance);
    } catch (BadResultException e) {
        throw e.getCause();
    }
}
 
Example 26
Project: oscm-app   File: ProductProvisioningServiceFactoryBeanTest.java   View source code 6 votes vote down vote up
@Ignore
@Test(expected = ConnectException.class)
public void test() throws Throwable {
    ServiceInstance instance = new ServiceInstance();
    ArrayList<InstanceParameter> params = new ArrayList<InstanceParameter>();
    params.add(PUBLIC_IP);
    params.add(WSDL);
    params.add(PROTOCOL);
    params.add(PORT);
    params.add(USER);
    params.add(USER_PWD);
    instance.setInstanceParameters(params);
    try {
        getInstance(instance);
    } catch (BadResultException e) {
        throw e.getCause();
    }
}
 
Example 27
Project: My-Android-Base-Code   File: ErrorUtils.java   View source code 6 votes vote down vote up
public void checkError(Throwable e){
    try {
        throwable = e;
        fireBaseReportError(e);
        Crashlytics.logException(e);
        e.printStackTrace();

        if (e instanceof HttpException) {
            int code = getHttpErrorCode(e);
            httpMessage(code);
        }
        else if (e instanceof ConnectException) {
            showToast(mContext.getString(R.string.slow_internet));
        } else if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
            showToast(mContext.getString(R.string.internet_not_connected));
        } else if (e instanceof SSLHandshakeException || e instanceof SSLPeerUnverifiedException) {
            showToast(mContext.getString(R.string.server_problem));
        } else {
            showToast(mContext.getString(R.string.unknown_error_msg));
        }
    }
    catch (Exception err){
        err.printStackTrace();
    }
}
 
Example 28
Project: JBase   File: BaseObserver.java   View source code 6 votes vote down vote up
@Override
public void onError(@NonNull Throwable e) {
    LoadingDialog.dissmiss();
    String errMsg = "";
    if (e instanceof SocketTimeoutException) {
        errMsg = "网络连接超时,请检查您的网络状态,稍后重试";
    } else if (e instanceof ConnectException) {
        errMsg = "网络连接异常,请检查您的网络状态";
    } else if (e instanceof UnknownHostException) {
        errMsg = "网络异常,请检查您的网络状态";
    } else {
        errMsg = e.getMessage();
    }
    LogUtils.i("onError:" + errMsg);
    _onError(errMsg);

}
 
Example 29
Project: oscm   File: ProductProvisioningServiceFactoryBeanTest.java   View source code 6 votes vote down vote up
@Ignore
@Test(expected = ConnectException.class)
public void test_NoPassword() throws Throwable {
    ServiceInstance instance = new ServiceInstance();
    ArrayList<InstanceParameter> params = new ArrayList<InstanceParameter>();
    params.add(PUBLIC_IP);
    params.add(WSDL);
    params.add(PROTOCOL);
    params.add(PORT);
    params.add(USER);
    instance.setInstanceParameters(params);
    try {
        getInstance(instance);
    } catch (BadResultException e) {
        throw e.getCause();
    }
}
 
Example 30
Project: chromium-net-for-android   File: CronetUrlRequestTest.java   View source code 6 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
public void testUploadFailsWithoutInitializingStream() throws Exception {
    TestUrlRequestCallback callback = new TestUrlRequestCallback();
    // The port for PTP will always refuse a TCP connection
    UrlRequest.Builder builder = new UrlRequest.Builder("http://127.0.0.1:319", callback,
            callback.getExecutor(), mTestFramework.mCronetEngine);

    TestUploadDataProvider dataProvider = new TestUploadDataProvider(
            TestUploadDataProvider.SuccessCallbackMode.SYNC, callback.getExecutor());
    dataProvider.addRead("test".getBytes());
    builder.setUploadDataProvider(dataProvider, callback.getExecutor());
    builder.addHeader("Content-Type", "useless/string");
    builder.build().start();
    callback.blockForDone();
    dataProvider.assertClosed();

    assertNull(callback.mResponseInfo);
    if (testingJavaImpl()) {
        Throwable cause = callback.mError.getCause();
        assertTrue("Exception was: " + cause, cause instanceof ConnectException);
    } else {
        assertEquals("Exception in CronetUrlRequest: net::ERR_CONNECTION_REFUSED",
                callback.mError.getMessage());
    }
}
 
Example 31
Project: aceql-http   File: WebServerApi.java   View source code 6 votes vote down vote up
/**
    * Stops the embedded Web server running on the designated port.
    * 
    * @param port
    *            the port on which the SQL Web server is running
    * 
    * @throws IOException
    *             if the semaphore file (that signals to the Web Server to
    *             stop) can not be created
    */
   public void stopServer(int port) throws IOException {
 
PortSemaphoreFile portSemaphoreFile = new PortSemaphoreFile(port);

if (! portSemaphoreFile.exists()) {
    throw new ConnectException("WARNING! There is no " + Version.PRODUCT.NAME + " Web server running on port " + port); 
}

// Always Force the deletion of the semaphore file:
try {
    portSemaphoreFile.delete();
} catch (IOException ioe) {
    throw new IOException(
	    "Can not stop the Web server. Please delete manually the semaphore file "
		    + portSemaphoreFile.getSemaphoreFile()
		    + " and then retry. ", ioe);
}

if (TomcatStarterUtil.available(port)) {	    
    throw new ConnectException("WARNING! There is no SQL Web server running on port " + port); 
}

   }
 
Example 32
Project: osc-core   File: ServerControl.java   View source code 6 votes vote down vote up
private static boolean isRunningServer() {
    try {
        log.info("Check if server is running ...");
        VmidcServerRestClient restClient = new VmidcServerRestClient("localhost", apiPort, VMIDC_DEFAULT_LOGIN, VMIDC_DEFAULT_PASS, true);

        ServerStatusResponse res = getServerStatusResponse(restClient);

        String oldPid = res.getPid();

        log.warn("Current pid:" + ServerUtil.getCurrentPid() + ". Running server (pid:" + oldPid + ") version: "
                + res.getVersion() + " with db version: " + res.getDbVersion());

        return true;
    } catch (ProcessingException | ConnectException e1) {
        log.warn("Fail to connect to running server: "+ e1.getMessage());
    } catch (Exception ex) {
        log.warn("Fail to connect to running server. Assuming not running: " + ex);
    }

    return false;
}
 
Example 33
Project: simulacron   File: ServerTest.java   View source code 5 votes vote down vote up
@Test
public void testStopAndStart() throws Exception {
  try (BoundNode boundNode = localServer.register(NodeSpec.builder());
      MockClient client = new MockClient(eventLoop)) {
    client.connect(boundNode.getAddress());
    client.write(new Startup());

    // sleep a little bit as connected channels may not be registered immediately.
    Thread.sleep(50);
    NodeConnectionReport report = boundNode.getConnections();
    assertThat(report.getConnections()).hasSize(1);

    // stop the node, connection should close.
    boundNode.stop();
    report = boundNode.getConnections();
    assertThat(report.getConnections()).hasSize(0);

    // attempt to connect should fail
    try {
      client.connect(boundNode.getAddress());
      fail("Should not have been able to connect");
    } catch (ConnectException ce) {
      // expected
    }

    // start the node
    boundNode.start();

    // attempt to connect should succeed
    client.connect(boundNode.getAddress());

    // sleep a little bit as connected channels may not be registered immediately.
    Thread.sleep(50);

    report = boundNode.getConnections();
    assertThat(report.getConnections()).hasSize(1);
  }
}
 
Example 34
Project: OSchina_resources_android   File: AppException.java   View source code 5 votes vote down vote up
public static AppException io(Exception e, int code) {
    if (e instanceof UnknownHostException || e instanceof ConnectException) {
        return new AppException(TYPE_NETWORK, code, e);
    } else if (e instanceof IOException) {
        return new AppException(TYPE_IO, code, e);
    }
    return run(e);
}
 
Example 35
Project: ditb   File: PreemptiveFastFailInterceptor.java   View source code 5 votes vote down vote up
/**
 * Check if the exception is something that indicates that we cannot
 * contact/communicate with the server.
 *
 * @param e
 * @return true when exception indicates that the client wasn't able to make contact with server
 */
private boolean isConnectionException(Throwable e) {
  if (e == null)
    return false;
  // This list covers most connectivity exceptions but not all.
  // For example, in SocketOutputStream a plain IOException is thrown
  // at times when the channel is closed.
  return (e instanceof SocketTimeoutException
      || e instanceof ConnectException || e instanceof ClosedChannelException
      || e instanceof SyncFailedException || e instanceof EOFException
      || e instanceof TimeoutException
      || e instanceof ConnectionClosingException || e instanceof FailedServerException);
}
 
Example 36
Project: JInsight   File: AbstractHttpClientInstrumentationTest.java   View source code 5 votes vote down vote up
@Test
public void testConnectErrors() throws Exception {
  Snapshot expectedCounts = tracker.snapshot();
  HttpGet request = new HttpGet("http://0.0.0.0/asd");
  HttpResponse response = null;
  try {
    response = httpclient.execute(request);
  } catch (ConnectException e) {
    //expected ... hence assertNull(response)
  }
  assertNull(response);
  tracker.validate(expectedCounts);//validate no metrics change
}
 
Example 37
Project: angel   File: MLRPC.java   View source code 5 votes vote down vote up
/**
 * @param retries current retried times.
 * @param maxAttmpts max attempts
 * @param protocol protocol interface
 * @param addr address of remote service
 * @param ce ConnectException
 * @throws RetriesExhaustedException
 */
private static void handleConnectionException(int retries, int maxAttmpts, Class<?> protocol,
    InetSocketAddress addr, ConnectException ce) throws RetriesExhaustedException {
  if (maxAttmpts >= 0 && retries >= maxAttmpts) {
    LOG.info("Server at " + addr + " could not be reached after " + maxAttmpts
        + " tries, giving up.");
    throw new RetriesExhaustedException("Failed setting up proxy " + protocol + " to "
        + addr.toString() + " after attempts=" + maxAttmpts, ce);
  }
}
 
Example 38
Project: GitHub   File: ExceptionEngine.java   View source code 5 votes vote down vote up
public static ApiException handleException(Throwable e) {
    ApiException ex;
    if (e instanceof HttpException) {             //HTTP错误
        HttpException httpExc = (HttpException) e;
        ex = new ApiException(e, httpExc.code());
        ex.setMsg("网络错误");  //均视为网络错误
        return ex;
    } else if (e instanceof ServerException) {    //服务器返回的错误
        ServerException serverExc = (ServerException) e;
        ex = new ApiException(serverExc, serverExc.getCode());
        ex.setMsg(serverExc.getMsg());
        return ex;
    } else if (e instanceof JsonParseException
            || e instanceof JSONException
            || e instanceof ParseException || e instanceof MalformedJsonException) {  //解析数据错误
        ex = new ApiException(e, ANALYTIC_SERVER_DATA_ERROR);
        ex.setMsg("解析错误");
        return ex;
    } else if (e instanceof ConnectException) {//连接网络错误
        ex = new ApiException(e, CONNECT_ERROR);
        ex.setMsg("连接失败");
        return ex;
    } else if (e instanceof SocketTimeoutException) {//网络超时
        ex = new ApiException(e, TIME_OUT_ERROR);
        ex.setMsg("网络超时");
        return ex;
    } else {  //未知错误
        ex = new ApiException(e, UN_KNOWN_ERROR);
        ex.setMsg("未知错误");
        return ex;
    }
}
 
Example 39
Project: teamcity-msteams-notifier   File: MsTeamsNotificationTest.java   View source code 5 votes vote down vote up
@Ignore
@Test(expected=java.net.ConnectException.class)
public void test_ConnectionRefused() throws ConnectException, IOException{
	MsTeamsNotification w = factory.getMsTeamsNotification();
	w.setEnabled(true);
	w.post();		
}
 
Example 40
Project: slacklet   File: SlackWebSocketSessionImpl.java   View source code 5 votes vote down vote up
private void connectImpl() throws IOException
{
    LOGGER.info("connecting to slack");
    HttpClient httpClient = getHttpClient();
    HttpGet request = new HttpGet(SLACK_HTTPS_AUTH_URL + authToken);
    HttpResponse response;
    response = httpClient.execute(request);
    LOGGER.debug(response.getStatusLine().toString());
    String jsonResponse = consumeToString(response.getEntity().getContent());
    SlackJSONSessionStatusParser sessionParser = new SlackJSONSessionStatusParser(jsonResponse);
    sessionParser.parse();
    if (sessionParser.getError() != null)
    {
        LOGGER.error("Error during authentication : " + sessionParser.getError());
        throw new ConnectException(sessionParser.getError());
    }

    users = sessionParser.getUsers();
    integrations = sessionParser.getIntegrations();
    channels = sessionParser.getChannels();
    sessionPersona = sessionParser.getSessionPersona();
    team = sessionParser.getTeam();
    LOGGER.info("Team " + team.getId() + " : " + team.getName());
    LOGGER.info("Self " + sessionPersona.getId() + " : " + sessionPersona.getUserName());
    LOGGER.info(users.size() + " users found on this session");
    LOGGER.info(channels.size() + " channels found on this session");
    webSocketConnectionURL = sessionParser.getWebSocketURL();
    LOGGER.debug("retrieved websocket URL : " + webSocketConnectionURL);
    establishWebsocketConnection();
}