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 testNoConnectionToDatabase() throws Exception {
    RouteBuilder rb = new RouteBuilder() {
        @Override//  w  w  w. j av  a 2s . com
        public void configure() throws Exception {
            interceptSendToEndpoint("jdbc:*").skipSendToOriginalEndpoint()
                    .throwException(new ConnectException("Cannot connect to the database"));
        }
    };

    // 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
    // AMQ will out of the box try to redeliver the message up till 6 times, and then move the message to its DLQ
    Thread.sleep(15000);

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

    // now check that the message was moved to the DLQ
    String dlq = consumer.receiveBody("activemq:queue:ActiveMQ.DLQ", 1000L, String.class);
    assertNotNull("Message should have been moved to the ActiveMQ DLQ", dlq);
}

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

static OCSPResp fetchResponse(X509Certificate subject, X509Certificate issuer, PrivateKey signerKey,
        X509Certificate signer, String signAlgoId) throws Exception {
    List<String> responderURIs = GlobalConf.getOcspResponderAddresses(subject);

    log.trace("responder URIs: {}", responderURIs);

    if (responderURIs.isEmpty()) {
        throw new ConnectException("No OCSP responder URIs available");
    }//from   ww  w . j ava  2s. c  om

    for (String responderURI : responderURIs) {
        try {
            log.trace("fetch response from: {}", responderURI);

            return fetchResponse(responderURI, subject, issuer, signerKey, signer, signAlgoId);
        } catch (Exception e) {
            log.error("Unable to fetch response from responder at {}", responderURI, e);
        }
    }

    throw new OCSPException("Unable to get valid OCSP response from any responders");
}

From source file:org.mule.transport.telnet.TelnetClientWrapper.java

public TelnetClientWrapper(String host, int port, TelnetMessageDispatcher dispatcher, int waitTime)
        throws IOException {

    TelnetClient client = new TelnetClient();

    TelnetOptionHandler handler = new EchoOptionHandler(true, true, true, true);
    try {//from w  w  w  . ja va 2  s  . c o  m
        client.addOptionHandler(handler);
    } catch (InvalidTelnetOptionException e) {
        dispatcher.exceptionThrown(e);
    }
    //TODO enable LINEMODE

    client.connect(host, port);

    if (!client.isConnected()) {
        throw new ConnectException("cannot connect : " + host + ":" + port);
    }

    setWaitTime(waitTime);
    this.responseTimeout = dispatcher.getEndpoint().getResponseTimeout();

    this.client = client;
    this.dispatcher = dispatcher;
    this.encoding = dispatcher.getEndpoint().getEncoding();
    exitStatusCommand = dispatcher.getConnector().getExitStatusCommand();

    reader = new BufferedInputStream(client.getInputStream(), 1024);

    writer = new BufferedOutputStream(client.getOutputStream(), 1024);
    client.setSoTimeout(responseTimeout + waitTime);
    client.setReaderThread(true);

    if (logger.isTraceEnabled())
        logger.trace(BeanUtils.describe(this));
}

From source file:org.apache.solr.client.solrj.impl.CloudSolrClientCacheTest.java

public void testCaching() throws Exception {
    String collName = "gettingstarted";
    Set<String> livenodes = new HashSet<>();
    Map<String, ClusterState.CollectionRef> refs = new HashMap<>();
    Map<String, DocCollection> colls = new HashMap<>();

    class Ref extends ClusterState.CollectionRef {
        private String c;

        public Ref(String c) {
            super(null);
            this.c = c;
        }//from w  ww .j  a v  a2 s  . c  o  m

        @Override
        public boolean isLazilyLoaded() {
            return true;
        }

        @Override
        public DocCollection get() {
            gets.incrementAndGet();
            return colls.get(c);
        }
    }
    Map<String, Function> responses = new HashMap<>();
    NamedList okResponse = new NamedList();
    okResponse.add("responseHeader", new NamedList<>(Collections.singletonMap("status", 0)));

    LBHttpSolrClient mockLbclient = getMockLbHttpSolrClient(responses);
    AtomicInteger lbhttpRequestCount = new AtomicInteger();
    try (CloudSolrClient cloudClient = new CloudSolrClientBuilder(getStateProvider(livenodes, refs))
            .withLBHttpSolrClient(mockLbclient).build()) {
        livenodes.addAll(ImmutableSet.of("192.168.1.108:7574_solr", "192.168.1.108:8983_solr"));
        ClusterState cs = ClusterState.load(1, coll1State.getBytes(UTF_8), Collections.emptySet(),
                "/collections/gettingstarted/state.json");
        refs.put(collName, new Ref(collName));
        colls.put(collName, cs.getCollectionOrNull(collName));
        responses.put("request", o -> {
            int i = lbhttpRequestCount.incrementAndGet();
            if (i == 1)
                return new ConnectException("TEST");
            if (i == 2)
                return new SocketException("TEST");
            if (i == 3)
                return new NoHttpResponseException("TEST");
            return okResponse;
        });
        UpdateRequest update = new UpdateRequest().add("id", "123", "desc", "Something 0");

        cloudClient.request(update, collName);
        assertEquals(2, refs.get(collName).getCount());
    }

}

From source file:net.sf.jooreports.openoffice.connection.AbstractOpenOfficeConnection.java

public synchronized void connect() throws ConnectException {
    logger.debug("connecting");
    try {/*from   w ww  . j av  a2 s  .  c o m*/
        XComponentContext localContext = Bootstrap.createInitialComponentContext(null);
        XMultiComponentFactory localServiceManager = localContext.getServiceManager();
        XConnector connector = (XConnector) UnoRuntime.queryInterface(XConnector.class, localServiceManager
                .createInstanceWithContext("com.sun.star.connection.Connector", localContext));
        XConnection connection = connector.connect(connectionString);
        XBridgeFactory bridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(XBridgeFactory.class,
                localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory",
                        localContext));
        XBridge bridge = bridgeFactory.createBridge("", "urp", connection, null);
        bridgeComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, bridge);
        bridgeComponent.addEventListener(this);
        serviceManager = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class,
                bridge.getInstance("StarOffice.ServiceManager"));
        XPropertySet properties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, serviceManager);
        componentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class,
                properties.getPropertyValue("DefaultContext"));
        connected = true;
        logger.info("connected");
    } catch (NoConnectException connectException) {
        throw new ConnectException(
                "connection failed: " + connectionString + ": " + connectException.getMessage());
    } catch (Exception exception) {
        throw new OpenOfficeException("connection failed: " + connectionString, exception);
    }
}

From source file:com.slidespeech.server.converter.openoffice.AbstractOpenOfficeConnection.java

public synchronized void connect() throws ConnectException, OpenOfficeException {
    logger.debug("connecting");
    try {/*w w  w. ja v a 2  s  . c  o m*/
        XComponentContext localContext = Bootstrap.createInitialComponentContext(null);
        XMultiComponentFactory localServiceManager = localContext.getServiceManager();
        XConnector connector = (XConnector) UnoRuntime.queryInterface(XConnector.class, localServiceManager
                .createInstanceWithContext("com.sun.star.connection.Connector", localContext));
        XConnection connection = connector.connect(connectionString);
        XBridgeFactory bridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(XBridgeFactory.class,
                localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory",
                        localContext));
        bridge = bridgeFactory.createBridge("", "urp", connection, null);
        bridgeComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, bridge);
        bridgeComponent.addEventListener(this);
        serviceManager = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class,
                bridge.getInstance("StarOffice.ServiceManager"));
        XPropertySet properties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, serviceManager);
        componentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class,
                properties.getPropertyValue("DefaultContext"));
        connected = true;
        logger.info("connected");
    } catch (NoConnectException connectException) {
        throw new ConnectException(
                "connection failed: " + connectionString + ": " + connectException.getMessage());
    } catch (Exception exception) {
        throw new OpenOfficeException("connection failed: " + connectionString, exception);
    }
}

From source file:org.eclipse.jubula.client.internal.impl.AUTImpl.java

/** {@inheritDoc} */
public void connect() throws CommunicationException {
    if (!isConnected()) {
        final Map<ComponentClass, String> typeMapping = getInformation().getTypeMapping();
        try {//from   w  w w  . j  a v a  2  s . co  m
            m_instance = AUTConnection.getInstance();
            m_instance.connectToAut(m_autID, typeMapping);
            if (!isConnected()) {
                throw new CommunicationException(new ConnectException("Could not connect to AUT: " //$NON-NLS-1$
                        + m_autID.getID() + ".")); //$NON-NLS-1$
            }
        } catch (ConnectionException e) {
            log.error(e.getLocalizedMessage(), e);
            throw new CommunicationException(e);
        }
    } else {
        throw new IllegalStateException("AUT connection is already made"); //$NON-NLS-1$
    }
}

From source file:org.jboss.wise.core.client.impl.wsdlResolver.Connection.java

InputStream getInputStream(HttpURLConnection conn) throws WiseRuntimeException {
    try {//ww  w  .  j a v a2 s  .c om
        InputStream is = null;
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
        } else {

            throw new ConnectException("Remote server's response is an error: " + conn.getResponseCode());
        }
        return is;
    } catch (Exception e) {
        throw new WiseRuntimeException(e);
    }
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.LDAPUserManager.java

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#validateUserAccount(java.lang.String, java.lang.String)
 */// w ww  .  j av  a  2s. c  o  m
public synchronized boolean validateUserAccount(final String userId, final String userGuid)
        throws UserManagementException {
    final String methodName = LDAPUserManager.CNAME
            + "#validateUserAccount(final String userID, final String userGuid) throws UserManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("userId: {}", userId);
        DEBUGGER.debug("userGuid: {}", userGuid);
    }

    boolean isValid = false;
    LDAPConnection ldapConn = null;
    LDAPConnectionPool ldapPool = null;

    try {
        ldapPool = (LDAPConnectionPool) svcBean.getAuthDataSource();

        if (DEBUG) {
            DEBUGGER.debug("LDAPConnectionPool: {}", ldapPool);
        }

        if (ldapPool.isClosed()) {
            throw new ConnectException("Failed to create LDAP connection using the specified information");
        }

        ldapConn = ldapPool.getConnection();

        if (DEBUG) {
            DEBUGGER.debug("LDAPConnection: {}", ldapConn);
        }

        if (!(ldapConn.isConnected())) {
            throw new ConnectException("Failed to create LDAP connection using the specified information");
        }

        Filter searchFilter = Filter.create("(&(objectClass=" + repoConfig.getBaseObject() + ")" + "(|(cn="
                + userGuid + ")" + "(uid=" + userId + ")))");

        if (DEBUG) {
            DEBUGGER.debug("Filter: {}", searchFilter);
        }

        SearchRequest searchRequest = new SearchRequest(repoConfig.getRepositoryBaseDN(), SearchScope.SUB,
                searchFilter, "cn");

        if (DEBUG) {
            DEBUGGER.debug("SearchRequest: {}", searchRequest);
        }

        SearchResult searchResult = ldapConn.search(searchRequest);

        if (DEBUG) {
            DEBUGGER.debug("searchResult: {}", searchResult);
        }

        if ((searchResult.getResultCode() != ResultCode.SUCCESS) || (searchResult.getEntryCount() == 0)) {
            return true;
        }
    } catch (LDAPException lx) {
        throw new UserManagementException(lx.getMessage(), lx);
    } catch (ConnectException cx) {
        throw new UserManagementException(cx.getMessage(), cx);
    } finally {
        if ((ldapPool != null) && ((ldapConn != null) && (ldapConn.isConnected()))) {
            ldapConn.close();
            ldapPool.releaseConnection(ldapConn);
        }
    }

    return isValid;
}

From source file:org.kawanfw.sql.api.server.web.WebServerApi.java

/**
 * Starts the embedded Web Server./*w ww. ja  v a  2 s  .com*/
 * 
 * @param host
 *            the host of the Web Server
 * @param port
 *            the port of the Web Server
 * @param propertiesFile
 *            properties file to use for configuration of the Web Server
 * 
 * @throws ConnectException
 *             if the port is not available
 * @throws IOException
 *             if an IOException occurs
 * @throws SqlConfigurationException
 *             if there is a configuration error, either in Configurators or
 *             in the <code>server-sql.properties</code> file
 * @throws LifecycleException
 *             thrown by the embedded Tomcat engine for any lifecycle
 *             related problem
 */
public void startServer(String host, int port, File propertiesFile)
        throws ConnectException, IOException, SqlConfigurationException, LifecycleException {

    debug("propertiesFiles: " + propertiesFile);

    if (host == null) {
        throw new SqlConfigurationException("host parameter can not be null.");
    }

    if (port <= 0) {
        throw new SqlConfigurationException("port parameter can not be null.");
    }

    if (propertiesFile == null) {
        throw new SqlConfigurationException("propertiesFile parameter can not be null.");
    }

    if (!propertiesFile.exists()) {
        throw new SqlConfigurationException(
                "The properties file " + propertiesFile + " does not exists. " + SqlTag.PLEASE_CORRECT);
    }

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

    PortSemaphoreFile portSemaphoreFile = new PortSemaphoreFile(port);

    try {
        if (!portSemaphoreFile.exists()) {
            portSemaphoreFile.create();
        }
    } catch (IOException e) {
        throw new IOException(
                "Web server can not start. Impossible to create the semaphore file: "
                        + portSemaphoreFile.getSemaphoreFile() + CR_LF
                        + "Create manually the semapahore file to start the Web server on port " + port + ".",
                e);
    }

    // Do not use SecureRandom class
    if (SystemUtils.IS_OS_UNIX) {
        System.setProperty("java.security.egd", "file:/dev/./urandom");
        debug("java.security.egd: " + System.getProperty("java.security.egd"));
    }

    // OK build the Servlet
    TomcatStarter tomcatStarter = new TomcatStarter(host, port, propertiesFile);

    tomcatStarter.start();

}