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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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();
}
 
Example 41
Project: GitHub   File: RealConnection.java   Source Code and License 5 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, Call call,
    EventListener eventListener) 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);

  eventListener.connectStart(call, route.socketAddress(), 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;
  }

  // The following try/catch block is a pseudo hacky way to get around a crash on Android 7.0
  // More details:
  // https://github.com/square/okhttp/issues/3245
  // https://android-review.googlesource.com/#/c/271775/
  try {
    source = Okio.buffer(Okio.source(rawSocket));
    sink = Okio.buffer(Okio.sink(rawSocket));
  } catch (NullPointerException npe) {
    if (NPE_THROW_WITH_NULL.equals(npe.getMessage())) {
      throw new IOException(npe);
    }
  }
}
 
Example 42
Project: T0rlib4Android   File: ProxyServer.java   Source Code and License 5 votes vote down vote up
private void handleException(final IOException ioe) {
	// If we couldn't read the request, return;
	if (msg == null) {
		return;
	}
	// If have been aborted by other thread
	if (mode == ABORT_MODE) {
		return;
	}
	// If the request was successfully completed, but exception happened
	// later
	if (mode == PIPE_MODE) {
		return;
	}

	int error_code = SocksProxyBase.SOCKS_FAILURE;

	if (ioe instanceof SocksException) {
		error_code = ((SocksException) ioe).errCode;
	} else if (ioe instanceof NoRouteToHostException) {
		error_code = SocksProxyBase.SOCKS_HOST_UNREACHABLE;
	} else if (ioe instanceof ConnectException) {
		error_code = SocksProxyBase.SOCKS_CONNECTION_REFUSED;
	} else if (ioe instanceof InterruptedIOException) {
		error_code = SocksProxyBase.SOCKS_TTL_EXPIRE;
	}

	if ((error_code > SocksProxyBase.SOCKS_ADDR_NOT_SUPPORTED)
			|| (error_code < 0)) {
		error_code = SocksProxyBase.SOCKS_FAILURE;
	}

	sendErrorMessage(error_code);
}
 
Example 43
Project: monarch   File: AutoConnectionSourceImpl.java   Source Code and License 5 votes vote down vote up
private synchronized void reportDeadLocator(InetSocketAddress l, Exception ex) {
  Object prevState = this.locatorState.put(l, ex);
  if (prevState == null) {
    if (ex instanceof ConnectException) {
      logger.info(LocalizedMessage
          .create(LocalizedStrings.AutoConnectionSourceImpl_LOCATOR_0_IS_NOT_RUNNING, l), ex);
    } else {
      logger.info(LocalizedMessage.create(
          LocalizedStrings.AutoConnectionSourceImpl_COMMUNICATION_WITH_LOCATOR_0_FAILED_WITH_1,
          new Object[] {l, ex}), ex);
    }
  }
}
 
Example 44
Project: DereHelper   File: MainViewModel.java   Source Code and License 5 votes vote down vote up
private void downLoadFiles(int i, String masterHash, String truthVersion){
    if (i < hashToDownload.size()){
        String hash = hashToDownload.get(i);
        Observable<ResponseBody> file = useReverseProxy ?
                RetrofitProvider.getInstance(false).create(CGSSService.class).getResourcesRP(hash) :
                RetrofitProvider.getInstance(false).create(CGSSService.class).getResources(hash);
        file.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(responseBody -> {
                    try {
                        FileHelper.writeFile(LZ4Helper.uncompressCGSS(responseBody.bytes()), fileToDownload.get(hash).first, fileToDownload.get(hash).second);
                        progress.set((float) ++solved / (float) total);
                        progressTxt.set(getProgress());
                        downLoadFiles(i + 1, masterHash, truthVersion);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }, throwable -> {
                    if (retryTimes < 50){
                        if (throwable instanceof HttpException || throwable instanceof SocketTimeoutException
                                || throwable instanceof ConnectException){
                            downLoadFiles(i, masterHash, truthVersion);
                        }
                    }else {
                        umi.makeToast(R.string.network_error_0);
                    }
                });
    }else {
        finishManifestUpdate(masterHash, truthVersion);
    }
}
 
Example 45
Project: keti   File: ACSTestUtil.java   Source Code and License 5 votes vote down vote up
public static boolean isServerListening(final URI url) {
    RestTemplate restTemplate = new RestTemplate();
    try {
        restTemplate.getForObject(url, String.class);
    } catch (RestClientException e) {
        if (e.getCause() instanceof ConnectException) {
            return false;
        }
    }
    return true;
}
 
Example 46
Project: lams   File: HessianClientInterceptor.java   Source Code and License 5 votes vote down vote up
/**
 * Convert the given Hessian access exception to an appropriate
 * Spring RemoteAccessException.
 * @param ex the exception to convert
 * @return the RemoteAccessException to throw
 */
protected RemoteAccessException convertHessianAccessException(Throwable ex) {
	if (ex instanceof HessianConnectionException || ex instanceof ConnectException) {
		return new RemoteConnectFailureException(
				"Cannot connect to Hessian remote service at [" + getServiceUrl() + "]", ex);
	}
	else {
		return new RemoteAccessException(
			"Cannot access Hessian remote service at [" + getServiceUrl() + "]", ex);
	}
}
 
Example 47
Project: appium-maven-plugin   File: UtilityFunctions.java   Source Code and License 5 votes vote down vote up
protected static int getAppiumStatus(String appiumIpAddress, String appiumPort) throws IOException {
    OkHttpClient client = new OkHttpClient();
    URL appiumURL = new URL("http://" + appiumIpAddress + ":" + appiumPort + "/wd/hub/status");

    try {
        Request request = new Request.Builder()
                .url(appiumURL)
                .build();

        return client.newCall(request).execute().code();
    } catch (ConnectException ex) {
        //Appium not yet responding
        return 0;
    }
}
 
Example 48
Project: AgentX   File: SocketTunnel.java   Source Code and License 5 votes vote down vote up
private void buildConnection(SelectionKey key) {
    try {
        // connect to dstAddr, sign bridge
        SocketChannel dstSocket;
        try {
            dstSocket = SocketChannel.open(dstAddr);
        } catch (ConnectException ce) {
            System.err.print("connection broke (" + ce.getMessage() + "), restarting... ");
            restart();
            System.err.println("ok!");
            return;
        }

        SocketChannel srcSocket;
        srcSocket = server.accept();
        srcSocket.configureBlocking(false);
        srcSocket.socket().setSoLinger(true, 0);
        srcSocket.register(selector, SelectionKey.OP_READ);

        // copy src-socket attributes
        dstSocket.socket().setReceiveBufferSize(srcSocket.socket().getReceiveBufferSize());
        dstSocket.socket().setSoTimeout(srcSocket.socket().getSoTimeout());
        dstSocket.socket().setTcpNoDelay(srcSocket.socket().getTcpNoDelay());
        dstSocket.socket().setKeepAlive(srcSocket.socket().getKeepAlive());
        dstSocket.socket().setOOBInline(srcSocket.socket().getOOBInline()); // urgent data
        dstSocket.socket().setSoLinger(true, 0);
        dstSocket.configureBlocking(false);
        bridge.put(srcSocket, dstSocket);
        bridge.put(dstSocket, srcSocket);
        dstSocket.register(selector, SelectionKey.OP_READ);

    } catch (IOException e) {
        e.printStackTrace();
    }
    key.interestOps(SelectionKey.OP_ACCEPT);
}
 
Example 49
Project: incubator-netbeans   File: HostInfoUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Tests whether a file <tt>fname</tt> exists in <tt>execEnv</tt>.
 * If execEnv refers to a remote host that is not connected yet, a
 * <tt>ConnectException</tt> is thrown.
 *
 * @param execEnv <tt>ExecutionEnvironment</tt> to check for file existence
 *        in.
 * @param fname name of file to check for
 *
 * @return <tt>true</tt> if file exists, <tt>false</tt> otherwise.
 *
 * @throws ConnectException if host, identified by this execution
 * environment is not connected or operation was terminated.
 *
 * @throws InterruptedException if the thread was interrupted.
 *
 * @throws IOException if the process could not be created
 */
public static boolean fileExists(final ExecutionEnvironment execEnv,
        final String fname)
        throws ConnectException, IOException, InterruptedException {

    if (execEnv.isLocal()) {
        return new File(fname).exists();
    } else {
        if (!ConnectionManager.getInstance().isConnectedTo(execEnv)) {
            throw new ConnectException();
        }

        try {
            SftpSupport.getInstance(execEnv).lstat(fname).get();
            return true;
        } catch (ExecutionException ex) {
            if (ex.getCause() instanceof SftpIOException) {
                SftpIOException e = (SftpIOException) ex.getCause();
                if (SftpIOException.SSH_FX_NO_SUCH_FILE == e.getId()) {
                    return false;
                }
            }
            if (ex.getCause() instanceof IOException) {
                throw (IOException) ex.getCause();
            }
            throw new IOException(ex);
        }
    }
}
 
Example 50
Project: incubator-netbeans   File: NativeExecutionTestSupport.java   Source Code and License 5 votes vote down vote up
public static synchronized RcFile getRemoteRcFile(ExecutionEnvironment env)
        throws IOException, RcFile.FormatException, ConnectException, 
        CancellationException, InterruptedException, InterruptedException,
        ExecutionException {
    if (env == null) {
        new Exception("WARNING: null ExecutionEnvironment; returning dummy remote rc file").printStackTrace();
        return RcFile.createDummy();
    }
    RcFile rcFile = remoteRcFiles.get(env);
    if (rcFile == null) {
        rcFile = createRemoteRcFile(env);
        remoteRcFiles.put(env, rcFile);
    }
    return rcFile;
}
 
Example 51
Project: okwallet   File: NioClientManager.java   Source Code and License 5 votes vote down vote up
private void handleKey(SelectionKey key) throws IOException {
    // We could have a !isValid() key here if the connection is already closed at this point
    if (key.isValid() && key.isConnectable()) { // ie a client connection which has finished the initial connect process
        // Create a ConnectionHandler and hook everything together
        PendingConnect data = (PendingConnect) key.attachment();
        StreamConnection connection = data.connection;
        SocketChannel sc = (SocketChannel) key.channel();
        ConnectionHandler handler = new ConnectionHandler(connection, key, connectedHandlers);
        try {
            if (sc.finishConnect()) {
                log.info("Connected to {}", sc.socket().getRemoteSocketAddress());
                key.interestOps((key.interestOps() | SelectionKey.OP_READ) & ~SelectionKey.OP_CONNECT).attach(handler);
                connection.connectionOpened();
                data.future.set(data.address);
            } else {
                log.warn("Failed to connect to {}", sc.socket().getRemoteSocketAddress());
                handler.closeConnection(); // Failed to connect for some reason
                data.future.setException(new ConnectException("Unknown reason"));
                data.future = null;
            }
        } catch (Exception e) {
            // If e is a CancelledKeyException, there is a race to get to interestOps after finishConnect() which
            // may cause this. Otherwise it may be any arbitrary kind of connection failure.
            // Calling sc.socket().getRemoteSocketAddress() here throws an exception, so we can only log the error itself
            Throwable cause = Throwables.getRootCause(e);
            log.warn("Failed to connect with exception: {}: {}", cause.getClass().getName(), cause.getMessage(), e);
            handler.closeConnection();
            data.future.setException(cause);
            data.future = null;
        }
    } else // Process bytes read
        ConnectionHandler.handleKey(key);
}
 
Example 52
Project: oscm   File: BesDAOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void isBESAvalible_false() throws Exception {
    // given
    doThrow(new APPlatformException("", new ConnectException())).when(
            besDAO).getBESWebService(eq(IdentityService.class),
            any(ServiceInstance.class), any(Optional.class));
    // when
    boolean result = besDAO.isBESAvalible();

    // then
    assertFalse(result);
}
 
Example 53
Project: launcher-backend   File: MissionControl.java   Source Code and License 5 votes vote down vote up
public String validateOpenShiftTokenExists(String authHeader, String cluster) {
    String validationMessage;
    try {
        UriBuilder builder = UriBuilder.fromUri(missionControlValidationURI).path("/token/openshift");
        if (cluster != null) {
            builder.queryParam("cluster", cluster);
        }
        URI targetURI = builder.build();
        if (head(targetURI, authHeader) == Response.Status.OK.getStatusCode()) {
            validationMessage = VALIDATION_MESSAGE_OK;
        } else {
            validationMessage = "OpenShift Token does not exist";
        }
    } catch (Exception e) {
        String message = e.getMessage();
        Throwable root = rootException(e);
        if (root instanceof UnknownHostException || root instanceof ConnectException) {
            validationMessage = "Mission Control is offline and cannot validate if the OpenShift token exists";
        } else {
            if (root.getMessage() != null) {
                message = root.getMessage();
            }
            validationMessage = "Error while validating if the OpenShift Token exists: " + message;
        }
    }
    return validationMessage;
}
 
Example 54
Project: hadoop   File: ServerProxy.java   Source Code and License 5 votes vote down vote up
protected static RetryPolicy createRetryPolicy(Configuration conf,
    String maxWaitTimeStr, long defMaxWaitTime,
    String connectRetryIntervalStr, long defRetryInterval) {
  long maxWaitTime = conf.getLong(maxWaitTimeStr, defMaxWaitTime);
  long retryIntervalMS =
      conf.getLong(connectRetryIntervalStr, defRetryInterval);
  if (maxWaitTime == -1) {
    // wait forever.
    return RetryPolicies.RETRY_FOREVER;
  }

  Preconditions.checkArgument(maxWaitTime > 0, "Invalid Configuration. "
      + maxWaitTimeStr + " should be a positive value.");
  Preconditions.checkArgument(retryIntervalMS > 0, "Invalid Configuration. "
      + connectRetryIntervalStr + "should be a positive value.");

  RetryPolicy retryPolicy =
      RetryPolicies.retryUpToMaximumTimeWithFixedSleep(maxWaitTime,
        retryIntervalMS, TimeUnit.MILLISECONDS);

  Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
      new HashMap<Class<? extends Exception>, RetryPolicy>();
  exceptionToPolicyMap.put(EOFException.class, retryPolicy);
  exceptionToPolicyMap.put(ConnectException.class, retryPolicy);
  exceptionToPolicyMap.put(NoRouteToHostException.class, retryPolicy);
  exceptionToPolicyMap.put(UnknownHostException.class, retryPolicy);
  exceptionToPolicyMap.put(RetriableException.class, retryPolicy);
  exceptionToPolicyMap.put(SocketException.class, retryPolicy);
  exceptionToPolicyMap.put(NMNotYetReadyException.class, retryPolicy);

  return RetryPolicies.retryByException(RetryPolicies.TRY_ONCE_THEN_FAIL,
    exceptionToPolicyMap);
}
 
Example 55
Project: hadoop-oss   File: TestNetUtils.java   Source Code and License 5 votes vote down vote up
@Test
public void testWrapConnectException() throws Throwable {
  IOException e = new ConnectException("failed");
  IOException wrapped = verifyExceptionClass(e, ConnectException.class);
  assertInException(wrapped, "failed");
  assertWikified(wrapped);
  assertInException(wrapped, "localhost");
  assertRemoteDetailsIncluded(wrapped);
  assertInException(wrapped, "/ConnectionRefused");
}
 
Example 56
Project: hadoop-oss   File: TestRPCWaitForProxy.java   Source Code and License 5 votes vote down vote up
/**
 * This tests that the time-bounded wait for a proxy operation works, and
 * times out.
 *
 * @throws Throwable any exception other than that which was expected
 */
@Test(timeout = 10000)
public void testWaitForProxy() throws Throwable {
  RpcThread worker = new RpcThread(0);
  worker.start();
  worker.join();
  Throwable caught = worker.getCaught();
  assertNotNull("No exception was raised", caught);
  if (!(caught instanceof ConnectException)) {
    throw caught;
  }
}
 
Example 57
Project: fresco_floodlight   File: AbstractRPCChannelHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (cause instanceof ReadTimeoutException) {
        // read timeout
        logger.error("[{}->{}] Disconnecting RPC node due to read timeout",
                     getLocalNodeIdString(), getRemoteNodeIdString());
        ctx.channel().close();
    } else if (cause instanceof HandshakeTimeoutException) {
        // read timeout
        logger.error("[{}->{}] Disconnecting RPC node due to " +
                "handshake timeout",
                getLocalNodeIdString(), getRemoteNodeIdString());
        ctx.channel().close();
    } else if (cause instanceof ConnectException ||
    		cause instanceof IOException) {
        logger.debug("[{}->{}] {}: {}", 
                     new Object[] {getLocalNodeIdString(),
                                   getRemoteNodeIdString(), 
                                   cause.getClass().getName(),
                                   cause.getMessage()});
    } else {
        logger.error("[{}->{}] An error occurred on RPC channel",
                     new Object[]{getLocalNodeIdString(), 
                                  getRemoteNodeIdString(),
                                  cause});
        ctx.channel().close();
    }
}
 
Example 58
Project: lams   File: BurlapClientInterceptor.java   Source Code and License 5 votes vote down vote up
/**
 * Convert the given Burlap access exception to an appropriate
 * Spring RemoteAccessException.
 * @param ex the exception to convert
 * @return the RemoteAccessException to throw
 */
protected RemoteAccessException convertBurlapAccessException(Throwable ex) {
	if (ex instanceof ConnectException) {
		return new RemoteConnectFailureException(
				"Cannot connect to Burlap remote service at [" + getServiceUrl() + "]", ex);
	}
	else {
		return new RemoteAccessException(
			"Cannot access Burlap remote service at [" + getServiceUrl() + "]", ex);
	}
}
 
Example 59
Project: private-WeChat   File: CommonUtil.java   Source Code and License 5 votes vote down vote up
/**
     * 发起https请求并获取结果
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new SaicX509TrustManager() };
//          SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("connection timed out cause by " + ce.getMessage());
        } catch (Exception e) {
            logger.error("https request error : " + e.getMessage());
        }
        return jsonObject;
    }
 
Example 60
Project: private-WeChat   File: CommonUtil.java   Source Code and License 5 votes vote down vote up
/**
     * 发起https请求并获取结果
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new SaicX509TrustManager() };
//          SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("connection timed out cause by " + ce.getMessage());
        } catch (Exception e) {
            logger.error("https request error : " + e.getMessage());
        }
        return jsonObject;
    }