Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:com.oakesville.mythling.util.MediaStreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null)
        return;//from ww  w .j a  v  a2  s.  c  o  m

    Log.d(TAG, "Proxy processing");

    HttpResponse realResponse = download();
    if (realResponse == null)
        return;

    Log.d(TAG, "Proxy downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    Log.d(TAG, "Proxy reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());
    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        // TODO: this is disabled until it is made optional
        //            if (h.getName().equals("Content-Type") && proxyInfo.isMpeg())
        //                httpString.append(h.getName()).append(": ").append("video/mpeg").append("\n");
        //            else
        Log.d(TAG, "  header->" + h.getName() + ": " + h.getValue());
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // start streaming content
        byte[] buff = new byte[1024 * 50];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (SocketException ex) {
        Log.e(TAG, "SocketException writing to client", ex);
        // avoid trying to close (because close() hangs in this situation, and for some reason
        // libvlc breaks the first connection when attempting to write, but second succeeds)
        data = null;
    } finally {
        if (data != null)
            data.close();
        client.close();
    }
}

From source file:com.piusvelte.taplock.server.ConnectionThread.java

@SuppressWarnings("unchecked")
@Override/*from  w  w w  . ja v a2 s .com*/
public void run() {
    TapLockServer.writeLog("ConnectionThread started");
    // retrieve the local Bluetooth device object
    // setup the server to listen for connection
    try {
        local = LocalDevice.getLocalDevice();
        local.setDiscoverable(DiscoveryAgent.GIAC);
        //         String url = "btspp://localhost:" + mRemoteAuthServerUUID.toString() + ";master=false;encrypt=false;authenticate=false;name=" + sSPD;
        String url = "btspp://localhost:" + sTapLockUUID.toString() + ";name=" + sSPD;
        notifier = (StreamConnectionNotifier) Connector.open(url);
    } catch (Exception e) {
        // no bluetooth present
        TapLockServer.writeLog("notifier init: " + e.getMessage());
        TapLockServer.shutdown();
        return;
    }
    JSONParser jsonParser = new JSONParser();
    while (notifier != null) {
        TapLockServer.writeLog("waiting for connection...");
        try {
            btConnection = notifier.acceptAndOpen();
        } catch (IOException e) {
            TapLockServer.writeLog("notifier.acceptAndOpen: " + e.getMessage());
            btConnection = null;
        }
        if (btConnection != null) {
            TapLockServer.writeLog("new connection...");
            try {
                btInStream = btConnection.openInputStream();
                btOutStream = btConnection.openOutputStream();
            } catch (IOException e) {
                TapLockServer.writeLog("inStream and outStream open: " + e.getMessage());
            }
            if ((btInStream != null) && (btOutStream != null)) {
                // send the challenge
                String challenge = Long.toString(System.currentTimeMillis());
                TapLockServer.writeLog("init challenge: " + challenge);
                JSONObject responseJObj = new JSONObject();
                responseJObj.put(TapLockServer.PARAM_CHALLENGE, challenge);
                String responseStr = responseJObj.toJSONString();
                try {
                    btOutStream.write(responseStr.getBytes());
                } catch (IOException e) {
                    TapLockServer.writeLog("outStream.write: " + e.getMessage());
                }
                // prepare to receive data
                byte[] btBuffer = new byte[1024];
                int btReadBytes = -1;
                try {
                    btReadBytes = btInStream.read(btBuffer);
                } catch (IOException e) {
                    TapLockServer.writeLog("inStream.read: " + e.getMessage());
                }
                while (btReadBytes != -1) {
                    responseJObj.clear();
                    String requestStr = new String(btBuffer, 0, btReadBytes);
                    TapLockServer.writeLog("request: " + requestStr);
                    JSONObject requestJObj = null;
                    try {
                        requestJObj = (JSONObject) jsonParser.parse(requestStr);
                    } catch (ParseException e) {
                        TapLockServer.writeLog("jsonParser.parse: " + e.getMessage());
                    }
                    if (requestJObj != null) {
                        if ((requestJObj != null) && requestJObj.containsKey(TapLockServer.PARAM_ACTION)
                                && requestJObj.containsKey(TapLockServer.PARAM_HMAC)) {
                            String requestAction = (String) requestJObj.get(TapLockServer.PARAM_ACTION);
                            TapLockServer.writeLog("action: " + requestAction);
                            String requestPassphrase = (String) requestJObj.get(TapLockServer.PARAM_PASSPHRASE);
                            if (requestPassphrase == null)
                                requestPassphrase = "";
                            String requestHMAC = (String) requestJObj.get(TapLockServer.PARAM_HMAC);
                            String validHMAC = null;
                            try {
                                validHMAC = TapLockServer.getHashString(challenge + TapLockServer.sPassphrase
                                        + requestAction + requestPassphrase);
                            } catch (NoSuchAlgorithmException e) {
                                TapLockServer.writeLog("getHashString: " + e.getMessage());
                            } catch (UnsupportedEncodingException e) {
                                TapLockServer.writeLog("getHashString: " + e.getMessage());
                            }
                            if (requestHMAC.equals(validHMAC)) {
                                if (TapLockServer.ACTION_PASSPHRASE.equals(requestAction))
                                    TapLockServer.setPassphrase(requestPassphrase);
                                else {
                                    if (TapLockServer.OS == TapLockServer.OS_WIN) {
                                        if (TapLockServer.ACTION_LOCK.equals(requestAction))
                                            runCommand("rundll32.exe user32.dll, LockWorkStation");
                                        else {
                                            // either unlock or toggle
                                            String password = "";
                                            Properties prop = new Properties();
                                            try {
                                                prop.load(new FileInputStream(TapLockServer.sProperties));
                                                if (prop.containsKey(TapLockServer.sPasswordKey))
                                                    password = TapLockServer.decryptString(
                                                            prop.getProperty(TapLockServer.sPasswordKey));
                                            } catch (FileNotFoundException e) {
                                                TapLockServer.writeLog("prop load: " + e.getMessage());
                                            } catch (IOException e) {
                                                TapLockServer.writeLog("prop load: " + e.getMessage());
                                            }
                                            Socket cpSocket = null;
                                            try {
                                                cpSocket = new Socket(TapLockServer.S_LOCALHOST,
                                                        TapLockServer.SERVER_PORT);
                                            } catch (UnknownHostException e) {
                                                TapLockServer.writeLog("socket: " + e.getMessage());
                                            } catch (IOException e) {
                                                TapLockServer.writeLog("socket: " + e.getMessage());
                                            }
                                            if (cpSocket != null) {
                                                InputStream cpInStream = null;
                                                OutputStream cpOutStream = null;
                                                try {
                                                    cpInStream = cpSocket.getInputStream();
                                                    cpOutStream = cpSocket.getOutputStream();
                                                } catch (IOException e) {
                                                    TapLockServer.writeLog("in/out stream: " + e.getMessage());
                                                }
                                                if ((cpInStream != null) && (cpOutStream != null)) {
                                                    // get the version
                                                    byte[] cpBuffer = new byte[1];
                                                    int cpReadBytes = -1;
                                                    try {
                                                        cpReadBytes = cpInStream.read(cpBuffer);
                                                    } catch (IOException e) {
                                                        TapLockServer
                                                                .writeLog("instream read: " + e.getMessage());
                                                    }
                                                    if (cpReadBytes != -1) {
                                                        TapLockServer.writeLog("credential provider version: "
                                                                + new String(cpBuffer, 0, cpReadBytes));
                                                        // pack the credentials
                                                        byte[] usernameBytes = System.getProperty("user.name")
                                                                .getBytes(Charset.forName("UTF-8"));
                                                        byte[] passwordBytes = password
                                                                .getBytes(Charset.forName("UTF-8"));
                                                        byte[] credentialsBuf = new byte[TapLockServer.S_CREDBUF];
                                                        for (int i = 0, l = usernameBytes.length; (i < l)
                                                                && (i < TapLockServer.S_USERBUF); i++)
                                                            credentialsBuf[i] = usernameBytes[i];
                                                        for (int i = 0, l = passwordBytes.length; (i < l)
                                                                && (i < TapLockServer.S_PASSBUF); i++)
                                                            credentialsBuf[i
                                                                    + TapLockServer.S_USERBUF] = passwordBytes[i];
                                                        try {
                                                            cpOutStream.write(credentialsBuf);
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "cpOutStream write: " + e.getMessage());
                                                        }
                                                        cpReadBytes = -1;
                                                        try {
                                                            cpReadBytes = cpInStream.read(credentialsBuf);
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "cpInStream read: " + e.getMessage());
                                                        }
                                                        // the socket should return "0" if no errors
                                                        if (cpReadBytes != -1) {
                                                            String cpResult = new String(credentialsBuf, 0,
                                                                    cpReadBytes);
                                                            TapLockServer.writeLog(
                                                                    "credential provider result: " + cpResult);
                                                            if (!TapLockServer.CREDENTIAL_PROVIDER_SUCCESS
                                                                    .equals(cpResult))
                                                                responseJObj.put(TapLockServer.PARAM_ERROR,
                                                                        "Authentication error, is the Windows password set in Tap Lock Server?");
                                                        }
                                                        try {
                                                            cpOutStream.close();
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "output close: " + e.getMessage());
                                                        }
                                                        try {
                                                            cpInStream.close();
                                                        } catch (IOException e) {
                                                            TapLockServer
                                                                    .writeLog("in close: " + e.getMessage());
                                                        }
                                                        try {
                                                            cpSocket.close();
                                                        } catch (IOException e) {
                                                            TapLockServer.writeLog(
                                                                    "socket close: " + e.getMessage());
                                                        }
                                                    }
                                                }
                                            } else
                                                runCommand("rundll32.exe user32.dll, LockWorkStation");
                                        }
                                    } else if (TapLockServer.OS == TapLockServer.OS_NIX) {
                                        if (TapLockServer.ACTION_TOGGLE.equals(requestAction))
                                            requestAction = TapLockServer.getToggleAction();
                                        String command = null;
                                        if (TapLockServer.ACTION_LOCK.equals(requestAction))
                                            command = "gnome-screensaver-command -a";
                                        else if (TapLockServer.ACTION_UNLOCK.equals(requestAction))
                                            command = "gnome-screensaver-command -d";
                                        if (command != null)
                                            runCommand(command);
                                    }
                                }
                            } else {
                                TapLockServer.writeLog("authentication failed");
                                responseJObj.put(TapLockServer.PARAM_ERROR, "authentication failed");
                            }
                        } else {
                            TapLockServer.writeLog("invalid request");
                            responseJObj.put(TapLockServer.PARAM_ERROR, "invalid request");
                        }
                    } else {
                        TapLockServer.writeLog("failed to parse request");
                        responseJObj.put(TapLockServer.PARAM_ERROR, "failed to parse request");
                    }
                    // send the new challenge
                    challenge = Long.toString(System.currentTimeMillis());
                    TapLockServer.writeLog("next challenge: " + challenge);
                    responseJObj.put(TapLockServer.PARAM_CHALLENGE, challenge);
                    responseStr = responseJObj.toJSONString();
                    try {
                        btOutStream.write(responseStr.getBytes());
                    } catch (IOException e) {
                        TapLockServer.writeLog("outStream.write: " + e.getMessage());
                    }
                    try {
                        btReadBytes = btInStream.read(btBuffer);
                    } catch (IOException e) {
                        TapLockServer.writeLog("inStream.read: " + e.getMessage());
                    }
                }
                if (btInStream != null) {
                    try {
                        btInStream.close();
                    } catch (IOException e) {
                        TapLockServer.writeLog("inStream.close: " + e.getMessage());
                    }
                }
                if (btOutStream != null) {
                    try {
                        btOutStream.close();
                    } catch (IOException e) {
                        TapLockServer.writeLog("outStream.close: " + e.getMessage());
                    }
                }
            }
            if (btConnection != null) {
                try {
                    btConnection.close();
                } catch (IOException e) {
                    TapLockServer.writeLog("connection.close: " + e.getMessage());
                }
                btConnection = null;
            }
        }
    }
}

From source file:com.vendsy.bartsy.venue.BartsyApplication.java

public void printOrders(ArrayList<Order> addedOrders) {

    String ip = Utilities.loadPref(this, R.string.config_printer_ip, null);

    if (ip == null) {
        Log.e(TAG, "Printer IP address not configured");
        return;/*from w  w  w . j  a  va 2 s . c o m*/
    }

    try {
        for (Order order : addedOrders) {
            Socket sock = new Socket(ip, 9100);
            PrintWriter oStream = new PrintWriter(sock.getOutputStream());
            order.println(oStream);
            oStream.print("\n\n\n");
            oStream.close();
            sock.close();
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
        Log.e(TAG, "Unknown host");
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(TAG, "I/O error");
    }
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

public void run() {
    long duration, starttime = System.currentTimeMillis();
    Socket destinationSocket = null;
    try {//from  ww w  .  j av  a  2  s .  co m
        BufferedOutputStream proxyClientStream = new BufferedOutputStream(proxySocket.getOutputStream());

        // read client request
        HttpRequest request = handleRequest(proxySocket);
        this.request = request;

        // send request to server
        //logger.debug("connecting to: " + request.getHost() + ":" + request.getPort());
        if (!((System.getProperty("http.proxyHost") == null)
                || System.getProperty("http.proxyHost").trim().equals(""))) {
            String proxyHost = System.getProperty("http.proxyHost");
            String proxyPortStr = System.getProperty("http.proxyPort");
            if (proxyPortStr == null || proxyPortStr.trim().equals("")) {
                proxyPortStr = "80";
            }
            int proxyPort = Integer.parseInt(proxyPortStr);
            //logger.debug("connecting via proxy: " + proxyHost + ":" + proxyPort);
            destinationSocket = new Socket(proxyHost, proxyPort);
        } else {
            destinationSocket = new Socket(request.getHost(), request.getPort());
        }
        OutputStream destinationOutputStream = destinationSocket.getOutputStream();
        destinationOutputStream.write(request.getRequest(), 0, request.getRequest().length);
        destinationOutputStream.flush();
        //logger.debug("request sent");

        // read response from server
        HttpResponse response = handleResponse(destinationSocket, proxyClientStream);
        this.response = response;
        destinationSocket.close();
        destinationSocket = null;

        // send response to client
        proxyClientStream.flush();
        proxySocket.close();
        proxySocket = null;
        duration = System.currentTimeMillis() - starttime;
        //logger.debug("duration: " + duration);
        String path = "http://" + request.getHost()
                + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
        proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path, starttime,
                request.getRequest(), this.response.getResponse(), duration);
    } catch (Exception e) {
        //logger.error("Error occurred: " + e.toString());
        duration = System.currentTimeMillis() - starttime;
        if (request != null) {
            String path = "http://" + request.getHost()
                    + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
            if (response != null && response.getResponse() != null) {
                proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path,
                        starttime, request.getRequest(), response.getResponse(), duration);
            } else {
                proxy.setWorkerResult(request.getMethod(), "XXX", path, starttime, request.getRequest(),
                        ("no response available - " + e.toString()).getBytes(), duration);
            }
        } else {
            proxy.setWorkerResult("---", "---", "---", starttime, e.toString().getBytes(),
                    "no response available".getBytes(), duration);
        }
        try {
            if (proxySocket != null) {
                closeSocket(proxySocket);
            }
        } finally {
            if (destinationSocket != null) {
                closeSocket(destinationSocket);
            }
        }
    }
}

From source file:gridool.util.xfer.RecievedFileWriter.java

public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket)
        throws IOException {
    final StopWatch sw = new StopWatch();
    if (!inChannel.isBlocking()) {
        inChannel.configureBlocking(true);
    }//from   w w w  .  j  a  va  2 s . c om

    InputStream in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    String fname = IOUtils.readString(dis);
    String dirPath = IOUtils.readString(dis);
    long len = dis.readLong();
    boolean append = dis.readBoolean();
    boolean ackRequired = dis.readBoolean();
    boolean hasAdditionalHeader = dis.readBoolean();
    if (hasAdditionalHeader) {
        readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired);
    }

    final File file;
    if (dirPath == null) {
        file = new File(baseDir, fname);
    } else {
        File dir = FileUtils.resolvePath(baseDir, dirPath);
        file = new File(dir, fname);
    }

    preFileAppend(file, append);
    final FileOutputStream dst = new FileOutputStream(file, append);
    final String fp = file.getAbsolutePath();
    final ReadWriteLock filelock = accquireLock(fp, locks);
    final FileChannel fileCh = dst.getChannel();
    final long startPos = file.length();
    try {
        NIOUtils.transferFully(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation?
    } finally {
        IOUtils.closeQuietly(fileCh, dst);
        releaseLock(fp, filelock, locks);
        postFileAppend(file, startPos, len);
    }
    if (ackRequired) {
        OutputStream out = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeLong(len);
        postAck(file, startPos, len);
    }

    if (LOG.isDebugEnabled()) {
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of "
                + len + " bytes from " + remoteAddr + " in " + sw.toString());
    }
}

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

private void connectResponseSocket(Socket responseSocket, StreamHandler streamHandler) throws IOException {
    String channelId = getChannelId();
    String channelName = getChannel().getName();
    int responsePort = NumberUtils
            .toInt(replacer.replaceValues(connectorProperties.getResponsePort(), channelId, channelName));
    SocketUtil.connectSocket(responseSocket,
            replacer.replaceValues(connectorProperties.getResponseAddress(), channelId, channelName),
            responsePort, timeout);/*w  ww  .  j  a  v  a 2s.c o  m*/
    initSocket(responseSocket);
    BufferedOutputStream bos = new BufferedOutputStream(responseSocket.getOutputStream(), bufferSize);
    streamHandler.setOutputStream(bos);
}

From source file:com.meh.IceProxy1.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;//from  ww  w . j  a  v  a2 s  . c  o  m
    }
    Log.d(tag, "processing");
    String url = request.getRequestLine().getUri();
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        return;
    }

    Log.d(tag, "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse dummyresponse = new BasicHttpResponse(line);
    dummyresponse.setHeaders(realResponse.getAllHeaders());

    Log.d(tag, "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(dummyresponse.getStatusLine().toString());
    httpString.append("\r\n");

    int icyInterval = -1;
    for (Header h : dummyresponse.getAllHeaders()) {
        if (ICY_INTERVAL_HEADER.equals(h.getName()))
            icyInterval = Integer.parseInt(h.getValue());
        else
            httpString.append(h.getName()).append(": ").append(h.getValue()).append("\r\n");
    }
    httpString.append("\r\n");
    Log.d(tag, "headers done");

    try {
        byte[] buffer = new byte[1024 * 16];
        int totalReadBytes = 0; //not including metadata
        int readBytes;

        byte[] httpdata = httpString.toString().getBytes();
        client.getOutputStream().write(httpdata, 0, httpdata.length);

        //now start streaming
        int bytesSinceLastIcy = 0;
        while (isRunning && (readBytes = data.read(buffer, 0, buffer.length)) != -1) {

            totalReadBytes += readBytes;
            bytesSinceLastIcy += readBytes;
            if (icyInterval != -1 && bytesSinceLastIcy > icyInterval) {
                //the icy metadata is in the buffer\
                int metadataPos = readBytes - (bytesSinceLastIcy - icyInterval);
                client.getOutputStream().write(buffer, 0, metadataPos);
                int metadataLength = buffer[metadataPos] * 16;
                byte[] metadata = new byte[metadataLength];
                System.arraycopy(buffer, metadataPos + 1, metadata, 0, metadataLength);
                Log.v(tag, new String(metadata));
                int remainingStart = metadataPos + 1 + metadataLength;
                int remainingLen = readBytes - metadataPos - metadataLength - 1;
                client.getOutputStream().write(buffer, remainingStart, remainingLen);
                bytesSinceLastIcy = remainingLen;
            } else
                client.getOutputStream().write(buffer, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}

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
 *//*ww w.  ja  v  a  2s .  com*/
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:com.clavain.munin.MuninNode.java

/**
 * Will load the plugin list from munin-node
 *///from   w ww .j  ava  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:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Stops running AUT./*from w  w w .  j a v a 2 s.  c  o  m*/
 * 
 */
public void stopApplication() {
    try {
        Socket client = getSocket();
        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println(STOP_APPLICATION);
        client.close();
        boolean appTerminated = false;
        while (!appTerminated) {
            try {
                process.exitValue();
                appTerminated = true;
                LOGGER.info("AUT terminated.");
            } catch (IllegalThreadStateException e) {
                LOGGER.info("AUT is shutting down...");
            }
            Thread.sleep(100);
        }

        writePerformanceLog();

        Runtime.getRuntime().addShutdownHook(addConfigCleaner());
    } catch (UnknownHostException e) {
        LOGGER.error("stopApplication UnknownHostException: ", e);
    } catch (IOException e) {
        LOGGER.error("stopApplication IOException ", e);
    } catch (InterruptedException e) {
        LOGGER.error("stopApplication ", e);
    } finally {
        if (process != null) {
            process.destroy();
        }
        markApplicationStopped();
    }
}