Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

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

Prototype

public Socket() 

Source Link

Document

Creates an unconnected Socket.

Usage

From source file:com.github.wasiqb.coteafs.appium.service.AppiumServer.java

/**
 * @author wasiq.bhamla/*from www  .ja v  a2s.co  m*/
 * @since 13-Apr-2017 5:30:12 PM
 * @return isRunning
 */
public boolean isRunning() {
    if (this.setting.isCloud())
        return true;
    if (!this.setting.isExternal()) {
        log.trace("Checking if Appium Service is running...");
        return this.service.isRunning();
    }
    final SocketAddress addr = new InetSocketAddress(this.setting.getHost(), this.setting.getPort());
    try (Socket socket = new Socket()) {
        socket.connect(addr, 2000);
    } catch (final IOException e) {
        fail(AppiumServerNotRunningError.class, "Error connecting to Server...", e);
    }
    return true;
}

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

/**
 * Will load the plugin list from munin-node
 *///from  w w w.  j  av a 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:ed.net.httpclient.HttpConnection.java

public void go() throws IOException {

    boolean doIWantKeepAlive = true;

    _lastAccess = System.currentTimeMillis();

    if (_sock == null) {
        int port = _currentUrl.getPort();
        if (port < 0) {
            if (_currentUrl.getProtocol().equalsIgnoreCase("https"))
                port = 443;/*from  w ww .j av a  2  s .  co  m*/
            else
                port = 80;
        }

        if (DEBUG)
            LOGGER.debug("creating new socket to " + _key.getAddress());
        InetSocketAddress isa = new InetSocketAddress(_key.getAddress(), port);

        _sock = new Socket();

        _sock.connect(isa, _timeout);
        _sock.setSoTimeout(_timeout * 5);

        if (_currentUrl.getProtocol().equalsIgnoreCase("https")) {
            try {
                _sock = getDefaultSSLSocketFactory().createSocket(_sock, _currentUrl.getHost(), port, true);
                _usingSLL = true;
                doIWantKeepAlive = false; // don't trust this with SSL yet
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        if (_sock == null) {
            RuntimeException re = new RuntimeException("_sock can't be null here.  close called? " + _closed);
            re.fillInStackTrace();
            LOGGER.error("weird...", re);
            throw re;
        }

        if (_sock.getInputStream() == null)
            throw new RuntimeException("_sock.getInputStream() is null!!"); // should never happen, should be IOException
        _in = new BufferedInputStream(_sock.getInputStream());
    }

    StringBuilder buf = new StringBuilder();

    // First Line
    buf.append(_requestMethod).append(" ");
    String f = _currentUrl.getFile();

    if (f == null || f.trim().length() == 0)
        f = "/";
    buf.append(f.replace(' ', '+'));
    buf.append(" HTTP/1.1\r\n");

    for (Iterator i = _headers.keySet().iterator(); i.hasNext();) {
        String name = (String) i.next();
        String value = String.valueOf(_headers.get(name));

        buf.append(name).append(": ").append(value).append("\r\n");

        if (name.equalsIgnoreCase("connection") && value.equalsIgnoreCase("close"))
            doIWantKeepAlive = false;
    }
    buf.append("\r\n");

    String headerString = buf.toString();
    if (DEBUG)
        System.out.println(headerString);
    try {
        _sock.getOutputStream().write(headerString.getBytes());

        if (_postData != null)
            _sock.getOutputStream().write(_postData);

        int timeoutSeconds = 60;

        _timeOutKeeper.add(this, timeoutSeconds);

        _in.mark(10);
        if (_in.read() < 0)
            throw new IOException("stream closed on be ya bastard");
        _in.reset();
        if (DEBUG)
            System.out.println("sent header and seems to be ok");
    } catch (IOException ioe) {
        if (_keepAlive) {
            if (DEBUG)
                LOGGER.debug("trying again");
            // if we previously had a keep alive connection, maybe it died, so rety
            _keepAlive = false;
            _key.reset();
            close();
            reset(_currentUrl, false);
            go();
            return;
        }
        throw ioe;
    }

    // need to look for end of headers

    byte currentLine[] = new byte[2048];
    int idx = 0;
    boolean gotStatus = false;
    boolean chunked = false;
    int lineNumber = 0;
    boolean previousSlashR = false;
    while (true) {
        if (idx >= currentLine.length) {
            byte temp[] = new byte[currentLine.length * 2];
            for (int i = 0; i < currentLine.length; i++)
                temp[i] = currentLine[i];
            currentLine = temp;
        }
        int t = -1;
        try {
            t = _in.read();
        } catch (NullPointerException e) {
            throw new IOException("input stream was closed while parsing headers");
        }

        if (t < 0)
            throw new IOException("input stream got closed while parsing headers");

        currentLine[idx] = (byte) t;
        if (currentLine[idx] == '\r') {
            currentLine[idx] = ' ';
        } else if (currentLine[idx] == '\n') {
            String line = new String(currentLine, 0, idx).trim();
            if (DEBUG)
                System.out.println(line);
            if (line.length() == 0) {
                if (DEBUG)
                    System.out.println("rc:" + _rc);
                if (_rc == 100) {
                    if (DEBUG)
                        System.out.println("got Continue");
                    gotStatus = false;
                    lineNumber = 0;
                    idx = 0;
                    continue;
                }
                break;
            }

            if (!gotStatus) {
                gotStatus = true;

                Matcher m = STATUS_PATTERN.matcher(line);
                if (!m.find())
                    throw new IOException("invalid status line:" + line);

                _httpVersion = Double.parseDouble(m.group(1));
                _rc = Integer.parseInt(m.group(2));
                _message = m.group(3);

                _responseHeaderFields[0] = line;
            } else {
                int colon = line.indexOf(":");
                if (colon < 0) {
                    //throw new IOException("invalid header[" + line + "]");
                    LOGGER.error("weird error : {" + line
                            + "} does not have a colon, using the whole line as the value and SWBadHeader as the key");
                    line = "SWBadHeader:" + line;
                    colon = line.indexOf(":");
                }
                String name = line.substring(0, colon).trim();
                String value = line.substring(colon + 1).trim();

                _responseHeaders.put(name, value);

                if (name.equalsIgnoreCase("Transfer-Encoding") && value.equalsIgnoreCase("chunked"))
                    chunked = true;

                if (lineNumber >= (_responseHeaderFields.length - 2)) {
                    // need to enlarge header...

                    String keys[] = new String[_responseHeaderFieldKeys.length * 2];
                    String values[] = new String[_responseHeaderFields.length * 2];

                    for (int i = 0; i < lineNumber; i++) {
                        keys[i] = _responseHeaderFieldKeys[i];
                        values[i] = _responseHeaderFields[i];
                    }

                    _responseHeaderFieldKeys = keys;
                    _responseHeaderFields = values;
                }

                _responseHeaderFieldKeys[lineNumber] = name;
                _responseHeaderFields[lineNumber] = value;

            }
            if (DEBUG)
                System.out.println(
                        "\t" + _responseHeaderFieldKeys[lineNumber] + ":" + _responseHeaderFields[lineNumber]);
            lineNumber++;
            idx = -1;
        }
        idx++;
    }

    _responseHeaderFieldKeys[lineNumber] = null;
    _responseHeaderFields[lineNumber] = null;

    // TODO: obey max? etc...?

    _keepAlive = false;
    if (doIWantKeepAlive && (chunked || getContentLength() >= 0 || _rc == 304)) {
        String hf = null;

        if (hf == null)
            hf = "Connection";

        if (_httpVersion > 1) {
            _keepAlive = getHeaderField(hf) == null || getHeaderField(hf).toLowerCase().indexOf("close") < 0;
        } else {
            _keepAlive = getHeaderField(hf) != null
                    && getHeaderField(hf).toLowerCase().indexOf("keep-alive") >= 0;
        }
    }

    if (DEBUG)
        System.out.println("_keepAlive=" + _keepAlive);

    /* DM: TODO --------------------------------
       fix keepalive it's not set if no content length
    */

    if (!_requestMethod.equals("HEAD")) {
        if (chunked) {
            _userIn = new ChunkedInputStream(_in);
        } else if (_keepAlive || _usingSLL) {
            _userIn = new MaxReadInputStream(_in, getContentLength());
        } else {
            _userIn = _in; // just pass throgh
        }
    }

    _lastAccess = System.currentTimeMillis();

}

From source file:com.legstar.csok.client.CicsSocket.java

/**
 * Connect to a CICS IBM Listener passing credentials and a client initial
 * message. The reply must be an acknowldgement otherwise it is an error
 * message returned from the host.//from  w ww . j  a v a2s  .c  o  m
 * 
 * @param cicsPassword credentials for security exist
 * @throws ConnectionException if connection fails
 */
public void connect(final String cicsPassword) throws ConnectionException {
    String password;
    if (_log.isDebugEnabled()) {
        _log.debug("Connection:" + mConnectionID + " Attempting connection. Host:"
                + mCicsSocketEndpoint.toString());
    }
    try {
        mClientSocket = new Socket();
        mClientSocket
                .connect(
                        new InetSocketAddress(InetAddress.getByName(mCicsSocketEndpoint.getHostIPAddress()),
                                mCicsSocketEndpoint.getHostIPPort()),
                        getCicsSocketEndpoint().getConnectTimeout());
        mClientSocket.setSoTimeout(getCicsSocketEndpoint().getReceiveTimeout());
        /*
         * In order to optimize memory allocation, this client program sends
         * message parts to server in 2 different sends. If we don t disable
         * Nagle, there is an unacceptable delay in the server
         * acknowldgement of the first send.
         */
        mClientSocket.setTcpNoDelay(true);

        /*
         * In an RPC mode, there is no reason to wait for additional data
         * when a close sequence is initiated (we wouldn't know what to do
         * with that data anyway.
         */
        mClientSocket.setSoLinger(false, 0);

        /* If a password is not passed, use the one from configuration */
        if (cicsPassword == null || cicsPassword.length() == 0) {
            password = mCicsSocketEndpoint.getHostPassword();
        } else {
            password = cicsPassword;
        }

        OutputStream out = mClientSocket.getOutputStream();
        out.write(formatCIM(mCicsSocketEndpoint.getHostUserID(), password, mConnectionID,
                mCicsSocketEndpoint.isHostTraceMode(), mHostProtocolCharset));
        recvConnectionAck();
        _isOpen = true;
        _lastUsedTime = System.currentTimeMillis();
    } catch (UnknownHostException e) {
        throw (new ConnectionException(e));
    } catch (IOException e) {
        throw (new ConnectionException(e));
    } catch (RequestException e) {
        throw (new ConnectionException(e));
    }
    if (_log.isDebugEnabled()) {
        _log.debug("Connection:" + mConnectionID + " Connected.");
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            executor.execute(command, resultHandler);

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

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

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

            response.setResponseData(outputStream.toString());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            executor.execute(command, resultHandler);

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

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

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

            response.setResponseData(outputStream.toString());

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

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

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

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

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

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

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

    return response;
}

From source file:io.undertow.server.handlers.ReceiverTestCase.java

@Test
public void testAsyncReceiveWholeBytesFailed() throws Exception {
    EXCEPTIONS.clear();//from   w  w  w .j a va 2s. co m
    Socket socket = new Socket();
    socket.connect(DefaultServer.getDefaultServerAddress());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; ++i) {
        sb.append("hello world\r\n");
    }
    //send a large request that is too small, then kill the socket
    String request = "POST /fullbytes HTTP/1.1\r\nHost:localhost\r\nContent-Length:" + sb.length() + 100
            + "\r\n\r\n" + sb.toString();
    OutputStream outputStream = socket.getOutputStream();

    outputStream.write(request.getBytes("US-ASCII"));
    socket.getInputStream().close();
    outputStream.close();

    IOException e = EXCEPTIONS.poll(2, TimeUnit.SECONDS);
    Assert.assertNotNull(e);

}

From source file:tap.Tap.java

/**
 * Usage:<BR> FIXME?/*www .j  a va 2  s . c om*/
 *       java votebox.Tap [serial] [report address] [port]
 *
 * @param args      arguments to be used
 *
 * @throws RuntimeException if there is an issue parsing values, the port used is bad,
 *                          or there is an interruption in the process
 */
public static void main(String[] args) {

    IAuditoriumParams params = new AuditoriumParams("tap.conf");

    System.out.println(params.getReportAddress());

    String reportAddr;

    int serial;
    int port;
    String launchCode;

    /* See if there isn't a full argument set */
    if (args.length != 4) {

        int p = 0;

        /* Assign the default serial */
        serial = params.getDefaultSerialNumber();

        /* If the serial is still bad... */
        if (serial == -1) {

            /* Try the first of the given arguments */
            try {
                serial = Integer.parseInt(args[p]);
                p++;
            } catch (Exception e) {
                throw new RuntimeException(
                        "usage: Tap [serial] [report address] [port]\nExpected valid serial.");
            }
        }

        /* Assign the report address */
        reportAddr = params.getReportAddress();

        /* If no valid address... */
        if (reportAddr.length() == 0) {

            /* Try one of the given arguments (first or second, depending) */
            try {
                reportAddr = args[p];
                p++;
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]");
            }
        }

        /* Assign the port */
        //port = params.getPort();
        port = Integer.parseInt(args[p]);

        /* If the port is still bad... */
        if (port == -1) {

            /* Try one of the given arguments (first, second, or third, depending) */
            try {
                port = Integer.parseInt(args[p]);
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]\nExpected valid port.");
            }
        }

        launchCode = "0000000000";
    }

    /* If there is a full argument set... */
    else {

        /* Try to load up the args */
        try {
            serial = Integer.parseInt(args[0]);
            reportAddr = args[1];
            port = Integer.parseInt(args[2]);
            launchCode = args[3];
        } catch (Exception e) {
            throw new RuntimeException("usage: Tap [serial] [report address] [port]");
        }
    }

    try {

        /* Create a new socket address */
        System.out.println(reportAddr + port);
        InetSocketAddress addr = new InetSocketAddress(reportAddr, port);

        /* Loop until an exception or tap is started */
        while (true) {

            try {

                /* Try to establish a socket connection */
                Socket localCon = new Socket();
                localCon.connect(addr);

                /* Start the tap */
                (new Tap(serial, localCon.getOutputStream(), launchCode, params)).start();
                System.out.println("Connection successful to " + addr);
                break;
            } catch (IOException e) { /* If no good, retry */
                System.out.println("Connection failed: " + e.getMessage());
                System.out.println("Retry in 5 seconds...");
                Thread.sleep(5000);
            }
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "usage: Tap [serial] [report address] [port]; where port is between 1 and 65335 & [serial] is a positive integer",
                e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    /* TEST CODE */

    testMethod();

    /* END TEST CODE */

}

From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java

/**
 * @since 4.1//from  w w w  .  ja va2  s .c o m
 */
@Override
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock = socket != null ? socket : new Socket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException(
                "Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out");
    }
    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        sslsock = (SSLSocket) getSocketFactory().createSocket(sock, remoteAddress.getHostName(),
                remoteAddress.getPort(), true);
        sslsock = enableSocket(sslsock);
    }
    // do we need it? trust all hosts
    //      if( getHostnameVerifier() != null )
    //      {
    //         try
    //         {
    //            getHostnameVerifier().verify( remoteAddress.getHostName(), sslsock );
    //            // verifyHostName() didn't blowup - good!
    //         }
    //         catch( IOException iox )
    //         {
    //            // close the socket before re-throwing the exception
    //            try
    //            {
    //               sslsock.close();
    //            }
    //            catch( Exception x )
    //            { /* ignore */
    //            }
    //            throw iox;
    //         }
    //      }
    return sslsock;
}

From source file:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Determine if an address is available.
 *///  ww w .  j ava2s.c  o m
public static boolean isAlive(String ips, int port) {
    if (logger.isDebugEnabled())
        logger.debug("trying to reach: " + ips + ":" + port);
    try {
        if ("".equals(ips))
            ips = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
        throw new StoreException(
                "can not determine local adapter, but there is another node, which would need to be contacted.",
                e);
    }
    StringTokenizer tokens = new StringTokenizer(ips, ",");
    while (tokens.hasMoreTokens()) {
        String ip = tokens.nextToken();
        if (logger.isDebugEnabled())
            logger.debug("determining whether '" + ip + ":" + port + "' is alive...");
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), SOCKET_CONNECT_TIMEOUT);
            socket.close();
            return true; // Success, so return true
        } catch (Exception e) {
            logger.debug("unreachable node at '" + ip + ":" + port + ", " + e.getMessage());
        }
    }
    logger.debug("could not reach any of the ips given for node");
    return false;
}

From source file:com.msopentech.thali.utilities.universal.HttpKeySocksProxyClientConnOperator.java

@Override
public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local,
        final HttpContext context, final HttpParams params) throws IOException {
    Socket socket = null;/*from  www.  j  a va  2 s . c o  m*/
    Socket sslSocket = null;
    try {
        if (conn == null || target == null || params == null) {
            throw new IllegalArgumentException("Required argument may not be null");
        }
        if (conn.isOpen()) {
            throw new IllegalStateException("Connection must not be open");
        }

        // The original NetCipher code uses a SchemeSocketFactory class that isn't supported by the version
        // of Apache that ships standard with Android. It also doesn't support the layered socket factory
        // interface either. We work around this later on but for now we just get our HttpKeySSLSocketFactory
        Scheme scheme = schemeRegistry.getScheme(target.getSchemeName());
        HttpKeySSLSocketFactory httpKeySSLSocketFactory = (HttpKeySSLSocketFactory) scheme.getSocketFactory();

        int port = scheme.resolvePort(target.getPort());
        String host = target.getHostName();

        // Perform explicit SOCKS4a connection request. SOCKS4a supports remote host name resolution
        // (i.e., Tor resolves the hostname, which may be an onion address).
        // The Android (Apache Harmony) Socket class appears to support only SOCKS4 and throws an
        // exception on an address created using INetAddress.createUnresolved() -- so the typical
        // technique for using Java SOCKS4a/5 doesn't appear to work on Android:
        // https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/net/PlainSocketImpl.java
        // See also: http://www.mit.edu/~foley/TinFoil/src/tinfoil/TorLib.java, for a similar implementation

        // From http://en.wikipedia.org/wiki/SOCKS#SOCKS4a:
        //
        // field 1: SOCKS version number, 1 byte, must be 0x04 for this version
        // field 2: command code, 1 byte:
        //     0x01 = establish a TCP/IP stream connection
        //     0x02 = establish a TCP/IP port binding
        // field 3: network byte order port number, 2 bytes
        // field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00
        // field 5: the user ID string, variable length, terminated with a null (0x00)
        // field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00)

        socket = new Socket();
        conn.opening(socket, target);
        socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        socket.connect(proxy.address(), CONNECT_TIMEOUT_MILLISECONDS);

        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        outputStream.write((byte) 0x04);
        outputStream.write((byte) 0x01);
        outputStream.writeShort((short) port);
        outputStream.writeInt(0x01);
        outputStream.write((byte) 0x00);
        outputStream.write(host.getBytes());
        outputStream.write((byte) 0x00);

        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        if (inputStream.readByte() != (byte) 0x00 || inputStream.readByte() != (byte) 0x5a) {
            throw new IOException("SOCKS4a connect failed");
        }
        inputStream.readShort();
        inputStream.readInt();

        // In the NetCipher code we cast to SchemeLayeredSocketFactory and call createLayeredSocket which amongst
        // other things takes 'params' as an argument. But none of this is supported in Android. When I looked in
        // Java at what createLayeredSocket was actually doing it was just calling createSocket with exactly the
        // arguments used below (it ignored params completely). So we should be good.
        sslSocket = ((HttpKeySSLSocketFactory) httpKeySSLSocketFactory).createSocket(socket, host, port, true);
        conn.opening(sslSocket, target);
        sslSocket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        prepareSocket(sslSocket, context, params);
        conn.openCompleted(httpKeySSLSocketFactory.isSecure(sslSocket), params);
        // TODO: clarify which connection throws java.net.SocketTimeoutException?
    } catch (IOException e) {
        try {
            if (sslSocket != null) {
                sslSocket.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ioe) {
        }
        throw e;
    }
}