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.sun.faces.systest.ant.SystestClient.java

/**
 * Execute the test via use of a socket with direct input/output.
 *
 * @throws BuildException if an exception occurs
 */// w  w w  .  j  av a2 s.  c  om
protected void executeSocket() throws BuildException {

    // Construct a summary of the request we will be sending
    String command = method + " " + request + " " + protocol;
    String summary = "[" + command + "]";
    if (log.isDebugEnabled()) {
        log.debug("RQST: " + summary);
    }
    boolean success = true;
    String result = null;
    Socket socket = null;
    OutputStream os = null;
    PrintWriter pw = null;
    InputStream is = null;
    Throwable throwable = null;
    int outStatus = 0;
    String outMessage = null;

    try {

        // Open a client socket for this request
        socket = new Socket(host, port);
        os = socket.getOutputStream();
        pw = new PrintWriter(os);
        is = socket.getInputStream();

        // Send the command and content length header (if any)
        pw.print(command + "\r\n");
        if (inContent != null) {
            if (log.isTraceEnabled()) {
                log.trace("INPH: " + "Content-Length: " + inContent.length());
            }
            pw.print("Content-Length: " + inContent.length() + "\r\n");
        }

        // Send the session id cookie (if any)
        if (joinSession && (sessionId != null)) {
            pw.println("Cookie: JSESSIONID=" + sessionId);
            if (log.isTraceEnabled()) {
                log.trace("INPH: Cookie: JSESSIONID=" + sessionId);
            }
        }

        // Send the specified headers (if any)
        if (inHeaders != null) {
            String headers = inHeaders;
            while (headers.length() > 0) {
                int delimiter = headers.indexOf("##");
                String header = null;
                if (delimiter < 0) {
                    header = headers;
                    headers = "";
                } else {
                    header = headers.substring(0, delimiter);
                    headers = headers.substring(delimiter + 2);
                }
                int colon = header.indexOf(":");
                if (colon < 0)
                    break;
                String name = header.substring(0, colon).trim();
                String value = header.substring(colon + 1).trim();
                if (log.isTraceEnabled()) {
                    log.trace("INPH: " + name + ": " + value);
                }
                pw.print(name + ": " + value + "\r\n");
            }
        }
        pw.print("\r\n");

        // Send our content (if any)
        if (inContent != null) {
            if (log.isTraceEnabled()) {
                log.trace("INPD: " + inContent);
            }
            for (int i = 0, length = inContent.length(); i < length; i++)
                pw.print(inContent.charAt(i));
        }
        pw.flush();

        // Read the response status and associated message
        String line = read(is);
        if (line == null) {
            outStatus = -1;
            outMessage = "NO RESPONSE";
        } else {
            line = line.trim();
            if (log.isTraceEnabled()) {
                log.trace("RESP: " + line);
            }
            int space = line.indexOf(" ");
            if (space >= 0) {
                line = line.substring(space + 1).trim();
                space = line.indexOf(" ");
            }
            try {
                if (space < 0) {
                    outStatus = Integer.parseInt(line);
                    outMessage = "";
                } else {
                    outStatus = Integer.parseInt(line.substring(0, space));
                    outMessage = line.substring(space + 1).trim();
                }
            } catch (NumberFormatException e) {
                outStatus = -1;
                outMessage = "NUMBER FORMAT EXCEPTION";
            }
        }
        if (log.isTraceEnabled()) {
            log.trace("STAT: " + outStatus + " MESG: " + outMessage);
        }

        // Read the response headers (if any)
        String headerName = null;
        String headerValue = null;
        while (true) {
            line = read(is);
            if ((line == null) || (line.length() == 0))
                break;
            int colon = line.indexOf(":");
            if (colon < 0) {
                if (log.isTraceEnabled()) {
                    log.trace("????: " + line);
                }
            } else {
                headerName = line.substring(0, colon).trim();
                headerValue = line.substring(colon + 1).trim();
                if (log.isTraceEnabled()) {
                    log.trace("HEAD: " + headerName + ": " + headerValue);
                }
                save(headerName, headerValue);
                if ("Set-Cookie".equals(headerName))
                    parseSession(headerValue);
            }
        }

        // Acquire the response data (if any)
        String outData = "";
        String outText = "";
        int lines = 0;
        while (true) {
            line = read(is);
            if (line == null)
                break;
            if (lines == 0)
                outData = line;
            else
                outText += line + "\r\n";
            saveResponse.add(line);
            lines++;
        }
        is.close();
        if (log.isTraceEnabled()) {
            log.trace("DATA: " + outData);
            if (outText.length() > 2) {
                log.trace("TEXT: " + outText);
            }
        }

        // Validate the response against our criteria
        if (success) {
            result = validateStatus(outStatus);
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateMessage(message);
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateHeaders();
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateData(outData);
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateGolden();
            if (result != null)
                success = false;
        }

    } catch (Throwable t) {
        success = false;
        result = "Status=" + outStatus + ", Message=" + outMessage;
        throwable = null;
    } finally {
        if (pw != null) {
            try {
                pw.close();
            } catch (Throwable w) {
                ;
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (Throwable w) {
                ;
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (Throwable w) {
                ;
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (Throwable w) {
                ;
            }
        }
    }

    if (success) {
        System.out.println("OK   " + summary);
    } else {
        System.out.println("FAIL " + summary + " " + result);
        if (throwable != null)
            throwable.printStackTrace(System.out);
        if (failonerror) {
            if (throwable != null) {
                throw new BuildException("System test failed", throwable);
            } else {
                throw new BuildException("System test failed");
            }
        }
    }

}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Client-side handshake with a Server//from  w w  w.ja va2 s . c o  m
 */
public ServerQueueStatus handshakeWithServer(Connection conn, ServerLocation location,
        CommunicationMode communicationMode) throws IOException, AuthenticationRequiredException,
        AuthenticationFailedException, ServerRefusedConnectionException {
    try {
        ServerQueueStatus serverQStatus = null;
        Socket sock = conn.getSocket();
        DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
        final InputStream in = sock.getInputStream();
        DataInputStream dis = new DataInputStream(in);
        DistributedMember member = getIDForSocket(sock);
        // if running in a loner system, use the new port number in the ID to
        // help differentiate from other clients
        DM dm = ((InternalDistributedSystem) this.system).getDistributionManager();
        InternalDistributedMember idm = dm.getDistributionManagerId();
        synchronized (idm) {
            if (idm.getPort() == 0 && dm instanceof LonerDistributionManager) {
                int port = sock.getLocalPort();
                ((LonerDistributionManager) dm).updateLonerPort(port);
                updateProxyID(dm.getDistributionManagerId());
            }
        }
        if (communicationMode.isWAN()) {
            this.credentials = getCredentials(member);
        }
        byte intermediateAcceptanceCode = write(dos, dis, communicationMode, REPLY_OK, this.clientReadTimeout,
                null, this.credentials, member, false);

        String authInit = this.system.getProperties().getProperty(SECURITY_CLIENT_AUTH_INIT);
        if (!communicationMode.isWAN() && intermediateAcceptanceCode != REPLY_AUTH_NOT_REQUIRED
                && (authInit != null && authInit.length() != 0)) {
            location.compareAndSetRequiresCredentials(true);
        }
        // Read the acceptance code
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode == (byte) 21 && !(sock instanceof SSLSocket)) {
            // This is likely the case of server setup with SSL and client not using
            // SSL
            throw new AuthenticationRequiredException(
                    LocalizedStrings.HandShake_SERVER_EXPECTING_SSL_CONNECTION.toLocalizedString());
        }
        if (acceptanceCode == REPLY_SERVER_IS_LOCATOR) {
            throw new GemFireConfigException("Improperly configured client detected.  " + "Server at "
                    + location + " is actually a locator.  Use addPoolLocator to configure locators.");
        }

        // Successful handshake for GATEWAY_TO_GATEWAY mode sets the peer version in connection
        if (communicationMode.isWAN() && !(acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_REQUIRED
                || acceptanceCode == REPLY_EXCEPTION_AUTHENTICATION_FAILED)) {
            short wanSiteVersion = Version.readOrdinal(dis);
            conn.setWanSiteVersion(wanSiteVersion);
            // establish a versioned stream for the other site, if necessary
            if (wanSiteVersion < Version.CURRENT_ORDINAL) {
                dis = new VersionedDataInputStream(dis, Version.fromOrdinalOrCurrent(wanSiteVersion));
            }
        }

        // No need to check for return value since DataInputStream already throws
        // EOFException in case of EOF
        byte epType = dis.readByte();
        int qSize = dis.readInt();

        // Read the server member
        member = readServerMember(dis);
        serverQStatus = new ServerQueueStatus(epType, qSize, member);

        // Read the message (if any)
        readMessage(dis, dos, acceptanceCode, member);

        // Read delta-propagation property value from server.
        // [sumedh] Static variable below? Client can connect to different
        // DSes with different values of this. It shoule be a member variable.
        if (!communicationMode.isWAN() && currentClientVersion.compareTo(Version.GFE_61) >= 0) {
            deltaEnabledOnServer = dis.readBoolean();
        }

        // validate that the remote side has a different distributed system id.
        if (communicationMode.isWAN() && Version.GFE_66.compareTo(conn.getWanSiteVersion()) <= 0
                && currentClientVersion.compareTo(Version.GFE_66) >= 0) {
            int remoteDistributedSystemId = in.read();
            int localDistributedSystemId = ((InternalDistributedSystem) system).getDistributionManager()
                    .getDistributedSystemId();
            if (localDistributedSystemId >= 0 && localDistributedSystemId == remoteDistributedSystemId) {
                throw new GatewayConfigurationException(
                        "Remote WAN site's distributed system id " + remoteDistributedSystemId
                                + " matches this sites distributed system id " + localDistributedSystemId);
            }
        }
        // Read the PDX registry size from the remote size
        if (communicationMode.isWAN() && Version.GFE_80.compareTo(conn.getWanSiteVersion()) <= 0
                && currentClientVersion.compareTo(Version.GFE_80) >= 0) {
            int remotePdxSize = dis.readInt();
            serverQStatus.setPdxSize(remotePdxSize);
        }

        return serverQStatus;
    } catch (IOException ex) {
        CancelCriterion stopper = this.system.getCancelCriterion();
        stopper.checkCancelInProgress(null);
        throw ex;
    }
}

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

/**
 * Will load the plugin list from munin-node
 *///from  w  w  w  . j  a va  2 s  .  c o  m
public boolean loadPlugins() {
    setLoadedPlugins(new CopyOnWriteArrayList<MuninPlugin>());
    String l_lastProceeded = "";

    try {
        Socket cs = new Socket();
        cs.setKeepAlive(false);
        cs.setSoLinger(true, 0);
        cs.setReuseAddress(true);
        cs.setSoTimeout(com.clavain.muninmxcd.socketTimeout);
        if (!str_via.equals("unset")) {
            cs.connect(new InetSocketAddress(this.getStr_via(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        } else {
            cs.connect(new InetSocketAddress(this.getHostname(), this.getPort()),
                    com.clavain.muninmxcd.socketTimeout);
        }

        if (p.getProperty("kill.sockets").equals("true")) {
            SocketCheck sc = new SocketCheck(cs, getUnixtime());
            sc.setHostname(this.getHostname());
            com.clavain.muninmxcd.v_sockets.add(sc);
        }
        PrintStream os = new PrintStream(cs.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()));

        String s = in.readLine();

        if (s != null) {
            // Set version
            os.println("version");
            Thread.sleep(150);
            s = in.readLine();

            String version = s.substring(s.indexOf(":") + 1, s.length()).trim();
            this.str_muninVersion = version;

            if (authpw != null) {
                // if authpw is set, verify
                if (!authpw.trim().equals("")) {
                    os.println("config muninmxauth");
                    Thread.sleep(150);
                    String apw = in.readLine();
                    s = in.readLine();
                    if (!apw.trim().equals(this.getAuthpw())) {
                        logger.error("Invalid muninmxauth password for host: " + this.getHostname());
                        cs.close();
                        return false;
                    }
                }
            }
            // check anyway if muninmxauth plugin is present
            else {
                os.println("config muninmxauth");
                Thread.sleep(100);
                String apw = in.readLine();
                if (!apw.trim().equals("# Unknown service")) {
                    logger.error(
                            "no auth password given, but muninmxauth plugin present on " + this.getHostname());
                    cs.close();
                    return false;
                }
                s = in.readLine();
            }

            // get list of available plugins
            if (str_via.equals("unset")) {
                os.println("list");
            } else {
                os.println("list " + str_hostname);
            }

            Thread.sleep(250);
            s = in.readLine();

            // if response is empty and host is not via, do a list $hostname
            if (s.trim().equals("") && str_via.equals("unset")) {
                logger.info("Plugin Response Empty on " + this.getHostname()
                        + " trying to load with list $hostname");
                os.println("list " + this.getHostname());
                Thread.sleep(250);
                s = in.readLine();
            }

            String l_tmp;
            StringTokenizer l_st = new StringTokenizer(s, " ");

            // create plugin
            MuninPlugin l_mp = new MuninPlugin();
            // negative support
            ArrayList<String> tmp_negatives = new ArrayList<String>();

            while (l_st.hasMoreTokens()) {

                String l_strPlugin = l_st.nextToken();

                // check for track_pkg and muninmx essentials
                if (l_strPlugin.equals("muninmx_trackpkg")) {
                    this.setTrack_pkg(true);
                    continue;
                }

                // got essentials?
                if (l_strPlugin.equals("muninmx_essentials")) {
                    this.setEssentials(true);
                    continue;
                }

                if (isPluginIgnored(l_strPlugin.toUpperCase())) {
                    continue;
                }

                l_mp.setPluginName(l_strPlugin);

                os.println("config " + l_strPlugin);

                // create graphs for plugin
                int l_iGraphsFound = 0;
                int l_iTmp = 0;
                MuninGraph l_mg = new MuninGraph();
                l_mg.setQueryInterval(this.getQueryInterval());
                while ((l_tmp = in.readLine()) != null) {
                    if (l_tmp.startsWith(".")) {
                        break;
                    }
                    // collect graphs only for plugin
                    String l_strName;
                    String l_strType;
                    String l_strValue;

                    if (!l_tmp.contains("graph_") && !l_tmp.trim().equals("") && !l_tmp.contains("host_name")
                            && !l_tmp.contains("multigraph") && !l_tmp.trim().equals("graph no")
                            && !l_tmp.trim().equals("# Bad exit")
                            && !l_tmp.trim().contains("info Currently our peer")
                            && !l_tmp.trim().startsWith("#")
                            && !l_tmp.trim().contains("Bonding interface errors")) {
                        l_lastProceeded = l_tmp;
                        l_strName = l_tmp.substring(0, l_tmp.indexOf("."));
                        l_strType = l_tmp.substring(l_tmp.indexOf(".") + 1, l_tmp.indexOf(" "));
                        l_strValue = l_tmp.substring(l_tmp.indexOf(" ") + 1, l_tmp.length());
                        //System.err.println("Name: " + l_strName + " Type: " + l_strType + " Value: " + l_strValue);

                        if (l_strType.equals("label")) {
                            l_iTmp++;

                            if (l_iTmp > 1) {
                                l_mp.addGraph(l_mg);
                                l_mg = new MuninGraph();
                                l_mg.setQueryInterval(this.getQueryInterval());
                            }
                            l_mg.setGraphName(l_strName);
                            l_mg.setGraphLabel(l_strValue);
                        } else if (l_strType.equals("draw")) {
                            l_mg.setGraphDraw(l_strValue);
                        } else if (l_strType.equals("type")) {
                            l_mg.setGraphType(l_strValue);
                        } else if (l_strType.equals("info")) {
                            l_mg.setGraphInfo(l_strValue);
                        } else if (l_strType.equals("negative")) {
                            // add to temporary negative list to set negatives later
                            tmp_negatives.add(l_strValue);
                        }

                        //System.out.println(l_strName); 
                        //System.out.println(l_strType);
                        //System.out.println(l_strValue);
                    } else {
                        // set plugin title
                        if (l_tmp.contains("graph_title")) {
                            l_mp.setPluginTitle(l_tmp.substring(12, l_tmp.length()));
                        }
                        // set plugin info, if any
                        if (l_tmp.contains("graph_info")) {
                            l_mp.setPluginInfo(l_tmp.substring(11, l_tmp.length()));
                        }
                        // set graph category
                        if (l_tmp.contains("graph_category")) {
                            l_mp.setPluginCategory(l_tmp.substring(15, l_tmp.length()));
                        }
                        // set graph vlabel
                        if (l_tmp.contains("graph_vlabel")) {
                            l_mp.setPluginLabel(l_tmp.substring(13, l_tmp.length()));
                        }
                        // set plugin title
                        if (l_tmp.contains("graph_mxdraw")) {
                            l_mp.setStr_LineMode(l_tmp.substring(13, l_tmp.length()));
                        }
                    }

                }

                // add to pluginlist
                l_mp.addGraph(l_mg);

                Iterator it = l_mp.getGraphs().iterator();
                while (it.hasNext()) {
                    MuninGraph l_mpNg = (MuninGraph) it.next();
                    if (tmp_negatives.contains(l_mpNg.getGraphName())) {
                        l_mpNg.setNegative(true);
                    }
                }

                // add plugin if it got valid graphs and add nodeid (req. for alerts)
                if (l_mp.getGraphs().size() > 0) {
                    l_mp.set_NodeId(this.getNode_id());
                    getLoadedPlugins().add(l_mp);
                }
                // flush temporary negatives
                tmp_negatives.clear();
                l_mp = null;
                l_mp = new MuninPlugin();
                //String l_strGraphTitle = s.substring(s.indexOf("graph_title") + 11,s.length());
                //System.out.println(" - " + l_strGraphTitle);
            }
            cs.close();
            in.close();
            os.close();
            last_plugin_load = getUnixtime();
            //System.out.println(s);
        } else {
            cs.close();
            in.close();
            os.close();
            logger.warn("Error loading plugins on " + str_hostname + " (" + this.getNode_id()
                    + "). Check connectivity or munin-node");
        }
        /*
        for (MuninPlugin l_mn : getLoadedPlugins()) {
        i_GraphCount = i_GraphCount + l_mn.getGraphs().size();
        logger.debug(l_mn.getGraphs().size() + " graphs found for plugin: " + l_mn.getPluginName().toUpperCase() + " on node: " + this.getNodename());
        }*/
    } catch (Exception ex) {
        logger.error("Error loading plugins on " + str_hostname + " (" + this.getNode_id() + ") : "
                + ex.getMessage());
        ex.printStackTrace();
        return false;
    }

    return true;
}

From source file:hudson.cli.CLI.java

/**
 * @deprecated Specific to {@link Mode#REMOTING}.
 *///from   w  ww .  ja  va  2 s  .  com
@Deprecated
private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException {
    LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint);

    if (authorization != null) {
        LOGGER.warning("-auth ignored when using JNLP agent port");
    }

    final Socket s = new Socket();
    // this prevents a connection from silently terminated by the router in between or the other peer
    // and that goes without unnoticed. However, the time out is often very long (for example 2 hours
    // by default in Linux) that this alone is enough to prevent that.
    s.setKeepAlive(true);
    // we take care of buffering on our own
    s.setTcpNoDelay(true);
    OutputStream out;

    if (httpsProxyTunnel != null) {
        String[] tokens = httpsProxyTunnel.split(":");
        LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port",
                new Object[] { tokens[0], tokens[1] });
        s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1])));
        PrintStream o = new PrintStream(s.getOutputStream());
        o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort()
                + " HTTP/1.0\r\n\r\n");

        // read the response from the proxy
        ByteArrayOutputStream rsp = new ByteArrayOutputStream();
        while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) {
            int ch = s.getInputStream().read();
            if (ch < 0)
                throw new IOException("Failed to read the HTTP proxy response: " + rsp);
            rsp.write(ch);
        }
        String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine();

        if (head == null) {
            throw new IOException("Unexpected empty response");
        }
        if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) {
            s.close();
            LOGGER.log(Level.SEVERE,
                    "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP.");
            throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp);
        }

        // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well.
        // So instead of relying on it, we'll just send the close command and then let the server
        // cut their side, then close the socket after the join.
        out = new SocketOutputStream(s) {
            @Override
            public void close() throws IOException {
                // ignore
            }
        };
    } else {
        s.connect(clip.endpoint, 3000);
        out = SocketChannelStream.out(s);
    }

    closables.add(new Closeable() {
        public void close() throws IOException {
            s.close();
        }
    });

    Connection c = new Connection(SocketChannelStream.in(s), out);

    switch (clip.version) {
    case 1:
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI-connect");
        // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor.
        break;
    case 2:
        DataInputStream dis = new DataInputStream(s.getInputStream());
        dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI2-connect");
        String greeting = dis.readUTF();
        if (!greeting.equals("Welcome"))
            throw new IOException("Handshaking failed: " + greeting);
        try {
            byte[] secret = c.diffieHellman(false).generateSecret();
            SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES");
            c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding");

            // validate the instance identity, so that we can be sure that we are talking to the same server
            // and there's no one in the middle.
            byte[] signature = c.readByteArray();

            if (clip.identity != null) {
                Signature verifier = Signature.getInstance("SHA1withRSA");
                verifier.initVerify(clip.getIdentity());
                verifier.update(secret);
                if (!verifier.verify(signature))
                    throw new IOException("Server identity signature validation failed.");
            }

        } catch (GeneralSecurityException e) {
            throw (IOException) new IOException("Failed to negotiate transport security").initCause(e);
        }
    }

    return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in),
            new BufferedOutputStream(c.out));
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Returns true if the application is launched.
 * //from ww  w  .  java  2 s . c o  m
 * @return true, if the server is ready.
 */
private boolean isLaunched() {
    try {
        Socket client = getSocket();
        LOGGER.info("Is server ready for " + testName + "?");
        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println("isLaunched");
        os.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8));
        String s = in.readLine();
        LOGGER.info(s);
        client.close();
        return Boolean.valueOf(s);
    } catch (UnknownHostException e) {
        LOGGER.error("isLaunched UnknownHostException: ", e);
    } catch (ConnectException e) {
        LOGGER.trace("Server not available.");
    } catch (IOException e) {
        LOGGER.error("isLaunched IOException: ", e);
    }
    return false;
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * @param message/*www  . j  av a  2s. c  o  m*/
 *            the message as a string, that should send.
 * @return the result of the call
 * @throws UnknownHostException
 * @throws IOException
 */
private boolean sendMessage(String message) {

    StringBuilder result = new StringBuilder();

    try {
        Socket client = getSocket();

        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println(message);
        LOGGER.info("Send message to AUT:" + message);
        os.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8));

        int c;
        while ((c = in.read()) != -1) {
            result.append((char) c);
        }
        String myMessage = result.toString();
        if (myMessage.indexOf("ERROR ") > -1) {
            LOGGER.error("Fails: " + myMessage);
            throw new RuntimeException("Message: " + message + " fails with: " + myMessage);
        }

        client.close();

    } catch (UnknownHostException e) {
        LOGGER.error("SendMessage Host not Found", e);
    } catch (IOException e) {
        LOGGER.error("Send Message IOException ", e);
    }
    if (result.toString().startsWith("true")) {
        return true;
    }
    return false;
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Used by client-side CacheClientUpdater to handshake with a server in order to receive messages
 * generated by subscriptions (register-interest, continuous query)
 *//*from  w  ww.j a v  a2 s  . com*/
public ServerQueueStatus handshakeWithSubscriptionFeed(Socket sock, boolean isPrimary)
        throws IOException, AuthenticationRequiredException, AuthenticationFailedException,
        ServerRefusedConnectionException, ClassNotFoundException {
    ServerQueueStatus sqs = null;
    try {
        DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
        final InputStream in = sock.getInputStream();
        DataInputStream dis = new DataInputStream(in);
        DistributedMember member = getIDForSocket(sock);
        if (!this.multiuserSecureMode) {
            this.credentials = getCredentials(member);
        }
        CommunicationMode mode = isPrimary ? CommunicationMode.PrimaryServerToClient
                : CommunicationMode.SecondaryServerToClient;
        write(dos, dis, mode, REPLY_OK, 0, new ArrayList(), this.credentials, member, true);

        // Wait here for a reply before continuing. This ensures that the client
        // updater is registered with the server before continuing.
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode == (byte) 21 && !(sock instanceof SSLSocket)) {
            // This is likely the case of server setup with SSL and client not using
            // SSL
            throw new AuthenticationRequiredException(
                    LocalizedStrings.HandShake_SERVER_EXPECTING_SSL_CONNECTION.toLocalizedString());
        }

        // No need to check for return value since DataInputStream already throws
        // EOFException in case of EOF
        byte qType = dis.readByte();
        // read and ignore qSize flag
        int qSize = dis.readInt();
        sqs = new ServerQueueStatus(qType, qSize, member);

        // Read the message (if any)
        readMessage(dis, dos, acceptanceCode, member);

        // [sumedh] nothing more to be done for older clients used in tests
        // there is a difference in serializer map registration for >= 6.5.1.6
        // clients but that is not used in tests
        if (currentClientVersion.compareTo(Version.GFE_61) < 0) {
            return sqs;
        }
        HashMap instantiatorMap = DataSerializer.readHashMap(dis);
        for (Iterator itr = instantiatorMap.entrySet().iterator(); itr.hasNext();) {
            Map.Entry instantiator = (Map.Entry) itr.next();
            Integer id = (Integer) instantiator.getKey();
            ArrayList instantiatorArguments = (ArrayList) instantiator.getValue();
            InternalInstantiator.register((String) instantiatorArguments.get(0),
                    (String) instantiatorArguments.get(1), id, false);
        }

        HashMap dataSerializersMap = DataSerializer.readHashMap(dis);
        for (Iterator itr = dataSerializersMap.entrySet().iterator(); itr.hasNext();) {
            Map.Entry dataSerializer = (Map.Entry) itr.next();
            Integer id = (Integer) dataSerializer.getKey();
            InternalDataSerializer.register((String) dataSerializer.getValue(), false, null, null, id);
        }
        HashMap<Integer, ArrayList<String>> dsToSupportedClassNames = DataSerializer.readHashMap(dis);
        InternalDataSerializer.updateSupportedClassesMap(dsToSupportedClassNames);
    } catch (IOException ex) {
        CancelCriterion stopper = this.system.getCancelCriterion();
        stopper.checkCancelInProgress(null);
        throw ex;
    } catch (ClassNotFoundException ex) {
        CancelCriterion stopper = this.system.getCancelCriterion();
        stopper.checkCancelInProgress(null);
        throw ex;
    }
    return sqs;
}

From source file:org.apache.hadoop.hbase.zookeeper.ZooKeeperWrapper.java

/**
 * Gets the statistics from the given server.
 *
 * @param server  The server to get the statistics from.
 * @param timeout  The socket timeout to use.
 * @return The array of response strings.
 * @throws IOException When the socket communication fails.
 *///from   www.j av a 2  s  .c o m
public String[] getServerStats(String server, int timeout) throws IOException {
    String[] sp = server.split(":");
    String host = sp[0];
    int port = sp.length > 1 ? Integer.parseInt(sp[1]) : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;

    Socket socket = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(host, port);
    socket.connect(sockAddr, timeout);
    socket.setSoTimeout(timeout);

    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.println("stat");
    out.flush();

    ArrayList<String> res = new ArrayList<String>();
    while (true) {
        String line = in.readLine();
        if (line != null)
            res.add(line);
        else
            break;
    }
    socket.close();
    return res.toArray(new String[res.size()]);
}

From source file:catalina.core.StandardServer.java

/**
 * Wait until a proper shutdown command is received, then return.
 *//*  w  ww  . jav a  2 s.  com*/
public void await() {

    // Set up a server socket to wait on
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
    } catch (IOException e) {
        System.err.println("StandardServer.await: create[" + port + "]: " + e);
        e.printStackTrace();
        System.exit(1);
    }

    // Loop waiting for a connection and a valid command
    while (true) {

        // Wait for the next connection
        Socket socket = null;
        InputStream stream = null;
        try {
            socket = serverSocket.accept();
            socket.setSoTimeout(10 * 1000); // Ten seconds
            stream = socket.getInputStream();
        } catch (AccessControlException ace) {
            System.err.println("StandardServer.accept security exception: " + ace.getMessage());
            continue;
        } catch (IOException e) {
            System.err.println("StandardServer.await: accept: " + e);
            e.printStackTrace();
            System.exit(1);
        }

        // Read a set of characters from the socket
        StringBuffer command = new StringBuffer();
        int expected = 1024; // Cut off to avoid DoS attack
        while (expected < shutdown.length()) {
            if (random == null)
                random = new Random(System.currentTimeMillis());
            expected += (random.nextInt() % 1024);
        }
        while (expected > 0) {
            int ch = -1;
            try {
                ch = stream.read();
            } catch (IOException e) {
                System.err.println("StandardServer.await: read: " + e);
                e.printStackTrace();
                ch = -1;
            }
            if (ch < 32) // Control character or EOF terminates loop
                break;
            command.append((char) ch);
            expected--;
        }

        // Close the socket now that we are done with it
        try {
            socket.close();
        } catch (IOException e) {
            ;
        }

        // Match against our command string
        boolean match = command.toString().equals(shutdown);
        if (match) {
            break;
        } else
            System.err.println("StandardServer.await: Invalid command '" + command.toString() + "' received");

    }

    // Close the server socket and return
    try {
        serverSocket.close();
    } catch (IOException e) {
        ;
    }

}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * HandShake Constructor used by server side connection
 *//* w w  w  .j  a  va2  s .  com*/
public HandShake(Socket sock, int timeout, DistributedSystem sys, Version clientVersion,
        CommunicationMode communicationMode, SecurityService securityService)
        throws IOException, AuthenticationRequiredException {

    this.clientVersion = clientVersion;
    this.system = sys;
    this.securityService = securityService;

    {
        int soTimeout = -1;
        try {
            soTimeout = sock.getSoTimeout();
            sock.setSoTimeout(timeout);
            InputStream is = sock.getInputStream();
            int valRead = is.read();
            // this.code = (byte)is.read();
            if (valRead == -1) {
                throw new EOFException(
                        LocalizedStrings.HandShake_HANDSHAKE_EOF_REACHED_BEFORE_CLIENT_CODE_COULD_BE_READ
                                .toLocalizedString());
            }
            this.code = (byte) valRead;
            if (this.code != REPLY_OK) {
                throw new IOException(
                        LocalizedStrings.HandShake_HANDSHAKE_REPLY_CODE_IS_NOT_OK.toLocalizedString());
            }
            try {
                DataInputStream dis = new DataInputStream(is);
                DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
                this.clientReadTimeout = dis.readInt();
                if (clientVersion.compareTo(Version.CURRENT) < 0) {
                    // versioned streams allow object serialization code to deal with older clients
                    dis = new VersionedDataInputStream(dis, clientVersion);
                    dos = new VersionedDataOutputStream(dos, clientVersion);
                }
                this.id = ClientProxyMembershipID.readCanonicalized(dis);
                // Note: credentials should always be the last piece in handshake for
                // Diffie-Hellman key exchange to work
                if (clientVersion.compareTo(Version.GFE_603) >= 0) {
                    setOverrides(new byte[] { dis.readByte() });
                } else {
                    setClientConflation(dis.readByte());
                }
                // Hitesh
                if (this.clientVersion.compareTo(Version.GFE_65) < 0 || communicationMode.isWAN()) {
                    this.credentials = readCredentials(dis, dos, sys, this.securityService);
                } else {
                    this.credentials = this.readCredential(dis, dos, sys);
                }
            } catch (IOException ioe) {
                this.code = -2;
                throw ioe;
            } catch (ClassNotFoundException cnfe) {
                this.code = -3;
                throw new IOException(
                        LocalizedStrings.HandShake_CLIENTPROXYMEMBERSHIPID_CLASS_COULD_NOT_BE_FOUND_WHILE_DESERIALIZING_THE_OBJECT
                                .toLocalizedString());
            }
        } finally {
            if (soTimeout != -1) {
                try {
                    sock.setSoTimeout(soTimeout);
                } catch (IOException ignore) {
                }
            }
        }
    }
}