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:com.meidusa.venus.io.network.VenusBIOConnectionFactory.java

public VenusBIOConnection makeObject() throws Exception {
    Socket socket = new Socket();
    InetSocketAddress address = null;
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {//from  w ww .  j a va2 s.c  o  m
        address = new InetSocketAddress(host, port);
    }

    socket.setSendBufferSize(sendBufferSize * 1024);
    socket.setReceiveBufferSize(receiveBufferSize * 1024);
    socket.setTcpNoDelay(tcpNoDelay);
    socket.setKeepAlive(keepAlive);
    try {
        if (soTimeout > 0) {
            socket.setSoTimeout(soTimeout);
        }
        if (coTimeout > 0) {
            socket.connect(address, coTimeout);
        } else {
            socket.connect(address);
        }
    } catch (ConnectException e) {
        throw new ConnectException(e.getMessage() + " " + address.getHostName() + ":" + address.getPort());
    }

    VenusBIOConnection conn = new VenusBIOConnection(socket, TimeUtil.currentTimeMillis());
    byte[] bts = conn.read();
    HandshakePacket handshakePacket = new HandshakePacket();
    handshakePacket.init(bts);

    AuthenPacket authen = getAuthenticator().createAuthenPacket(handshakePacket);
    conn.write(authen.toByteArray());
    bts = conn.read();
    int type = AbstractServicePacket.getType(bts);
    if (type == PacketConstant.PACKET_TYPE_OK) {
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " success");
        }
    } else if (type == PacketConstant.PACKET_TYPE_ERROR) {
        ErrorPacket error = new ErrorPacket();
        error.init(bts);
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " error={code="
                    + error.errorCode + ",message=" + error.message + "}");
        }
        throw new AuthenticationException(error.message, error.errorCode);
    }

    return conn;
}

From source file:ddf.common.test.cometd.CometDClient.java

/**
 * Starts the client./* w  w  w .jav  a 2s  .c om*/
 *
 * @throws Exception thrown if the client fails to start
 */
public void start() throws Exception {
    httpClient.start();
    LOGGER.debug("HTTP client started: {}", httpClient.isStarted());
    MessageListener handshakeListener = new MessageListener(Channel.META_HANDSHAKE);
    bayeuxClient.getChannel(Channel.META_HANDSHAKE).addListener(handshakeListener);
    bayeuxClient.handshake();
    boolean connected = bayeuxClient.waitFor(TIMEOUT, BayeuxClient.State.CONNECTED);
    if (!connected) {
        shutdownHttpClient();
        String message = String.format("%s failed to connect to the server at %s", this.getClass().getName(),
                bayeuxClient.getURL());
        LOGGER.error(message);
        throw new ConnectException(message);
    }
}

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

/** {@inheritDoc} */
public void connect() throws CommunicationException {
    if (!isConnected()) {
        try {//from w  ww. j  a  v  a2s  .  co m
            AutAgentConnection.createInstance(m_hostname, m_port);
            m_agent = AutAgentConnection.getInstance();
            m_agent.getCommunicator().addCommunicationErrorListener(new ErrorListener(Thread.currentThread()));
            m_agent.run();
            if (!isConnected()) {
                throw new CommunicationException(new ConnectException("Could not connect to AUT-Agent: " //$NON-NLS-1$
                        + m_hostname + ":" + m_port)); //$NON-NLS-1$
            }
        } catch (ConnectionException e) {
            throw new CommunicationException(e);
        } catch (AlreadyConnectedException e) {
            throw new CommunicationException(e);
        } catch (JBVersionException e) {
            log.error(e.getLocalizedMessage(), e);
            throw new CommunicationException(e);
        }
    } else {
        throw new IllegalStateException("AUT-Agent connection is already made"); //$NON-NLS-1$
    }
}

From source file:ch.cyberduck.core.proxy.ProxySocketFactory.java

private IOException failure(final String target, final IllegalArgumentException e) {
    final Proxy proxy = proxyFinder.find(new Host(protocol, target));
    return new ConnectException(String.format("Unsupported proxy type %s", proxy.getType()));
}

From source file:com.alibaba.wasp.ipc.WaspRPC.java

/**
 * @param protocol/*from   www  .j  av a2 s  .  c  o  m*/
 *          protocol interface
 * @param clientVersion
 *          which client version we expect
 * @param addr
 *          address of remote service
 * @param conf
 *          configuration
 * @param maxAttempts
 *          max attempts
 * @param rpcTimeout
 *          timeout for each RPC
 * @param timeout
 *          timeout in milliseconds
 * @return proxy
 * @throws java.io.IOException
 *           e
 */
@SuppressWarnings("unchecked")
public static VersionedProtocol waitForProxy(Class protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int maxAttempts, int rpcTimeout, long timeout) throws IOException {
    long startTime = System.currentTimeMillis();
    IOException ioe;
    int reconnectAttempts = 0;
    while (true) {
        try {
            return getProxy(protocol, clientVersion, addr, conf, rpcTimeout);
        } catch (SocketTimeoutException te) { // namenode is busy
            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:org.codice.ddf.itests.common.cometd.CometDClient.java

/**
 * Starts the client.//from  w w  w. j a v  a2  s .co  m
 *
 * @throws Exception thrown if the client fails to start
 */
public void start() throws Exception {
    httpClient.start();
    LOGGER.debug("HTTP client started: {}", httpClient.isStarted());
    MessageListener handshakeListener = new MessageListener(Channel.META_HANDSHAKE);
    bayeuxClient.getChannel(Channel.META_HANDSHAKE).addListener(handshakeListener);
    bayeuxClient.handshake();
    boolean connected = bayeuxClient.waitFor(TIMEOUT, BayeuxClient.State.CONNECTED);
    if (!connected) {
        shutdownHttpClient();
        String message = String.format("%s failed to connect to the server at %s", this.getClass().getName(),
                bayeuxClient.getURL());
        LOGGER.error(message);
        throw new ConnectException(message);
    }

}

From source file:com.android.mms.service.http.NetworkAwareClientConnectionOperator.java

/**
 * This method is mostly copied from the overridden one in parent. The only change
 * is how we resolve host name./*from  w w  w.  j  a v  a 2s  . c  om*/
 */
@Override
public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local,
        HttpContext context, HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection must not be null.");
    }
    if (target == null) {
        throw new IllegalArgumentException("Target host must not be null.");
    }
    // local address may be null
    //@@@ is context allowed to be null?
    if (params == null) {
        throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (conn.isOpen()) {
        throw new IllegalArgumentException("Connection must not be open.");
    }

    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    final SocketFactory sf = schm.getSocketFactory();
    final SocketFactory plain_sf;
    final LayeredSocketFactory layered_sf;
    if (sf instanceof LayeredSocketFactory) {
        plain_sf = staticPlainSocketFactory;
        layered_sf = (LayeredSocketFactory) sf;
    } else {
        plain_sf = sf;
        layered_sf = null;
    }
    // CHANGE FOR MmsService
    ArrayList<InetAddress> addresses = resolveHostName(target.getHostName());

    for (int i = 0; i < addresses.size(); ++i) {
        Log.d(TAG, "NetworkAwareClientConnectionOperator: connecting " + addresses.get(i));
        Socket sock = plain_sf.createSocket();
        conn.opening(sock, target);

        try {
            Socket connsock = plain_sf.connectSocket(sock, addresses.get(i).getHostAddress(),
                    schm.resolvePort(target.getPort()), local, 0, params);
            if (sock != connsock) {
                sock = connsock;
                conn.opening(sock, target);
            }
            /*
             * prepareSocket is called on the just connected
             * socket before the creation of the layered socket to
             * ensure that desired socket options such as
             * TCP_NODELAY, SO_RCVTIMEO, SO_LINGER will be set
             * before any I/O is performed on the socket. This
             * happens in the common case as
             * SSLSocketFactory.createSocket performs hostname
             * verification which requires that SSL handshaking be
             * performed.
             */
            prepareSocket(sock, context, params);
            if (layered_sf != null) {
                Socket layeredsock = layered_sf.createSocket(sock, target.getHostName(),
                        schm.resolvePort(target.getPort()), true);
                if (layeredsock != sock) {
                    conn.opening(layeredsock, target);
                }
                conn.openCompleted(sf.isSecure(layeredsock), params);
            } else {
                conn.openCompleted(sf.isSecure(sock), params);
            }
            break;
            // BEGIN android-changed
            //       catch SocketException to cover any kind of connect failure
        } catch (SocketException ex) {
            if (i == addresses.size() - 1) {
                ConnectException cause = ex instanceof ConnectException ? (ConnectException) ex
                        : (ConnectException) new ConnectException(ex.getMessage()).initCause(ex);
                throw new HttpHostConnectException(target, cause);
            }
            // END android-changed
        } catch (ConnectTimeoutException ex) {
            if (i == addresses.size() - 1) {
                throw ex;
            }
        }
    }
}

From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java

public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException {
    final String methodName = IServiceCheckProcessor.CNAME
            + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException";

    if (DEBUG) {//from w  ww.j  ava 2s .co  m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServiceCheckRequest: {}", request);
    }

    int exitCode = -1;
    Socket socket = null;
    File sourceFile = null;
    CommandLine command = null;
    BufferedWriter writer = null;
    ExecuteStreamHandler streamHandler = null;
    ByteArrayOutputStream outputStream = null;
    ServiceCheckResponse response = new ServiceCheckResponse();

    final DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        switch (request.getRequestType()) {
        case NETSTAT:
            sourceFile = scriptConfig.getScripts().get("netstat");

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

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

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

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

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

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        case REMOTEDATE:
            response.setRequestStatus(AgentStatus.SUCCESS);
            response.setResponseData(System.currentTimeMillis());

            break;
        case TELNET:
            response = new ServiceCheckResponse();

            int targetPort = request.getPortNumber();
            String targetServer = request.getTargetHost();

            if (DEBUG) {
                DEBUGGER.debug("Target port: {}", targetPort);
                DEBUGGER.debug("Target server: {}", targetServer);
            }

            if (targetPort == 0) {
                throw new ServiceCheckException("Target port number was not assigned. Cannot action request.");
            }

            final String CRLF = "\r\n";
            final String TERMINATE_TELNET = "^]";

            synchronized (new Object()) {
                InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort);

                socket = new Socket();
                socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT);
                socket.setSoLinger(false, 0);
                socket.setKeepAlive(false);

                try {
                    socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT);

                    if (!(socket.isConnected())) {
                        throw new ConnectException("Failed to connect to host " + targetServer + " on port "
                                + request.getPortNumber());
                    }

                    PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);
                    pWriter.println(TERMINATE_TELNET + CRLF);
                    pWriter.flush();
                    pWriter.close();

                    response.setRequestStatus(AgentStatus.SUCCESS);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " successful.");
                } catch (ConnectException cx) {
                    response.setRequestStatus(AgentStatus.FAILURE);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " failed with message: " + cx.getMessage());
                }
            }

            break;
        case PROCESSLIST:
            sourceFile = scriptConfig.getScripts().get("processList");

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

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

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

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

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

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        default:
            // unknown operation
            throw new ServiceCheckException("No valid operation was specified");
        }
    } catch (UnknownHostException uhx) {
        ERROR_RECORDER.error(uhx.getMessage(), uhx);

        throw new ServiceCheckException(uhx.getMessage(), uhx);
    } catch (SocketException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new ServiceCheckException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ServiceCheckException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ServiceCheckException(ix.getMessage(), ix);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }

            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:edu.si.services.beans.cameratrap.UCT_DeleteCacheDirOnFailTest.java

@Test
public void testConnectException() throws Exception {
    expectedFileExists = processErrorDirPath + "/" + deploymentZip.getName();

    MockEndpoint mockError = getMockEndpoint("mock:error");
    mockError.expectedMessageCount(1);// w w  w. j  a  v a  2s . c  om
    mockError.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(ConnectException.class);
    mockError.expectedHeaderReceived("redeliveryCount", getExtra().getProperty("min.connectEx.redeliveries"));
    mockError.expectedFileExists(expectedFileExists);
    mockError.setAssertPeriod(7000);

    context.getRouteDefinition("UnifiedCameraTrapProcessParents").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override
                public void configure() throws Exception {
                    weaveByType(SetBodyDefinition.class).selectFirst().before().to("mock:result");
                    weaveById("logConnectException").after().to("mock:error");
                }
            });

    context.getRouteDefinition("UnifiedCameraTrapFindObjectByPIDPredicate").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override
                public void configure() throws Exception {
                    weaveByType(ToDynamicDefinition.class).selectFirst().replace().process(new Processor() {
                        @Override
                        public void process(Exchange exchange) throws Exception {
                            Message in = exchange.getIn();
                            in.setHeader("redeliveryCount",
                                    in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class));
                            throw new ConnectException("Simulating Connection Exception");
                        }
                    });

                }
            });

    runTest();
}

From source file:com.hortonworks.hbase.replication.bridge.HBaseRPC.java

/**
 * @param protocol protocol interface/*from   w w w.j a  va  2  s .co  m*/
 * @param clientVersion which client version we expect
 * @param addr address of remote service
 * @param conf configuration
 * @param maxAttempts max attempts
 * @param rpcTimeout timeout for each RPC
 * @param timeout timeout in milliseconds
 * @return proxy
 * @throws IOException e
 */
@SuppressWarnings("unchecked")
public static <T extends VersionedProtocol> T waitForProxy(RpcEngine rpcClient, Class<T> protocol,
        long clientVersion, 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 rpcClient.getProxy(protocol, clientVersion, addr, conf, rpcTimeout);
        } catch (SocketTimeoutException te) { // namenode is busy
            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
        }
    }
}