Example usage for java.net Socket setReuseAddress

List of usage examples for java.net Socket setReuseAddress

Introduction

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

Prototype

public void setReuseAddress(boolean on) throws SocketException 

Source Link

Document

Enable/disable the SocketOptions#SO_REUSEADDR SO_REUSEADDR socket option.

Usage

From source file:com.mirth.connect.connectors.tcp.TcpReceiver.java

private void initSocket(Socket socket) throws SocketException {
    logger.debug("Initializing socket (" + connectorProperties.getName() + " \"Source\" on channel "
            + getChannelId() + ").");
    socket.setReceiveBufferSize(bufferSize);
    socket.setSendBufferSize(bufferSize);
    socket.setSoTimeout(timeout);//  w w  w. j  a  va 2 s .c om
    socket.setKeepAlive(connectorProperties.isKeepConnectionOpen());
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
}

From source file:com.delphix.session.test.ServiceTest.java

/**
 * Scan for an unused port./* w w w .  j a  va  2  s .  com*/
 */
private int portScan() {
    int localPort = (int) (Math.random() * 1000) + 62626;

    do {
        Socket socket = new Socket();

        try {
            socket.setReuseAddress(true);
            socket.bind(new InetSocketAddress(localPort));
            assertTrue(socket.isBound());
            break;
        } catch (IOException e) {
            logger.infof(e, "failed to bind to port %d - try next", localPort);
            localPort++;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                fail("failed to close socket", e);
            }
        }
    } while (localPort < 65536);

    if (localPort >= 65536) {
        fail("failed to find unused port");
    }

    logger.infof("unused local port %d found", localPort);

    return localPort;
}

From source file:com.mirth.connect.connectors.tcp.TcpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage message) {
    TcpDispatcherProperties tcpDispatcherProperties = (TcpDispatcherProperties) connectorProperties;
    Status responseStatus = Status.QUEUED;
    String responseData = null;//w  w  w. ja  v a2 s. c om
    String responseStatusMessage = null;
    String responseError = null;
    boolean validateResponse = false;

    long dispatcherId = getDispatcherId();

    String socketKey = dispatcherId + tcpDispatcherProperties.getRemoteAddress()
            + tcpDispatcherProperties.getRemotePort();
    if (tcpDispatcherProperties.isOverrideLocalBinding()) {
        socketKey += tcpDispatcherProperties.getLocalAddress() + tcpDispatcherProperties.getLocalPort();
    }

    Socket socket = null;
    Thread timeoutThread = null;

    try {
        // Do some validation first to avoid unnecessarily creating sockets
        if (StringUtils.isBlank(tcpDispatcherProperties.getRemoteAddress())) {
            throw new Exception("Remote address is blank.");
        } else if (NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()) <= 0) {
            throw new Exception("Remote port is invalid.");
        }

        socket = connectedSockets.get(socketKey);
        timeoutThread = timeoutThreads.get(socketKey);

        // If keep connection open is true, then interrupt the thread so it won't close the socket
        if (tcpDispatcherProperties.isKeepConnectionOpen() && timeoutThread != null) {
            disposeThreadQuietly(socketKey);
        }

        // Initialize a new socket if our current one is invalid, the remote side has closed, or keep connection open is false
        if (!tcpDispatcherProperties.isKeepConnectionOpen() || socket == null || socket.isClosed()
                || (tcpDispatcherProperties.isCheckRemoteHost() && socket instanceof StateAwareSocketInterface
                        && ((StateAwareSocketInterface) socket).remoteSideHasClosed())) {
            closeSocketQuietly(socketKey);

            logger.debug("Creating new socket (" + connectorProperties.getName() + " \"" + getDestinationName()
                    + "\" on channel " + getChannelId() + ").");
            String info = "Trying to connect on " + tcpDispatcherProperties.getRemoteAddress() + ":"
                    + tcpDispatcherProperties.getRemotePort() + "...";
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.CONNECTING, info));

            if (tcpDispatcherProperties.isOverrideLocalBinding()) {
                socket = SocketUtil.createSocket(configuration, tcpDispatcherProperties.getLocalAddress(),
                        NumberUtils.toInt(tcpDispatcherProperties.getLocalPort()));
            } else {
                socket = SocketUtil.createSocket(configuration);
            }

            ThreadUtils.checkInterruptedStatus();
            connectedSockets.put(socketKey, socket);

            SocketUtil.connectSocket(socket, tcpDispatcherProperties.getRemoteAddress(),
                    NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()), responseTimeout);

            socket.setReuseAddress(true);
            socket.setReceiveBufferSize(bufferSize);
            socket.setSendBufferSize(bufferSize);
            socket.setSoTimeout(responseTimeout);
            socket.setKeepAlive(tcpDispatcherProperties.isKeepConnectionOpen());

            eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.CONNECTED,
                    SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket), true));
        }

        ThreadUtils.checkInterruptedStatus();

        // Send the message
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.SENDING,
                SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket)));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), bufferSize);
        BatchStreamReader batchStreamReader = new DefaultBatchStreamReader(socket.getInputStream());
        StreamHandler streamHandler = transmissionModeProvider.getStreamHandler(socket.getInputStream(), bos,
                batchStreamReader, tcpDispatcherProperties.getTransmissionModeProperties());
        streamHandler.write(getTemplateBytes(tcpDispatcherProperties, message));
        bos.flush();

        if (!tcpDispatcherProperties.isIgnoreResponse()) {
            ThreadUtils.checkInterruptedStatus();

            // Attempt to get the response from the remote endpoint
            try {
                String info = "Waiting for response from " + SocketUtil.getInetAddress(socket) + " (Timeout: "
                        + tcpDispatcherProperties.getResponseTimeout() + " ms)... ";
                eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                        getDestinationName(), ConnectionStatusEventType.WAITING_FOR_RESPONSE, info));
                byte[] responseBytes = streamHandler.read();
                if (responseBytes != null) {
                    responseData = new String(responseBytes,
                            CharsetUtils.getEncoding(tcpDispatcherProperties.getCharsetEncoding()));
                    responseStatusMessage = "Message successfully sent.";
                } else {
                    responseStatusMessage = "Message successfully sent, but no response received.";
                }

                streamHandler.commit(true);
                responseStatus = Status.SENT;

                // We only want to validate the response if we were able to retrieve it successfully
                validateResponse = tcpDispatcherProperties.getDestinationConnectorProperties()
                        .isValidateResponse();
            } catch (IOException e) {
                // An exception occurred while retrieving the response
                if (e instanceof SocketTimeoutException
                        || e.getCause() != null && e.getCause() instanceof SocketTimeoutException) {
                    responseStatusMessage = "Timeout waiting for response";

                    if (!tcpDispatcherProperties.isQueueOnResponseTimeout()) {
                        responseStatus = Status.ERROR;
                    }
                } else {
                    responseStatusMessage = "Error receiving response";
                }

                responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                        responseStatusMessage + ": " + e.getMessage(), e);
                logger.warn(responseStatusMessage + " (" + connectorProperties.getName() + " \""
                        + getDestinationName() + "\" on channel " + getChannelId() + ").", e);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                        message.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                        connectorProperties.getName(), responseStatusMessage + ".", e));
                eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                        getDestinationName(), ConnectionStatusEventType.FAILURE,
                        responseStatusMessage + " from " + SocketUtil.getInetAddress(socket)));

                closeSocketQuietly(socketKey);
            }
        } else {
            try {
                // MIRTH-2980: Since we're ignoring responses, flush out the socket's input stream so it doesn't continually grow
                socket.getInputStream().skip(socket.getInputStream().available());
            } catch (IOException e) {
                logger.warn("Error flushing socket input stream.", e);
            }

            // We're ignoring the response, so always return a successful response
            responseStatus = Status.SENT;
            responseStatusMessage = "Message successfully sent.";
        }

        if (tcpDispatcherProperties.isKeepConnectionOpen() && (getCurrentState() == DeployedState.STARTED
                || getCurrentState() == DeployedState.STARTING)) {
            if (sendTimeout > 0) {
                // Close the connection after the send timeout has been reached
                startThread(socketKey);
            }
        } else {
            // If keep connection open is false, then close the socket right now
            closeSocketQuietly(socketKey);
        }
    } catch (Throwable t) {
        disposeThreadQuietly(socketKey);
        closeSocketQuietly(socketKey);

        String monitorMessage = "Error sending message (" + SocketUtil.getLocalAddress(socket) + " -> "
                + SocketUtil.getInetAddress(socket) + "): " + t.getMessage();
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.FAILURE, monitorMessage));

        // If an exception occurred then close the socket, even if keep connection open is true
        responseStatusMessage = t.getClass().getSimpleName() + ": " + t.getMessage();
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), t.getMessage(), t);

        String logMessage = "Error sending message via TCP (" + connectorProperties.getName() + " \""
                + getDestinationName() + "\" on channel " + getChannelId() + ").";

        if (t instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        } else if (t instanceof ConnectException
                || t.getCause() != null && t.getCause() instanceof ConnectException) {
            if (isQueueEnabled()) {
                logger.warn(logMessage, t);
            } else {
                logger.error(logMessage, t);
            }
        } else {
            logger.debug(logMessage, t);
        }

        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), message.getMessageId(),
                ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(),
                "Error sending message via TCP.", t));
    } finally {
        eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE,
                SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket),
                (Boolean) null));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

/**
 * Starts Accumulo and Zookeeper processes. Can only be called once.
 *///from  w w  w  .j  av  a2 s  .  c  o  m
@Override
public synchronized void start() throws IOException, InterruptedException {
    if (config.useMiniDFS() && miniDFS == null) {
        throw new IllegalStateException("Cannot restart mini when using miniDFS");
    }

    MiniAccumuloClusterControl control = getClusterControl();

    if (config.useExistingInstance()) {
        Configuration acuConf = config.getAccumuloConfiguration();
        Configuration hadoopConf = config.getHadoopConfiguration();

        ConfigurationCopy cc = new ConfigurationCopy(acuConf);
        VolumeManager fs;
        try {
            fs = VolumeManagerImpl.get(cc, hadoopConf);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Path instanceIdPath = Accumulo.getAccumuloInstanceIdPath(fs);

        String instanceIdFromFile = ZooUtil.getInstanceIDFromHdfs(instanceIdPath, cc, hadoopConf);
        IZooReaderWriter zrw = new ZooReaderWriterFactory().getZooReaderWriter(
                cc.get(Property.INSTANCE_ZK_HOST), (int) cc.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT),
                cc.get(Property.INSTANCE_SECRET));

        String rootPath = ZooUtil.getRoot(instanceIdFromFile);

        String instanceName = null;
        try {
            for (String name : zrw.getChildren(Constants.ZROOT + Constants.ZINSTANCES)) {
                String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name;
                byte[] bytes = zrw.getData(instanceNamePath, new Stat());
                String iid = new String(bytes, UTF_8);
                if (iid.equals(instanceIdFromFile)) {
                    instanceName = name;
                }
            }
        } catch (KeeperException e) {
            throw new RuntimeException("Unable to read instance name from zookeeper.", e);
        }
        if (instanceName == null)
            throw new RuntimeException("Unable to read instance name from zookeeper.");

        config.setInstanceName(instanceName);
        if (!AccumuloStatus.isAccumuloOffline(zrw, rootPath))
            throw new RuntimeException("The Accumulo instance being used is already running. Aborting.");
    } else {
        if (!initialized) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        MiniAccumuloClusterImpl.this.stop();
                    } catch (IOException e) {
                        log.error("IOException while attempting to stop the MiniAccumuloCluster.", e);
                    } catch (InterruptedException e) {
                        log.error("The stopping of MiniAccumuloCluster was interrupted.", e);
                    }
                }
            });
        }

        if (!config.useExistingZooKeepers())
            control.start(ServerType.ZOOKEEPER);

        if (!initialized) {
            if (!config.useExistingZooKeepers()) {
                // sleep a little bit to let zookeeper come up before calling init, seems to work better
                long startTime = System.currentTimeMillis();
                while (true) {
                    Socket s = null;
                    try {
                        s = new Socket("localhost", config.getZooKeeperPort());
                        s.setReuseAddress(true);
                        s.getOutputStream().write("ruok\n".getBytes());
                        s.getOutputStream().flush();
                        byte buffer[] = new byte[100];
                        int n = s.getInputStream().read(buffer);
                        if (n >= 4 && new String(buffer, 0, 4).equals("imok"))
                            break;
                    } catch (Exception e) {
                        if (System.currentTimeMillis() - startTime >= config.getZooKeeperStartupTime()) {
                            throw new ZooKeeperBindException("Zookeeper did not start within "
                                    + (config.getZooKeeperStartupTime() / 1000) + " seconds. Check the logs in "
                                    + config.getLogDir() + " for errors.  Last exception: " + e);
                        }
                        // Don't spin absurdly fast
                        Thread.sleep(250);
                    } finally {
                        if (s != null)
                            s.close();
                    }
                }
            }

            LinkedList<String> args = new LinkedList<>();
            args.add("--instance-name");
            args.add(config.getInstanceName());
            args.add("--user");
            args.add(config.getRootUserName());
            args.add("--clear-instance-name");

            // If we aren't using SASL, add in the root password
            final String saslEnabled = config.getSiteConfig().get(Property.INSTANCE_RPC_SASL_ENABLED.getKey());
            if (null == saslEnabled || !Boolean.parseBoolean(saslEnabled)) {
                args.add("--password");
                args.add(config.getRootPassword());
            }

            Process initProcess = exec(Initialize.class, args.toArray(new String[0]));
            int ret = initProcess.waitFor();
            if (ret != 0) {
                throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in "
                        + config.getLogDir() + " for errors.");
            }
            initialized = true;
        }
    }

    log.info("Starting MAC against instance {} and zookeeper(s) {}.", config.getInstanceName(),
            config.getZooKeepers());

    control.start(ServerType.TABLET_SERVER);

    int ret = 0;
    for (int i = 0; i < 5; i++) {
        ret = exec(Main.class, SetGoalState.class.getName(), MasterGoalState.NORMAL.toString()).waitFor();
        if (ret == 0)
            break;
        sleepUninterruptibly(1, TimeUnit.SECONDS);
    }
    if (ret != 0) {
        throw new RuntimeException("Could not set master goal state, process returned " + ret
                + ". Check the logs in " + config.getLogDir() + " for errors.");
    }

    control.start(ServerType.MASTER);
    control.start(ServerType.GARBAGE_COLLECTOR);

    if (null == executor) {
        executor = Executors.newSingleThreadExecutor();
    }
}

From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java

/**
 * Starts Accumulo and Zookeeper processes. Can only be called once.
 *///from   w w  w  . j  a v a2 s.  co m
@SuppressFBWarnings(value = "UNENCRYPTED_SOCKET", justification = "insecure socket used for reservation")
@Override
public synchronized void start() throws IOException, InterruptedException {
    if (config.useMiniDFS() && miniDFS == null) {
        throw new IllegalStateException("Cannot restart mini when using miniDFS");
    }

    MiniAccumuloClusterControl control = getClusterControl();

    if (config.useExistingInstance()) {
        AccumuloConfiguration acuConf = config.getAccumuloConfiguration();
        Configuration hadoopConf = config.getHadoopConfiguration();

        ConfigurationCopy cc = new ConfigurationCopy(acuConf);
        VolumeManager fs;
        try {
            fs = VolumeManagerImpl.get(cc, hadoopConf);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Path instanceIdPath = ServerUtil.getAccumuloInstanceIdPath(fs);

        String instanceIdFromFile = ZooUtil.getInstanceIDFromHdfs(instanceIdPath, cc, hadoopConf);
        IZooReaderWriter zrw = new ZooReaderWriterFactory().getZooReaderWriter(
                cc.get(Property.INSTANCE_ZK_HOST), (int) cc.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT),
                cc.get(Property.INSTANCE_SECRET));

        String rootPath = ZooUtil.getRoot(instanceIdFromFile);

        String instanceName = null;
        try {
            for (String name : zrw.getChildren(Constants.ZROOT + Constants.ZINSTANCES)) {
                String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name;
                byte[] bytes = zrw.getData(instanceNamePath, new Stat());
                String iid = new String(bytes, UTF_8);
                if (iid.equals(instanceIdFromFile)) {
                    instanceName = name;
                }
            }
        } catch (KeeperException e) {
            throw new RuntimeException("Unable to read instance name from zookeeper.", e);
        }
        if (instanceName == null)
            throw new RuntimeException("Unable to read instance name from zookeeper.");

        config.setInstanceName(instanceName);
        if (!AccumuloStatus.isAccumuloOffline(zrw, rootPath))
            throw new RuntimeException("The Accumulo instance being used is already running. Aborting.");
    } else {
        if (!initialized) {
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    MiniAccumuloClusterImpl.this.stop();
                } catch (IOException e) {
                    log.error("IOException while attempting to stop the MiniAccumuloCluster.", e);
                } catch (InterruptedException e) {
                    log.error("The stopping of MiniAccumuloCluster was interrupted.", e);
                }
            }));
        }

        if (!config.useExistingZooKeepers())
            control.start(ServerType.ZOOKEEPER);

        if (!initialized) {
            if (!config.useExistingZooKeepers()) {
                // sleep a little bit to let zookeeper come up before calling init, seems to work better
                long startTime = System.currentTimeMillis();
                while (true) {
                    Socket s = null;
                    try {
                        s = new Socket("localhost", config.getZooKeeperPort());
                        s.setReuseAddress(true);
                        s.getOutputStream().write("ruok\n".getBytes());
                        s.getOutputStream().flush();
                        byte[] buffer = new byte[100];
                        int n = s.getInputStream().read(buffer);
                        if (n >= 4 && new String(buffer, 0, 4).equals("imok"))
                            break;
                    } catch (Exception e) {
                        if (System.currentTimeMillis() - startTime >= config.getZooKeeperStartupTime()) {
                            throw new ZooKeeperBindException("Zookeeper did not start within "
                                    + (config.getZooKeeperStartupTime() / 1000) + " seconds. Check the logs in "
                                    + config.getLogDir() + " for errors.  Last exception: " + e);
                        }
                        // Don't spin absurdly fast
                        sleepUninterruptibly(250, TimeUnit.MILLISECONDS);
                    } finally {
                        if (s != null)
                            s.close();
                    }
                }
            }

            LinkedList<String> args = new LinkedList<>();
            args.add("--instance-name");
            args.add(config.getInstanceName());
            args.add("--user");
            args.add(config.getRootUserName());
            args.add("--clear-instance-name");

            // If we aren't using SASL, add in the root password
            final String saslEnabled = config.getSiteConfig().get(Property.INSTANCE_RPC_SASL_ENABLED.getKey());
            if (saslEnabled == null || !Boolean.parseBoolean(saslEnabled)) {
                args.add("--password");
                args.add(config.getRootPassword());
            }

            Process initProcess = exec(Initialize.class, args.toArray(new String[0])).getProcess();
            int ret = initProcess.waitFor();
            if (ret != 0) {
                throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in "
                        + config.getLogDir() + " for errors.");
            }
            initialized = true;
        }
    }

    log.info("Starting MAC against instance {} and zookeeper(s) {}.", config.getInstanceName(),
            config.getZooKeepers());

    control.start(ServerType.TABLET_SERVER);

    int ret = 0;
    for (int i = 0; i < 5; i++) {
        ret = exec(Main.class, SetGoalState.class.getName(), MasterGoalState.NORMAL.toString()).getProcess()
                .waitFor();
        if (ret == 0)
            break;
        sleepUninterruptibly(1, TimeUnit.SECONDS);
    }
    if (ret != 0) {
        throw new RuntimeException("Could not set master goal state, process returned " + ret
                + ". Check the logs in " + config.getLogDir() + " for errors.");
    }

    control.start(ServerType.MASTER);
    control.start(ServerType.GARBAGE_COLLECTOR);

    if (executor == null) {
        executor = Executors.newSingleThreadExecutor();
    }
}

From source file:org.apache.http.impl.conn.HttpClientConnectionOperator.java

public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }/*from   w w  w.  j a va2s.c  o  m*/
    final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection established " + conn);
            }
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.apache.usergrid.chop.client.ssh.Job.java

protected boolean waitActive(int timeout) {
    LOG.info("Waiting maximum {} msecs for SSH port of {} to get active", timeout, value.getPublicIpAddress());
    long startTime = System.currentTimeMillis();

    while (System.currentTimeMillis() - startTime < timeout) {
        Socket s = null;
        try {//from   w  w  w  .  j a va2  s .c om
            s = new Socket();
            s.setReuseAddress(true);
            SocketAddress sa = new InetSocketAddress(value.getPublicIpAddress(), 22);
            s.connect(sa, 2000);
            LOG.info("Port 22 of {} got opened", value.getPublicIpAddress());
            return true;
        } catch (Exception e) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ee) {
            }
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                }
            }
        }
    }
    return false;
}

From source file:org.mule.transport.tcp.AbstractTcpSocketFactory.java

public Object makeObject(Object key) throws Exception {
    TcpSocketKey socketKey = (TcpSocketKey) key;

    Socket socket = createSocket(socketKey);
    socket.setReuseAddress(true);

    TcpConnector connector = socketKey.getConnector();
    connector.configureSocket(TcpConnector.CLIENT, socket);

    return socket;
}

From source file:org.opennms.test.system.api.NewTestEnvironment.java

/**
 * Blocks until we can connect to the PostgreSQL data port.
 *///  w w  w.  j a  v  a  2 s.  c o  m
private void waitForPostgres() {
    final ContainerAlias alias = ContainerAlias.POSTGRES;
    if (!isEnabled(alias)) {
        return;
    }

    final InetSocketAddress postgresAddr = getServiceAddress(alias, 5432);
    final Callable<Boolean> isConnected = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                final Socket socket = new Socket(postgresAddr.getAddress(), postgresAddr.getPort());
                socket.setReuseAddress(true);
                final InputStream is = socket.getInputStream();
                final OutputStream os = socket.getOutputStream();
                os.write("\\_()_/\n".getBytes());
                os.close();
                is.close();
                socket.close();
                // good enough, not gonna try speaking the PostgreSQL protocol
                return true;
            } catch (final Throwable t) {
                LOG.debug("PostgreSQL connect failed: " + t.getMessage());
                return null;
            }
        }
    };
    LOG.info("************************************************************");
    LOG.info("Waiting for PostgreSQL service @ {}.", postgresAddr);
    LOG.info("************************************************************");
    await().atMost(5, MINUTES).pollInterval(10, SECONDS).until(isConnected, is(notNullValue()));
}

From source file:org.wso2.carbon.analytics.common.jmx.agent.JmxAgentWebInterface.java

/**
 * Test the availability of the DataPublisher by
 * trying to connect to it (credentials are not checked)
 *
 * @return : whether the test was successful or not
 *///from  ww w. j  a v a  2 s .c om
public boolean testDataPublisherAvailability(String connectionType, String url, int port) {

    //check for tcp and ssl port availability
    if (connectionType.equalsIgnoreCase("tcp://") || connectionType.equalsIgnoreCase("ssl://")) {

        DatagramSocket ds = null;

        try {
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);

            return true;
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }

    //check for http and https port availability
    if (connectionType.equalsIgnoreCase("http://") || connectionType.equalsIgnoreCase("https://")) {

        Socket socket = null;

        try {
            socket = new Socket();
            socket.setReuseAddress(true);

            SocketAddress sa = new InetSocketAddress(url, port);
            socket.connect(sa);
            return true;
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    //do nothing
                }
            }
        }
    }

    return false;
}