Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.isecpartners.gizmo.HttpRequest.java

void passThroughAllBits() {
    try {/*from   w w w .java2  s  . c o  m*/
        Socket destinationHost = new Socket(host, port);
        byte[] buf = new byte[1024];
        boolean didNothing = true;
        while (!this.sock.isClosed() && !destinationHost.isClosed()) {
            didNothing = true;
            if (sock.getInputStream().available() > 0) {
                int b = sock.getInputStream().read(buf);
                destinationHost.getOutputStream().write(buf, 0, b);
                didNothing = false;
            }
            if (destinationHost.getInputStream().available() > 0) {
                int b = destinationHost.getInputStream().read(buf);
                sock.getOutputStream().write(buf, 0, b);
                didNothing = false;
            }
            if (didNothing) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        this.sock.close();
        destinationHost.close();
    } catch (UnknownHostException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.cong.chenchong.wifi.manager.ProxyConnector.java

/**
 * Connects an outgoing socket to the proxy and authenticates, creating an account
 * if necessary.// w w  w. j a  va  2  s. c o m
 */
private Socket newAuthedSocket(String hostname, int port) {
    if (hostname == null) {
        //myLog.i("newAuthedSocket can't connect to null host");
        return null;
    }
    JSONObject json = new JSONObject();
    //String secret = retrieveSecret();
    Socket socket;
    OutputStream out = null;
    InputStream in = null;

    try {
        //myLog.d("Opening proxy connection to " + hostname + ":" + port);
        socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT);
        json.put("android_id", RemoteUtil.getAndroidId());
        json.put("swiftp_version", RemoteUtil.getVersion());
        json.put("action", "login");
        out = socket.getOutputStream();
        in = socket.getInputStream();
        int numBytes;

        out.write(json.toString().getBytes(ENCODING));
        //myLog.l(Log.DEBUG, "Sent login request");
        // Read and parse the server's response
        byte[] bytes = new byte[IN_BUF_SIZE];
        // Here we assume that the server's response will all be contained in
        // a single read, which may be unsafe for large responses
        numBytes = in.read(bytes);
        if (numBytes == -1) {
            //myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response");
            return null;
        } else if (numBytes == 0) {
            //myLog.l(Log.INFO, "Short network read waiting for auth, quitting");
            return null;
        }
        json = new JSONObject(new String(bytes, 0, numBytes, ENCODING));
        if (checkAndPrintJsonError(json)) {
            return null;
        }
        //myLog.d("newAuthedSocket successful");
        return socket;
    } catch (Exception e) {
        //myLog.i("Exception during proxy connection or authentication: " + e);
        return null;
    }
}

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

/**
 * Starts Accumulo and Zookeeper processes. Can only be called once.
 *//* w  ww . j ava2s.c o  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:com.hijacker.MainActivity.java

static void checkForUpdate(final Activity activity, final boolean showMessages) {
    //Can be called from any thread, blocks until the job is finished
    Runnable runnable = new Runnable() {
        @Override//  w  ww.j  ava2  s.c o  m
        public void run() {
            progress.setIndeterminate(false);
        }
    };
    if (showMessages) {
        runInHandler(new Runnable() {
            @Override
            public void run() {
                progress.setIndeterminate(true);
            }
        });
    }
    Socket socket = connect();
    if (socket == null) {
        if (showMessages) {
            runInHandler(runnable);
            Snackbar.make(rootView, activity.getString(R.string.server_error), Snackbar.LENGTH_SHORT).show();
        }
        return;
    }

    try {
        PrintWriter in = new PrintWriter(socket.getOutputStream());
        BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        in.print(REQ_VERSION + '\n');
        in.flush();

        int latestCode = Integer.parseInt(out.readLine());
        String latestName = out.readLine();
        String latestLink = out.readLine();

        in.print(REQ_EXIT + '\n');
        in.flush();
        in.close();
        out.close();
        socket.close();

        if (latestCode > versionCode) {
            final UpdateConfirmDialog dialog = new UpdateConfirmDialog();
            dialog.newVersionCode = latestCode;
            dialog.newVersionName = latestName;
            dialog.link = latestLink;
            runInHandler(new Runnable() {
                @Override
                public void run() {
                    dialog.show(activity.getFragmentManager(), "UpdateConfirmDialog");
                }
            });
        } else {
            if (showMessages)
                Snackbar.make(rootView, activity.getString(R.string.already_on_latest), Snackbar.LENGTH_SHORT)
                        .show();
        }
    } catch (IOException | NumberFormatException e) {
        Log.e("HIJACKER/update", e.toString());
        if (showMessages)
            Snackbar.make(rootView, activity.getString(R.string.unknown_error), Snackbar.LENGTH_SHORT).show();
    } finally {
        if (showMessages)
            runInHandler(runnable);
    }
}

From source file:com.predic8.membrane.core.rules.SSLProxy.java

@Override
public SSLContext getSslInboundContext() {
    return new SSLContext(new SSLParser(), router.getResolverMap(), router.getBaseLocation()) {

        @Override/*  w  w  w  .j  av a  2s. co  m*/
        public Socket wrap(Socket socket, byte[] buffer, int position) throws IOException {
            int port = target.getPort();
            if (port == -1)
                port = getPort();

            StreamPump.StreamPumpStats streamPumpStats = router.getStatistics().getStreamPumpStats();
            String protocol = "SSL";

            Connection con = cm.getConnection(target.getHost(), port, connectionConfiguration.getLocalAddr(),
                    null, connectionConfiguration.getTimeout());

            con.out.write(buffer, 0, position);
            con.out.flush();

            String source = socket.getRemoteSocketAddress().toString();
            String dest = con.toString();
            final StreamPump a = new StreamPump(con.in, socket.getOutputStream(), streamPumpStats,
                    protocol + " " + source + " <- " + dest, SSLProxy.this);
            final StreamPump b = new StreamPump(socket.getInputStream(), con.out, streamPumpStats,
                    protocol + " " + source + " -> " + dest, SSLProxy.this);

            socket.setSoTimeout(0);

            String threadName = Thread.currentThread().getName();
            new Thread(a, threadName + " " + protocol + " Backward Thread").start();
            try {
                Thread.currentThread().setName(threadName + " " + protocol + " Onward Thread");
                b.run();
            } finally {
                try {
                    con.close();
                } catch (IOException e) {
                    log.debug("", e);
                }
            }
            throw new SocketException("SSL Forwarding Connection closed.");
        }
    };
}

From source file:it.jnrpe.client.JNRPEClient.java

/**
 * Inovoke a command installed in JNRPE.
 * //  w  w w.  j a  v a2s  . c  o  m
 * @param sCommandName
 *            The name of the command to be invoked
 * @param arguments
 *            The arguments to pass to the command (will substitute the
 *            $ARGSx$ parameters)
 * @return The value returned by the server
 * @throws JNRPEClientException
 *             Thrown on any communication error.
 */
public final ReturnValue sendCommand(final String sCommandName, final String... arguments)
        throws JNRPEClientException {
    SocketFactory socketFactory;

    Socket s = null;
    try {
        if (!useSSL) {
            socketFactory = SocketFactory.getDefault();
        } else {
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

            sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom());

            socketFactory = sslContext.getSocketFactory();
        }

        s = socketFactory.createSocket();
        if (weakCipherSuitesEnabled) {
            SSLSocket ssl = (SSLSocket) s;
            ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        }

        s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout));
        s.connect(new InetSocketAddress(serverIPorURL, serverPort));
        JNRPERequest req = new JNRPERequest(sCommandName, arguments);

        s.getOutputStream().write(req.toByteArray());

        InputStream in = s.getInputStream();
        JNRPEResponse res = new JNRPEResponse(in);

        return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage());
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new JNRPEClientException(e);
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:com.clavain.munin.MuninNode.java

private void updateTrackPackages(Socket p_socket) {
    // only try to update this once per hour
    int curTime = getUnixtime();
    int lalert = this.last_pkg_update + 3600;
    if (lalert > curTime) {
        return;/*from  w w w .  j a v  a 2  s  .co m*/
    }

    String decodestr = "";
    try {
        logger.info("TrackPackages - fetching " + this.str_hostname);
        PrintStream os = new PrintStream(p_socket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(p_socket.getInputStream()));
        os.println("config muninmx_trackpkg");
        // skip first line if starts with #
        decodestr = in.readLine();
        if (decodestr.startsWith("#")) {
            decodestr = in.readLine();
        }

        if (decodestr.equals(".")) {
            decodestr = in.readLine();
        }
        byte[] decode = Base64.decodeBase64(decodestr);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decode);
        GZIPInputStream gzipInputStream;
        gzipInputStream = new GZIPInputStream(byteArrayInputStream);

        InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 4);

        String read;
        String sum = bufferedReader.readLine();
        if (sum == null) {
            logger.error("TrackPackages - sum is null for: " + this.str_hostname);
            return;
        }
        String dist = bufferedReader.readLine();
        String ver = bufferedReader.readLine();
        String kernel = bufferedReader.readLine();
        if (dbTrackLogChangedForNode(sum, this.node_id)) {
            logger.info("TrackPackages - packages changed, updating " + this.str_hostname);
            // purge old logs
            removeOldPackageTrack(this.node_id);

            dbUpdateNodeDistVerKernel(sum, dist, ver, kernel, this.node_id);
            int i = 0;
            while ((read = bufferedReader.readLine()) != null) {
                BasicDBObject doc = new BasicDBObject();
                doc.put("package", read);
                doc.put("time", getUnixtime());
                doc.put("node", this.node_id);
                doc.put("type", "trackpkg");
                com.clavain.muninmxcd.mongo_essential_queue.add(doc);
                i++;
            }
            logger.info("TrackPackages Updated for Node: " + this.getHostname() + " (" + dist + " " + ver + " "
                    + kernel + "). tracking " + i + " packages");
        } else {
            logger.info("TrackPackages - sum not changed since last run for Node: " + this.getHostname());
        }
        this.last_pkg_update = getUnixtime();

    } catch (Exception ex) {
        logger.error("Error in updateTrackPackages for Node " + this.getHostname() + " : "
                + ex.getLocalizedMessage());
        logger.error("updateTrackPackages for Node " + this.getHostname() + " received: " + decodestr);
        ex.printStackTrace();
    }

}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//from w  w  w . jav a  2  s.co  m
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

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

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

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

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

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

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}

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

/**
 * Starts Accumulo and Zookeeper processes. Can only be called once.
 *//*w w w .  j  av  a 2  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:com.raddle.tools.ClipboardTransferMain.java

private Object doInSocket(SocketCallback callback) {
    Socket socket = null;
    try {//  w w w . ja  v a2  s. c  o m
        String address = serverAddrTxt.getText();
        String[] ipport = address.split(":");
        if (ipport.length != 2) {
            updateMessage("????");
            return null;
        }
        socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress(ipport[0], Integer.parseInt(ipport[1]));
        socket.connect(socketAddress, 2000);
        socket.setSoTimeout(10000);
        return callback.connected(socket);
    } catch (Exception e) {
        e.printStackTrace();
        updateMessage("?" + e.getMessage());
        return null;
    } finally {
        if (socket != null) {
            try {
                socket.getInputStream().close();
            } catch (IOException e) {
            }
            try {
                socket.getOutputStream().close();
            } catch (IOException e) {
            }
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
}