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.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;
    Socket sslSocket = null;//  w  ww.  ja  va 2s.c  o m
    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;
    }
}

From source file:MyZone.Settings.java

public boolean retrieveCert() {
    while (true) {
        try {//  w w  w .j a v  a2 s  . c om
            Socket toCAServer = new Socket(globalProperties.caAddress, globalProperties.caPort);
            toCAServer.setSoTimeout(IDLE_LIMIT);
            byte[] usernameBytes = username.getBytes("UTF-8");
            DataOutputStream outToCAServer = new DataOutputStream(toCAServer.getOutputStream());
            byte[] buffer = new byte[usernameBytes.length + 4];
            int len = 0;
            System.arraycopy(intToByteArray(usernameBytes.length), 0, buffer, len, 4);
            len += 4;
            System.arraycopy(usernameBytes, 0, buffer, len, usernameBytes.length);
            outToCAServer.write(buffer, 0, buffer.length);
            outToCAServer.flush();
            int i = 0;
            byte[] lenBytes = new byte[4];
            while (i < 4) {
                i += toCAServer.getInputStream().read(lenBytes, i, 4 - i);
                if (i < 0) {
                    if (DEBUG) {
                        System.out.println("DEBUG: line 2529 of Settings.java");
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    if (DEBUG) {
                        e.printStackTrace();
                    }
                }
            }
            len = byteArrayToInt(lenBytes);
            byte[] certBytes = new byte[len];
            i = 0;
            while (i < len) {
                i += toCAServer.getInputStream().read(certBytes, i, len - i);
                if (i < 0) {
                    if (DEBUG) {
                        System.out.println("DEBUG: line 2555 of Settings.java");
                    }
                    len = 4;
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    if (DEBUG) {
                        e.printStackTrace();
                    }
                }
            }
            if (len == 4) {
                Thread.sleep(30000);
                outToCAServer.close();
                toCAServer.close();
                continue;
            }
            outToCAServer.close();
            toCAServer.close();
            globalProperties.caCertPath = prefix + "/CAs/";
            CertVerifier y = new CertVerifier();
            userCertificate uc = y.verifyCertificate(certBytes, globalProperties.caCertPath,
                    globalProperties.keyPairAlgorithm, globalProperties.certSigAlgorithm);
            if (uc == null) {
                Thread.sleep(30000);
                continue;
            }
            File file = new File(prefix + username + "/cert/" + username + ".cert");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(certBytes);
            fos.flush();
            fos.close();
            outToCAServer.close();
            toCAServer.close();
            return true;
        } catch (Exception e) {
            if (DEBUG)
                e.printStackTrace();
        }
    }
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private void transferCheckpoint(Socket sock) {
    synchronized (this.fileSystemLock) {
        BufferedReader brSock = null, brFile = null;
        try {/*  w ww.  j  a va 2  s  . com*/
            brSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            // first and only line is request
            String request = brSock.readLine();
            if ((new File(request).exists())) {
                // request is filename
                brFile = new BufferedReader(new InputStreamReader(new FileInputStream(request)));
                // file successfully open if here
                OutputStream outStream = sock.getOutputStream();
                String line = null; // each line is a record
                while ((line = brFile.readLine()) != null)
                    outStream.write(line.getBytes(CHARSET));
                outStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (brSock != null)
                    brSock.close();
                if (brFile != null)
                    brFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.shonshampain.streamrecorder.util.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;//w w  w. j a v a  2 s .  co m
    }
    String url = request.getRequestLine().getUri();
    int mi = 0;
    Logger.d(DBG, TAG, "processing: " + url);
    Logger.d(DBG, TAG, "request: " + request.getRequestLine());
    for (Header h : request.getAllHeaders()) {
        Logger.d(DBG, TAG, "header: [" + h.getName() + "] = [" + h.getValue() + "]");
    }
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        startOver(null, client, FailType.CantDownload, null);
        return;
    }

    Logger.d(DBG, TAG, "downloading...");

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

    Logger.d(DBG, TAG, "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        if (h.getName().equalsIgnoreCase("Transfer-Encoding")) {
            /* The KCRW stream specifies chunked encoding in their headers,
             * however, when we read their stream, the data gets "unchunked".
             * Therefore, we cannot advertise a chunked encoding unless
             * we actually re-chunk the data; which we are not.
             */
            httpString.append("Accept-Ranges: bytes\r\n");
            httpString.append("Content-Length: 9999999999\r\n");
        } else {
            if (h.getName().equalsIgnoreCase("icy-metaint")) {
                mi = Integer.parseInt(h.getValue());
                Logger.d(DBG, TAG, "Creating new meta data extractor with interval: " + mi);
                mde = new MetaDataExtractor(mi);
            }
            httpString.append(h.getName()).append(": ").append(h.getValue()).append("\r\n");
        }
    }
    httpString.append("\n");
    Logger.d(DBG, TAG, "headers done: [" + httpString + "]");

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

        // Start streaming content.
        final byte[] buff = new byte[1024 * 50];
        boolean endOfStream = false;
        ExecutorService executor = Executors.newFixedThreadPool(1);

        while (isRunning && !endOfStream) {
            Callable<Integer> readTask = new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return data.read(buff, 0, buff.length);
                }
            };
            Future<Integer> future = executor.submit(readTask);
            try {
                readBytes = future.get(STREAM_STALLED_TIMEOUT, TimeUnit.MILLISECONDS);
            } catch (TimeoutException to) {
                startOver(data, client, FailType.Stall, null);
                return;
            } catch (InterruptedException ie) {
                Logger.e(TAG, "The read operation was interrupted");
                continue;
            }
            endOfStream = readBytes == -1;
            if (!endOfStream) {
                Logger.d(DBG_READS, TAG, "Raw read: " + readBytes + " bytes");
                if (mi > 0) {
                    readBytes = mde.processBuffer(buff, readBytes);
                    Logger.d(DBG_META, TAG,
                            "Status: " + mde.getStatus() + ", running count: " + mde.getRunningCount());
                }
                Logger.d(DBG_WRITES, TAG, "writing " + readBytes + " bytes of content to client");
                client.getOutputStream().write(buff, 0, readBytes);
                if (fileHelper != null) {
                    Logger.d(DBG, TAG, "writing " + readBytes + " bytes of content to file");
                    //                        NotificationHelper.build(context, "StreamRecorder Rip Control", "writing " + readBytes + " bytes", notificationId);
                    fileHelper.write(fos, buff, readBytes);
                }
            }
        }
    } catch (Exception e) {
        startOver(data, client, FailType.Unexpected, e);
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String RegisterTheDevice(String sSrvr, String sPort, String sData) {
    String sRet = "";
    String line = "";

    //        Debug.waitForDebugger();

    if (sSrvr != null && sPort != null && sData != null) {
        try {/*from  ww  w .j av a2s .c  o m*/
            int nPort = Integer.parseInt(sPort);
            Socket socket = new Socket(sSrvr, nPort);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), false);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out.println(sData);
            if (out.checkError() == false) {
                socket.setSoTimeout(30000);
                while (socket.isInputShutdown() == false) {
                    line = in.readLine();

                    if (line != null) {
                        line = line.toLowerCase();
                        sRet += line;
                        // ok means we're done
                        if (line.contains("ok"))
                            break;
                    } else {
                        // end of stream reached
                        break;
                    }
                }
            }
            out.close();
            in.close();
            socket.close();
        } catch (NumberFormatException e) {
            sRet += "reg NumberFormatException thrown [" + e.getLocalizedMessage() + "]";
            e.printStackTrace();
        } catch (UnknownHostException e) {
            sRet += "reg UnknownHostException thrown [" + e.getLocalizedMessage() + "]";
            e.printStackTrace();
        } catch (IOException e) {
            sRet += "reg IOException thrown [" + e.getLocalizedMessage() + "]";
            e.printStackTrace();
        }
    }
    return (sRet);
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * @since 3.1/*from   w w  w  .  j  a v a2 s .  com*/
 */
protected OutputStream _storeFileStream(String command, String remote) throws IOException {
    Socket socket = _openDataConnection_(command, remote);

    if (socket == null) {
        return null;
    }

    OutputStream output = socket.getOutputStream();
    if (__fileType == ASCII_FILE_TYPE) {
        // We buffer ascii transfers because the buffering has to
        // be interposed between ToNetASCIIOutputSream and the underlying
        // socket output stream.  We don't buffer binary transfers
        // because we don't want to impose a buffering policy on the
        // programmer if possible.  Programmers can decide on their
        // own if they want to wrap the SocketOutputStream we return
        // for file types other than ASCII.
        output = getBufferedOutputStream(output);
        output = new ToNetASCIIOutputStream(output);

    }
    return new org.apache.commons.net.io.SocketOutputStream(socket, output);
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * @since 3.1//from   w w  w  . j  a v  a  2  s . c  o  m
 */
protected boolean _storeFile(String command, String remote, InputStream local) throws IOException {
    Socket socket = _openDataConnection_(command, remote);

    if (socket == null) {
        return false;
    }

    OutputStream output = getBufferedOutputStream(socket.getOutputStream());

    if (__fileType == ASCII_FILE_TYPE) {
        output = new ToNetASCIIOutputStream(output);
    }

    CSL csl = null;
    if (__controlKeepAliveTimeout > 0) {
        csl = new CSL(this, __controlKeepAliveTimeout, __controlKeepAliveReplyTimeout);
    }

    // Treat everything else as binary for now
    try {
        Util.copyStream(local, output, getBufferSize(), CopyStreamEvent.UNKNOWN_STREAM_SIZE,
                __mergeListeners(csl), false);
    } catch (IOException e) {
        Util.closeQuietly(socket); // ignore close errors here
        if (csl != null) {
            csl.cleanUp(); // fetch any outstanding keepalive replies
        }
        throw e;
    }

    output.close(); // ensure the file is fully written
    socket.close(); // done writing the file
    if (csl != null) {
        csl.cleanUp(); // fetch any outstanding keepalive replies
    }
    // Get the transfer response
    boolean ok = completePendingCommand();
    return ok;
}

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

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

    long dispatcherId = getDispatcherId();

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

    Socket socket = null;
    Thread timeoutThread = null;

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

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

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

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

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

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

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

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

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

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

        ThreadUtils.checkInterruptedStatus();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:Tcpbw100.java

public boolean test_mid(Protocol ctl) throws IOException {
    byte buff[] = new byte[8192];
    Message msg = new Message();
    if ((tests & TEST_MID) == TEST_MID) {
        /* now look for middleboxes (firewalls, NATs, and other boxes that
         * muck with TCP's end-to-end priciples
         *//*w  ww . j a  v a  2 s  . c  o  m*/
        showStatus(messages.getString("middleboxTest"));
        results.append(messages.getString("checkingMiddleboxes") + "  ");
        statistics.append(messages.getString("checkingMiddleboxes") + "  ");
        emailText = messages.getString("checkingMiddleboxes") + "  ";
        pub_status = "checkingMiddleboxes";

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_PREPARE) {
            errmsg = messages.getString("mboxWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        int midport = Integer.parseInt(new String(msg.body));

        Socket in2Socket = null;
        try {
            in2Socket = new Socket(host, midport);
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + host);
            errmsg = messages.getString("unknownServer") + "\n";
            return true;
        } catch (IOException e) {
            System.err.println("Couldn't perform middlebox testing to: " + host);
            errmsg = messages.getString("middleboxFail") + "\n";
            return true;
        }

        InputStream srvin2 = in2Socket.getInputStream();
        OutputStream srvout2 = in2Socket.getOutputStream();

        int largewin = 128 * 1024;

        in2Socket.setSoTimeout(6500);
        int bytes = 0;
        int inlth;
        t = System.currentTimeMillis();
        pub_TimeStamp = new Date();

        try {
            while ((inlth = srvin2.read(buff, 0, buff.length)) > 0) {
                bytes += inlth;
                pub_bytes = bytes;
                if ((System.currentTimeMillis() - t) > 5500)
                    break;
            }
        } catch (IOException e) {
        }

        t = System.currentTimeMillis() - t;
        System.out.println(bytes + " bytes " + (8.0 * bytes) / t + " kb/s " + t / 1000 + " secs");
        s2cspd = ((8.0 * bytes) / 1000) / t;

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_MSG) {
            errmsg = messages.getString("mboxWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        tmpstr2 = new String(msg.body);

        String tmpstr4 = Double.toString(s2cspd * 1000);
        System.out.println("Sending '" + tmpstr4 + "' back to server");
        ctl.send_msg(TEST_MSG, tmpstr4.getBytes());

        try {
            tmpstr2 += in2Socket.getInetAddress() + ";";
        } catch (SecurityException e) {
            System.err.println("Unable to obtain Servers IP addresses: using " + host);
            errmsg = "getInetAddress() called failed\n";
            tmpstr2 += host + ";";
            results.append(messages.getString("lookupError") + "\n");
        }

        System.err.println("calling in2Socket.getLocalAddress()");
        try {
            tmpstr2 += in2Socket.getLocalAddress() + ";";
        } catch (SecurityException e) {
            System.err.println("Unable to obtain local IP address: using 127.0.0.1");
            errmsg = "getLocalAddress() call failed\n";
            tmpstr2 += "127.0.0.1;";
        }

        srvin2.close();
        srvout2.close();
        in2Socket.close();

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_FINALIZE) {
            errmsg = messages.getString("mboxWrongMessage");
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        results.append(messages.getString("done") + "\n");
        statistics.append(messages.getString("done") + "\n");
        emailText += messages.getString("done") + "\n%0A";
    }
    return false;
}

From source file:Tcpbw100.java

public boolean test_c2s(Protocol ctl) throws IOException {
    // byte buff2[] = new byte[8192];
    byte buff2[] = new byte[64 * 1024];
    Message msg = new Message();
    if ((tests & TEST_C2S) == TEST_C2S) {
        showStatus(messages.getString("outboundTest"));
        results.append(messages.getString("runningOutboundTest") + " ");
        statistics.append(messages.getString("runningOutboundTest") + " ");
        emailText += messages.getString("runningOutboundTest") + " ";
        pub_status = "runningOutboundTest";

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }/*  w  w w.  ja v a  2 s  . c om*/
        if (msg.type != TEST_PREPARE) {
            errmsg = messages.getString("outboundWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        int c2sport = Integer.parseInt(new String(msg.body));

        final Socket outSocket;
        try {
            outSocket = new Socket(host, c2sport);
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + host);
            errmsg = messages.getString("unknownServer") + "\n";
            return true;
        } catch (IOException e) {
            System.err.println("Couldn't get 2nd connection to: " + host);
            errmsg = messages.getString("serverBusy15s") + "\n";
            return true;
        }

        // Get server IP address from the outSocket.
        pub_host = outSocket.getInetAddress().getHostAddress().toString();

        final OutputStream out = outSocket.getOutputStream();

        // wait here for signal from server application 
        // This signal tells the client to start pumping out data
        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_START) {
            errmsg = messages.getString("outboundWrongMessage") + "\n";
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }

        byte c = '0';
        int i;
        for (i = 0; i < lth; i++) {
            if (c == 'z')
                c = '0';
            buff2[i] = c++;
        }
        System.err.println("Send buffer size =" + i);
        pkts = 0;
        t = System.currentTimeMillis();
        pub_time = t;
        new Thread() {

            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    System.out.println(e);
                }
                try {
                    out.close();
                    outSocket.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
            }
        }.start();
        while (true) {
            // System.err.println("Send pkt = " + pkts + "; at " + System.currentTimeMillis()); 
            try {
                out.write(buff2, 0, buff2.length);
            } catch (SocketException e) {
                System.out.println(e);
                break;
            }
            // catch (InterruptedIOException iioe) {
            catch (IOException ioe) {
                System.out.println("Client socket timed out");
                break;
            }
            pkts++;
            pub_bytes = (pkts * lth);
        }

        t = System.currentTimeMillis() - t;
        System.err.println(t + "sec test completed");
        if (t == 0) {
            t = 1;
        }
        System.out.println((8.0 * pkts * buff2.length) / t + " kb/s outbound");
        c2sspd = ((8.0 * pkts * buff2.length) / 1000) / t;
        /* receive the c2sspd from the server */
        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_MSG) {
            errmsg = messages.getString("outboundWrongMessage");
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
        String tmpstr3 = new String(msg.body);
        sc2sspd = Double.parseDouble(tmpstr3) / 1000.0;

        if (sc2sspd < 1.0) {
            results.append(prtdbl(sc2sspd * 1000) + "kb/s\n");
            statistics.append(prtdbl(sc2sspd * 1000) + "kb/s\n");
            emailText += prtdbl(sc2sspd * 1000) + "kb/s\n%0A";
        } else {
            results.append(prtdbl(sc2sspd) + "Mb/s\n");
            statistics.append(prtdbl(sc2sspd) + "Mb/s\n");
            emailText += prtdbl(sc2sspd) + "Mb/s\n%0A";
        }

        // Expose upload speed to JavaScript clients
        pub_c2sspd = sc2sspd;
        uplLbl.setText(String.format(padding + "%.3f Mbps", sc2sspd));

        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            return true;
        }
        if (msg.type != TEST_FINALIZE) {
            errmsg = messages.getString("outboundWrongMessage");
            if (msg.type == MSG_ERROR) {
                errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n";
            }
            return true;
        }
    }
    return false;
}