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:camelinaction.RiderAutoPartsPartnerTXTest.java

@Test
public void testFailFirstTime() throws Exception {
    RouteBuilder rb = new RouteBuilder() {
        @Override/*w  w  w .j  a v  a 2 s  .c o m*/
        public void configure() throws Exception {
            interceptSendToEndpoint("jdbc:*").to("log:intercepted?showAll=true").choice()
                    .when(header("JMSRedelivered").isEqualTo("false"))
                    .throwException(new ConnectException("Cannot connect to the database")).end();
        }
    };

    // adviseWith enhances our route by adding the interceptor from the route builder
    // this allows us here directly in the unit test to add interceptors so we can simulate the connection failure
    context.getRouteDefinition("partnerToDB").adviceWith(context, rb);

    // there should be 0 row in the database when we start
    assertEquals(0, jdbc.queryForInt("select count(*) from partner_metric"));

    String xml = "<?xml version=\"1.0\"?><partner id=\"123\"><date>200911150815</date><code>200</code><time>4387</time></partner>";
    template.sendBody("activemq:queue:partners", xml);

    // wait for the route to complete
    Thread.sleep(5000);

    // data is inserted so there should be 1 rows
    assertEquals(1, jdbc.queryForInt("select count(*) from partner_metric"));

    // now check that the message is not on the DLQ
    String dlq = consumer.receiveBody("activemq:queue:ActiveMQ.DLQ", 1000L, String.class);
    assertNull("Should not be in the ActiveMQ DLQ", dlq);
}

From source file:org.sakuli.starter.SahiConnectorTest.java

@Test
public void testStartSahiTestSuiteReconnect() throws Throwable {
    TestRunner testRunnerMock = mock(TestRunner.class);
    doReturn(testRunnerMock).when(testling).getTestRunner();
    when(testRunnerMock.execute()).thenThrow(new ConnectException("TEST"));
    doNothing().when(testling).reconnect(any(Exception.class));
    doReturn(SAKULI_HOME_FOLDER_PATH).when(testling).getIncludeFolderJsPath();

    testling.startSahiTestSuite();// w w w  .j av a 2s .c  om
    verify(testRunnerMock).addReport(any(Report.class));
    verify(testRunnerMock).setInitJS(anyString());
    verify(sakuliExceptionHandler, never()).handleException(any(SakuliInitException.class));
    verify(sahiProxy).shutdown();
    verify(testling).reconnect(any(Exception.class));
}

From source file:uk.trainwatch.io.ftp.DefaultFTPClient.java

@Override
public void connect() throws IOException {
    if (ftp.isConnected()) {
        return;/*from  w  w  w.  ja  v  a2s . co m*/
    }

    debug(() -> "Connecting...");

    connect.accept(this);

    // After connection attempt, you should check the reply code to verifysuccess.
    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        debug(() -> "Connected");
    } else {
        debug(() -> "Connection refused");
        throw new ConnectException("Connection refused");
    }
}

From source file:org.apache.hadoop.hbase.ipc.HBaseClientRPC.java

/**
 * @param protocol      protocol interface
 * @param addr          address of remote service
 * @param conf          configuration/*from   w  w  w .  ja v a 2s . c o m*/
 * @param maxAttempts   max attempts
 * @param rpcTimeout    timeout for each RPC
 * @param timeout       timeout in milliseconds
 * @return proxy
 * @throws java.io.IOException e
 */
public static IpcProtocol waitForProxy(Class<? extends IpcProtocol> protocol, InetSocketAddress addr,
        Configuration conf, int maxAttempts, int rpcTimeout, long timeout) throws IOException {
    // HBase does limited number of reconnects which is different from hadoop.
    long startTime = System.currentTimeMillis();
    IOException ioe;
    int reconnectAttempts = 0;
    while (true) {
        try {
            return getProxy(protocol, addr, conf, rpcTimeout);
        } catch (SocketTimeoutException te) {
            LOG.info("Problem connecting to server: " + addr);
            ioe = te;
        } catch (IOException ioex) {
            // We only handle the ConnectException.
            ConnectException ce = null;
            if (ioex instanceof ConnectException) {
                ce = (ConnectException) ioex;
                ioe = ce;
            } else if (ioex.getCause() != null && ioex.getCause() instanceof ConnectException) {
                ce = (ConnectException) ioex.getCause();
                ioe = ce;
            } else if (ioex.getMessage().toLowerCase().contains("connection refused")) {
                ce = new ConnectException(ioex.getMessage());
                ioe = ce;
            } else {
                // This is the exception we can't handle.
                ioe = ioex;
            }
            if (ce != null) {
                handleConnectionException(++reconnectAttempts, maxAttempts, protocol, addr, ce);
            }
        }
        // check if timed out
        if (System.currentTimeMillis() - timeout >= startTime) {
            throw ioe;
        }

        // wait for retry
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ie) {
            // IGNORE
        }
    }
}

From source file:onl.area51.filesystem.ftp.client.DefaultFTPClient.java

@Override
public void connect(String server, int port) throws IOException {
    if (ftp.isConnected()) {
        throw new IllegalStateException("Already connected");
    }//from  w ww  .  j  a v a 2  s. c o  m

    debug(() -> "Connecting to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

    if (port > 0) {
        ftp.connect(server, port);
    } else {
        ftp.connect(server);
    }

    debug(() -> "Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

    // After connection attempt, you should check the reply code to verifysuccess.
    if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        debug(() -> "Connection refused to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        throw new ConnectException("Failed to connect to " + server);
    }
}

From source file:org.apache.phoenix.loadbalancer.service.LoadBalancer.java

private List<HostAndPort> conductSanityCheckAndReturn() throws Exception {
    Preconditions.checkNotNull(curaFramework, " curator framework in not initialized ");
    Preconditions.checkNotNull(cache, " cache value is not initialized");
    boolean connected = curaFramework.getZookeeperClient().isConnected();
    if (!connected) {
        String message = " Zookeeper seems to be down. The data is stale ";
        ConnectException exception = new ConnectException(message);
        LOG.error(message, exception);/*from w w w .j a v a 2  s. c  o  m*/
        throw exception;
    }
    List<String> currentNodes = curaFramework.getChildren().forPath(CONFIG.getParentPath());
    List<HostAndPort> returnNodes = new ArrayList<>();
    String nodeAsString = null;
    for (String node : currentNodes) {
        try {
            returnNodes.add(HostAndPort.fromString(node));
        } catch (Throwable ex) {
            LOG.error(" something wrong with node string " + nodeAsString, ex);
        }
    }
    return returnNodes;
}

From source file:org.kawanfw.sql.tomcat.TomcatConnectorsUpdater.java

/**
 * If there are some SSL Connector properties, set them on Tomcat instance
 * //ww  w  .ja  v  a  2  s .  com
 * @return the setted Connector
 */
public Connector setSslConnectorValues() throws SqlConfigurationException, ConnectException {

    String sslConnectorSSLEnabled = properties.getProperty("sslConnector.SSLEnabled");

    if (sslConnectorSSLEnabled != null) {
        sslConnectorSSLEnabled = sslConnectorSSLEnabled.trim();
    }

    Connector sslConnector = null;

    // Do we have to add an SSL Connector?
    if (sslConnectorSSLEnabled == null || !sslConnectorSSLEnabled.trim().equals("true")) {
        return sslConnector;
    }

    // Ok, set the connector properties
    sslConnector = new Connector();

    // Scheme is mandatory
    String scheme = getMandatoryPropertyValue("sslConnector.scheme");
    if (!scheme.equals("https")) {
        throw new SqlConfigurationException(
                "The property sslConnector.https value must be \"https\" in properties file. "
                        + SqlTag.PLEASE_CORRECT);
    }

    String portStr = getMandatoryPropertyValue("sslConnector.port");

    int port = -1;
    try {
        port = Integer.parseInt(portStr);
    } catch (NumberFormatException e) {
        throw new SqlConfigurationException(
                "The property sslConnector.port is not numeric: " + portStr + " in properties file.");
    }

    if (!TomcatStarterUtil.available(port)) {
        throw new ConnectException("The port for SSL " + port + " is not available for starting Web server. "
                + SqlTag.PLEASE_CORRECT);
    }

    // Testing the keystore file
    String keyStoreFileStr = getMandatoryPropertyValue("sslConnector.keystoreFile");

    File keystoreFile = new File(keyStoreFileStr);
    if (!keystoreFile.exists()) {
        throw new SqlConfigurationException(
                "The file specified by sslConnector.keystoreFile property does not exists: " + keystoreFile
                        + ". " + SqlTag.PLEASE_CORRECT);
    }

    // Testing taht keystore & keyPass password are set
    @SuppressWarnings("unused")
    String keystorePass = getMandatoryPropertyValue("sslConnector.keystorePass");
    @SuppressWarnings("unused")
    String keyPass = getMandatoryPropertyValue("sslConnector.keyPass");

    sslConnector.setScheme(scheme);
    sslConnector.setPort(port);
    sslConnector.setSecure(true);

    // Set the SSL connector
    Enumeration<?> enumeration = properties.propertyNames();

    if (enumeration.hasMoreElements()) {
        System.out.println(SqlTag.SQL_PRODUCT_START + " Setting SSL Connector attribute values:");
    }

    while (enumeration.hasMoreElements()) {
        String property = (String) enumeration.nextElement();

        if (property.startsWith("sslConnector.") && !property.equals("sslConnector.scheme")
                && !property.equals("sslConnector.port")) {

            String theValue = properties.getProperty(property);
            String tomcatProperty = StringUtils.substringAfter(property, "sslConnector.");

            if (theValue != null && !theValue.isEmpty()) {

                theValue = theValue.trim();
                sslConnector.setProperty(tomcatProperty, theValue);

                if (property.equals("sslConnector.keyPass") || property.equals("sslConnector.keystorePass")) {
                    theValue = TomcatStarter.MASKED_PASSWORD;
                }

                System.out.println(SqlTag.SQL_PRODUCT_START + "  -> " + tomcatProperty + " = " + theValue);

            }
        }
    }

    Service service = tomcat.getService();
    service.addConnector(sslConnector); // Add the connector

    return sslConnector;

}

From source file:uk.trainwatch.io.ftp.DefaultFTPClient.java

@Override
public void login() throws IOException {
    if (loggedIn) {
        return;//  w  w  w  . j  a va 2 s .  c  om
    }

    if (!login.test(this)) {
        throw new ConnectException("Login failed");
    }

    String systemType = ftp.getSystemType();
    debug(() -> "Remote system is " + systemType);

    if (binaryTransfer) {
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
    } else {
        // in theory this should not be necessary as servers should default to ASCII but they don't all do so - see NET-500
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
    }

    // Use passive mode as default because most of us are
    // behind firewalls these days.
    if (localActive) {
        ftp.enterLocalActiveMode();
    } else {
        ftp.enterLocalPassiveMode();
    }

    ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

    loggedIn = true;
}

From source file:onl.area51.filesystem.ftp.client.DefaultFTPClient.java

@Override
public void login(String username, String password) throws IOException {
    if (loggedIn) {
        throw new IllegalStateException("Already logged in");
    }/*from   www .  j  ava 2 s  .  c  o  m*/

    if (!ftp.login(username, password)) {
        throw new ConnectException("Login failed");
    }

    String systemType = ftp.getSystemType();
    debug(() -> "Remote system is " + systemType);

    if (binaryTransfer) {
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
    } else {
        // in theory this should not be necessary as servers should default to ASCII but they don't all do so - see NET-500
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
    }

    // Use passive mode as default because most of us are
    // behind firewalls these days.
    if (localActive) {
        ftp.enterLocalActiveMode();
    } else {
        ftp.enterLocalPassiveMode();
    }

    ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

    loggedIn = true;
}