Example usage for java.net ConnectException ConnectException

List of usage examples for java.net ConnectException ConnectException

Introduction

In this page you can find the example usage for java.net ConnectException ConnectException.

Prototype

public ConnectException(String msg) 

Source Link

Document

Constructs a new ConnectException with the specified detail message as to why the connect error occurred.

Usage

From source file:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * Connect to WebSocketServer with additional Header.
 * When unsubscribe is called, the observable will disconnect automatically.
 * <p>//from   w ww .j  a va 2  s.c  om
 * Caution: This method run on same thread of caller. So if you want to run on NOT UI THREAD,
 * you have to use subscribeOn to specify thread model.
 *
 * @param uri
 * @param extraHeaders
 * @return
 */
public Observable<Event> connect(Uri uri, List<Pair<String, String>> extraHeaders) {
    this.disconnect(false);

    this.mUri = uri;
    this.mExtraHeaders = extraHeaders;
    this.mParser = new HybiParser(this);

    this.mHandlerThread = new HandlerThread(getClass().getName());
    this.mHandlerThread.start();
    this.mHandler = new Handler(mHandlerThread.getLooper());

    return Observable.create(new Observable.OnSubscribe<Event>() {
        @Override
        public void call(Subscriber<? super Event> subscriber) {
            try {
                mSubscriber = subscriber;
                String secret = createSecret();
                String scheme = mUri.getScheme();

                // uri have invalid scheme throw MalformedURLException
                if (scheme == null || !(scheme.equals("ws") || scheme.equals("wss"))) {
                    new MalformedURLException("Url scheme has to be specified as \"ws\" or \"wss\".");
                }

                int port = (mUri.getPort() != -1) ? mUri.getPort() : (scheme.equals("wss") ? 443 : 80);
                String path = TextUtils.isEmpty(mUri.getPath()) ? "/" : mUri.getPath();
                if (!TextUtils.isEmpty(mUri.getQuery())) {
                    path += "?" + mUri.getQuery();
                }

                String originScheme = scheme.equals("wss") ? "https" : "http";
                Uri origin = Uri.parse(originScheme + "://" + mUri.getHost());

                SocketFactory factory = scheme.equals("wss") ? getSSLSocketFactory()
                        : SocketFactory.getDefault();
                mSocket = factory.createSocket(mUri.getHost(), port);

                PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                out.print("GET " + path + " HTTP/1.1\r\n");
                out.print("Upgrade: websocket\r\n");
                out.print("Connection: Upgrade\r\n");
                out.print("Host: " + mUri.getHost() + "\r\n");
                out.print("Origin: " + origin.toString() + "\r\n");
                out.print("Sec-WebSocket-Key: " + secret + "\r\n");
                out.print("Sec-WebSocket-Version: 13\r\n");
                if (mExtraHeaders != null) {
                    for (Pair<String, String> pair : mExtraHeaders) {
                        out.print(String.format("%s: %s\r\n", pair.first, pair.second));
                    }
                }
                out.print("\r\n");
                out.flush();

                HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                        mSocket.getInputStream());

                // Read HTTP response status line.
                StatusLine statusLine = parseStatusLine(readLine(stream));
                if (statusLine == null) {
                    throw new ConnectException("Received no reply from server.");
                } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new ProtocolException(
                            "Server sent invalid response code " + statusLine.getStatusCode()
                                    + ". WebSocket server must return " + HttpStatus.SC_SWITCHING_PROTOCOLS);
                }

                // Read HTTP response headers.
                String line;
                boolean validated = false;

                while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                        String expected = createSecretValidation(secret);
                        String actual = header.getValue().trim();

                        if (!expected.equals(actual)) {
                            throw new ProtocolException("Bad Sec-WebSocket-Accept header value.");
                        }

                        validated = true;
                    }
                }

                if (!validated) {
                    throw new ProtocolException("No Sec-WebSocket-Accept header.");
                }

                mIsConnected = true;
                emitterOnNext(new Event(EventType.CONNECT));

                // Now decode websocket frames.
                mParser.start(stream);
            } catch (Exception e) {
                emitterOnError(e);
            }
        }
    }).doOnUnsubscribe(new Action0() {
        @Override
        public void call() {
            RxWebSocketClient.this.disconnect(false);
        }
    });
}

From source file:it.geosolutions.geobatch.imagemosaic.GeoBatchBaseTest.java

protected void connectToGeoserver() throws Exception {
    LOGGER.debug("geoserver url is " + getFixture().getProperty("gs_url"));

    try {/*from  ww  w.ja  v  a  2  s . c  o  m*/
        GeoServerRESTReader reader = createGSReader();

        if (!reader.existGeoserver()) {
            LOGGER.error("GeoServer not found at " + getFixture().getProperty("gs_url"));
            throw new ConnectException("GeoServer not found at " + getFixture().getProperty("gs_url"));
        }
    } catch (MalformedURLException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        throw e;
    }
    LOGGER.debug("geoserver connection is ok");
}

From source file:org.apache.hadoop.hbase.catalog.TestCatalogTracker.java

/**
 * Test get of meta region fails properly if nothing to connect to.
 * @throws IOException//from   w w  w  . ja  v a 2  s  .  c om
 * @throws InterruptedException
 * @throws KeeperException
 * @throws ServiceException
 */
@Test
public void testVerifyMetaRegionLocationFails()
        throws IOException, InterruptedException, KeeperException, ServiceException {
    HConnection connection = Mockito.mock(HConnection.class);
    ServiceException connectException = new ServiceException(new ConnectException("Connection refused"));
    final AdminProtos.AdminService.BlockingInterface implementation = Mockito
            .mock(AdminProtos.AdminService.BlockingInterface.class);
    Mockito.when(
            implementation.getRegionInfo((RpcController) Mockito.any(), (GetRegionInfoRequest) Mockito.any()))
            .thenThrow(connectException);
    Mockito.when(connection.getAdmin(Mockito.any(ServerName.class), Mockito.anyBoolean()))
            .thenReturn(implementation);
    final CatalogTracker ct = constructAndStartCatalogTracker(connection);

    MetaRegionTracker.setMetaLocation(this.watcher,
            ServerName.valueOf("example.com", 1234, System.currentTimeMillis()));
    Assert.assertFalse(ct.verifyMetaRegionLocation(100));
}

From source file:org.apache.hadoop.hbase.TestMetaTableLocator.java

/**
 * Test get of meta region fails properly if nothing to connect to.
 * @throws IOException/*w  ww .j a v a2 s.c o m*/
 * @throws InterruptedException
 * @throws KeeperException
 * @throws ServiceException
 */
@Test
public void testVerifyMetaRegionLocationFails()
        throws IOException, InterruptedException, KeeperException, ServiceException {
    ClusterConnection connection = Mockito.mock(ClusterConnection.class);
    ServiceException connectException = new ServiceException(new ConnectException("Connection refused"));
    final AdminProtos.AdminService.BlockingInterface implementation = Mockito
            .mock(AdminProtos.AdminService.BlockingInterface.class);
    Mockito.when(
            implementation.getRegionInfo((RpcController) Mockito.any(), (GetRegionInfoRequest) Mockito.any()))
            .thenThrow(connectException);
    Mockito.when(connection.getAdmin(Mockito.any(ServerName.class))).thenReturn(implementation);

    ServerName sn = ServerName.valueOf("example.com", 1234, System.currentTimeMillis());
    MetaTableLocator.setMetaLocation(this.watcher, sn, RegionState.State.OPENING);
    assertFalse(new MetaTableLocator().verifyMetaRegionLocation(connection, watcher, 100));
    MetaTableLocator.setMetaLocation(this.watcher, sn, RegionState.State.OPEN);
    assertFalse(new MetaTableLocator().verifyMetaRegionLocation(connection, watcher, 100));
}

From source file:com.hellblazer.process.impl.JavaProcessImpl.java

@Override
public MBeanServerConnection getLocalMBeanServerConnection(String connectionName)
        throws ConnectException, NoLocalJmxConnectionException {
    JMXConnector connector = getLocalJmxConnector(connectionName);

    try {//from  w w  w.j a v a2  s .  c  o  m
        return connector.getMBeanServerConnection();
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }
}

From source file:com.evolveum.icf.dummy.resource.DummyObject.java

private void checkModifyBreak() throws ConnectException, FileNotFoundException {
    if (resource == null) {
        return;//from   w w w.  j  a v  a  2  s.c  o m
    }
    BreakMode modifyBreakMode = this.modifyBreakMode;
    if (modifyBreakMode == null) {
        modifyBreakMode = resource.getModifyBreakMode();
    }
    if (modifyBreakMode == BreakMode.NONE) {
        // go on
    } else if (modifyBreakMode == BreakMode.NETWORK) {
        throw new ConnectException("Network error (simulated error)");
    } else if (modifyBreakMode == BreakMode.IO) {
        throw new FileNotFoundException("IO error (simulated error)");
    } else if (modifyBreakMode == BreakMode.GENERIC) {
        // The connector will react with generic exception
        throw new IllegalArgumentException("Generic error (simulated error)");
    } else if (modifyBreakMode == BreakMode.RUNTIME) {
        // The connector will just pass this up
        throw new IllegalStateException("Generic error (simulated error)");
    } else if (modifyBreakMode == BreakMode.UNSUPPORTED) {
        throw new UnsupportedOperationException("Not supported (simulated error)");
    } else {
        // This is a real error. Use this strange thing to make sure it passes up
        throw new RuntimeException("Unknown schema break mode " + modifyBreakMode);
    }
}

From source file:org.apache.pig.shock.SSHSocketImplFactory.java

@Override
protected int available() throws IOException {
    if (is == null) {
        throw new ConnectException("Not connected");
    }//from  w  w w . j a  v  a 2s.c om
    return is.available();
}

From source file:com.hellblazer.process.impl.JavaProcessImpl.java

@Override
public MBeanServerConnection getLocalMBeanServerConnection(String connectionName, Subject delegationSubject)
        throws ConnectException, NoLocalJmxConnectionException {
    JMXConnector connector = getLocalJmxConnector(connectionName);

    try {/*from   w ww. j a v a2  s .  co  m*/
        return connector.getMBeanServerConnection(delegationSubject);
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }
}

From source file:windows.webservices.utilidades.EjecutorJson.java

private <T> T ejecutarJsonGeneral(Request request, Class<? extends List> colleccion, Class<? extends Map> map,
        Class<?> key, Class<T> mappe) throws IOException {

    try {/* ww w  . ja v a  2  s. c  o  m*/
        System.out.println("enlace : " + request.urlString()
                + (json != null && !json.isEmpty() ? "\n body :" + json : ""));
        Response response = client.newCall(request).execute();

        ultimoJson = response.body().string();
        if (colleccion != null) {
            return (T) mapperToList(ultimoJson, mappe);
        } else if (map != null) {
            return (T) mapperToMap(ultimoJson, map, key, mappe);
        } else {
            if (mappe.equals(String.class)) {
                return (T) ultimoJson;
            }
            return mapper.readValue(ultimoJson, mappe);
        }
    } catch (IOException ex) {
        if ((ex instanceof JsonParseException) || (ex instanceof EOFException)) {

            if ((ultimoJson.contains(EXCEPTION_REPORT)
                    || ultimoJson.contains(ERROR_REPORT) | ultimoJson.contains(INFORME_ERROR))
                    && ultimoJson.contains(MESSAGE) && ultimoJson.contains(DESCRIPTION)) {
                String title = ultimoJson.substring(ultimoJson.indexOf("<h1>") + 4,
                        ultimoJson.indexOf("</h1>"));
                String[] tags = ultimoJson.split("<p>");
                String msj = tags[2].substring(tags[2].indexOf("<u>") + 3, tags[2].indexOf("</u>"));
                String desb = tags[3].substring(tags[3].indexOf("<u>") + 3, tags[3].indexOf("</u>"));

                Logger.getLogger(EjecutorJson.class.getName()).log(Level.INFO,
                        "Titulo : {0}\nMensaje : {1}\nDescripcin : {2}", new String[] { title, msj, desb });
                throw new RuntimeException();
            }
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.WARNING,
                    "No se pudo castear el siguiente jSon : \n {0}", ultimoJson);

        } else if (ex instanceof SocketTimeoutException) {
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.WARNING,
                    "Se agoto el tiempo de respuesta");

            throw new SocketTimeoutException("Se agoto el tiempo de respuesta");
        } else if (ex instanceof ConnectException) {
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.WARNING,
                    "No se pudo conectar al servidor");
            throw new ConnectException("No se pudo conectar al servidor");

        } else {
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:org.apache.hadoop.hbase.client.TestFastFailWithoutTestUtil.java

@Test
public void testExceptionsIdentifiedByInterceptor() throws IOException {
    Throwable[] networkexceptions = new Throwable[] { new ConnectException("Mary is unwell"),
            new SocketTimeoutException("Mike is too late"), new ClosedChannelException(),
            new SyncFailedException("Dave is not on the same page"), new TimeoutException("Mike is late again"),
            new EOFException("This is the end... "), new ConnectionClosingException("Its closing") };
    final String INDUCED = "Induced";
    Throwable[] nonNetworkExceptions = new Throwable[] { new IOException("Bob died"),
            new RemoteException("Bob's cousin died", null), new NoSuchMethodError(INDUCED),
            new NullPointerException(INDUCED), new DoNotRetryIOException(INDUCED), new Error(INDUCED) };

    Configuration conf = HBaseConfiguration.create();
    long CLEANUP_TIMEOUT = 0;
    long FAST_FAIL_THRESHOLD = 1000000;
    conf.setBoolean(HConstants.HBASE_CLIENT_FAST_FAIL_MODE_ENABLED, true);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_CLEANUP_MS_DURATION_MS, CLEANUP_TIMEOUT);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_THREASHOLD_MS, FAST_FAIL_THRESHOLD);
    for (Throwable e : networkexceptions) {
        PreemptiveFastFailInterceptor interceptor = TestFastFailWithoutTestUtil
                .createPreemptiveInterceptor(conf);
        FastFailInterceptorContext context = (FastFailInterceptorContext) interceptor.createEmptyContext();

        RetryingCallable<?> callable = getDummyRetryingCallable(getSomeServerName());
        context.prepare(callable, 0);//from w  w w. jav  a  2  s  . c  o m
        interceptor.intercept(context);
        interceptor.handleFailure(context, e);
        interceptor.updateFailureInfo(context);
        assertTrue("The call shouldn't have been successful if there was a ConnectException",
                context.getCouldNotCommunicateWithServer().booleanValue());
    }
    for (Throwable e : nonNetworkExceptions) {
        try {
            PreemptiveFastFailInterceptor interceptor = TestFastFailWithoutTestUtil
                    .createPreemptiveInterceptor(conf);
            FastFailInterceptorContext context = (FastFailInterceptorContext) interceptor.createEmptyContext();

            RetryingCallable<?> callable = getDummyRetryingCallable(getSomeServerName());
            context.prepare(callable, 0);
            interceptor.intercept(context);
            interceptor.handleFailure(context, e);
            interceptor.updateFailureInfo(context);
            assertFalse("The call shouldn't have been successful if there was a ConnectException",
                    context.getCouldNotCommunicateWithServer().booleanValue());
        } catch (NoSuchMethodError t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (NullPointerException t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (DoNotRetryIOException t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        } catch (Error t) {
            assertTrue("Exception not induced", t.getMessage().contains(INDUCED));
        }
    }
}