Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file: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
         *///from  w  ww. j  a v  a  2s.c om
        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: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;//from  ww w  . j av  a2s  . co  m
    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:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

/**
 * Default public constructor.//from  w  w w  .j av a2s  . co  m
 * 
 * @param http
 * @param url
 * @param knownMetadata
 * @throws IOException
 * @throws HttpException
 */
public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException {

    this.http = http;
    this.url = url;

    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new IOException("Unknown scheme (not http/https) for url:" + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        this.conf = http.getConf();
        if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) {
            headers.setValue("_ip_", sockAddr.getAddress().getHostAddress());
        }

        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (HttpProtocol.LOGGER.isErrorEnabled()) {
                HttpProtocol.LOGGER.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        reqStr.append("Accept-Language: ");
        reqStr.append(this.http.getAcceptLanguage());
        reqStr.append("\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        if (knownMetadata != null) {
            String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified");
            if (StringUtils.isNotBlank(ifModifiedSince)) {
                reqStr.append("If-Modified-Since: ");
                reqStr.append(ifModifiedSince);
                reqStr.append("\r\n");
            }

            String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag");
            if (StringUtils.isNotBlank(ifNoneMatch)) {
                reqStr.append("If-None-Match: ");
                reqStr.append(ifNoneMatch);
                reqStr.append("\r\n");
            }
        }

        reqStr.append("\r\n");

        // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default
        // charset
        // TODO use UTF-8 and set a charset value explicitely
        byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1);

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(
                        new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE),
                        HttpProtocol.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is
                                                     // "Continue"
        }
        String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING);
        if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) {
            readChunkedContent(in, line);
        } else {
            readPlainContent(in);
        }

        String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING);
        if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
            content = http.processGzipEncoded(content, url);
        } else if ("deflate".equals(contentEncoding)) {
            content = http.processDeflateEncoded(content, url);
        } else {
            HttpProtocol.LOGGER.trace("fetched {}  bytes from {}", content.length, url);
        }

    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel payRequest(String strMachOrderId, Integer nTransactionAmount, String strTerminalId,
        String strTrackData, String strPIN, String strLongitude, String strLatitude, String host, Integer port,
        Integer nT0Flag, Integer marketType) {
    byte[] head = Device.nativeFunction1008(device);
    byte[] body = Device.nativeFunction1009(device, strMachOrderId, nTransactionAmount, strTerminalId,
            strTrackData, strPIN, strLongitude, strLatitude, nT0Flag, marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);//  w  ww  .ja v a 2 s .  c  om
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }

}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel newPayRequest(String strMachOrderId, Integer nTransactionAmount, String strTerminalId,
        String strTrackData, String strPIN, String strLongitude, String strLatitude, String host, Integer port,
        Integer nT0Flag, Integer marketType) {
    if (YeahkaDevice.getDeviceVersionType() == YeahkaDevice.DEVICE_VERSION_TYPE_PIN_WITH_OPERATE) {
        if (!TextUtils.isEmpty(strPIN)) {
            strPIN = strPIN + PIN_BACK;// w w  w  .jav a  2 s. com
        }
    }
    byte[] head = Device.nativeFunction1020(device);
    byte[] body = Device.nativeFunction1021(device, strMachOrderId, nTransactionAmount, strTerminalId,
            strTrackData, strPIN, strLongitude, strLatitude, nT0Flag, marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }

}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel ICCardPayRequest(String strMachOrderId, Integer nTransactionAmount, String strTerminalId,
        String strTrackData, String strPIN, String strLongitude, String strLatitude, String host, Integer port,
        String strCardSerialNo, String strICCardInfo, Integer nT0Flag, Integer marketType) {
    if (YeahkaDevice.getDeviceVersionType() == YeahkaDevice.DEVICE_VERSION_TYPE_PIN_WITH_OPERATE) {
        if (!TextUtils.isEmpty(strPIN)) {
            strPIN = strPIN + PIN_BACK;/*  w w w. j a v  a 2  s  .  c  om*/
        }
    }

    //        MyLog.info("mDealMode=", nT0Flag + "");
    byte[] head = Device.nativeFunction1020(device);
    byte[] body = Device.nativeFunction1023(device, strMachOrderId, nTransactionAmount, strTerminalId,
            strTrackData, strPIN, strLongitude, strLatitude, strCardSerialNo, strICCardInfo, nT0Flag,
            marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }
}

From source file:com.yeahka.android.lepos.Device.java

/**
 * ??/*from   w w w  .  ja v  a2  s. c om*/
 *
 * @param strOrderID
 * @param amount
 * @param strPinpadID
 * @param strTrack2Data
 * @param strTrack3Data
 * @param strPin
 * @param strLongitude
 * @param strLatitude
 * @param strCardSerialNo
 * @param strICCardInfo
 * @param strDiffuseFactor
 * @param deviceType
 * @param host
 * @param port
 * @return
 */
//-----------terence add --2016-03-17 t+0 ---------
//-----------terence add --2016-05-16   marketType---------
public ResultModel zhongciPayRequest(String strOrderID, Integer amount, String strPinpadID,
        String strTrack2Data, String strTrack3Data, String strPin, String strLongitude, String strLatitude,
        String strCardSerialNo, String strICCardInfo, String strDiffuseFactor, Integer deviceType, String host,
        Integer port, Integer nT0Flag, Integer marketType) {
    if (YeahkaDevice.getDeviceVersionType() == YeahkaDevice.DEVICE_VERSION_TYPE_PIN_WITH_OPERATE) {
        if (!TextUtils.isEmpty(strPin)) {
            strPin = strPin + PIN_BACK;
        }
    }
    //        String tag = "zhongciPayRequest";
    byte[] head = Device.nativeFunction10004(device);
    byte[] body = Device.nativeFunction10005(device, strOrderID, amount, strPinpadID, strTrack2Data,
            strTrack3Data, strPin, strLongitude, strLatitude, strCardSerialNo, strICCardInfo, strDiffuseFactor,
            deviceType, nT0Flag, marketType);
    byte[] sendData = Device.nativeFunction60(device, head, intToFourByte(Device.nativeFunction66(device)),
            body);
    InetAddress address;
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(sendData);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket);
        if (bGetHead == false) {
            //                MyLog.d(TAG, "get head =" + bGetHead);
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            //                MyLog.d(TAG, "len is not 4 ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntLowByteFirst();
        if (dataLength < 0) {
            //                MyLog.d(TAG, "data len less than 0 ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        if (length != dataLength) {
            //                MyLog.d(TAG, "len not equal data lenth ");
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        String sc = new String(bytes, "UTF-8");
        return new ResultModel(sc);
    } catch (UnknownHostException e) {
        e.printStackTrace();
        MyLog.d(TAG, "UnknownHostException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        e1.printStackTrace();
        MyLog.d(TAG, "SocketException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        e2.printStackTrace();
        MyLog.d(TAG, "IOException ");
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }

}

From source file:com.yeahka.android.lepos.Device.java

public ResultModel sendDataToRegisterServer(byte[] data, Class classOfT) {
    String host = REGISTER_HOST; // "192.168.21.243";
    int port = REGISTER_PORT; // 8061;
    InetAddress address;//from ww w . j a v a  2s.  co m
    try {
        address = InetAddress.getByName(host);
        Socket socket = new Socket(address, port);
        socket.setKeepAlive(true);// ????
        socket.setSoTimeout(60 * 1000);// 
        OutputStream out = socket.getOutputStream();
        out.write(data);
        out.flush();
        InputStream input = socket.getInputStream();
        boolean bGetHead = ServerSocketConnectUtil.getHead(socket,
                ServerSocketConnectUtil.HEAD_TYPE_REGISTER_SYSTEM);
        if (bGetHead == false) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        byte[] bytes = new byte[4];
        int length = input.read(bytes);
        if (length != 4) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        ByteArrayReader bar = new ByteArrayReader(bytes);
        int dataLength = bar.readIntHighByteFirst(); // readIntHighByteFirst
        // readIntLowByteFirst
        if (dataLength < 0) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }
        bytes = new byte[dataLength];
        length = input.read(bytes);
        while (length < dataLength) {
            length += input.read(bytes, length, dataLength - length);
        }

        if (length != dataLength) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        byte[] bytesMsgHeader = new byte[4];
        System.arraycopy(bytes, 0, bytesMsgHeader, 0, 4);
        if (!ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM_HEADER,
                bytesMsgHeader)) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        System.arraycopy(bytes, 4, bytesMsgHeader, 0, 4);
        bar = new ByteArrayReader(bytesMsgHeader);
        length = bar.readIntHighByteFirst();

        int index = 8 + length;
        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;
        if (!ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM_BODY,
                bytesMsgHeader)) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;

        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;
        if (!ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM_BODY_CONTENT,
                bytesMsgHeader)) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        System.arraycopy(bytes, index, bytesMsgHeader, 0, 4);
        index += 4;
        bar = new ByteArrayReader(bytesMsgHeader);
        length = bar.readIntHighByteFirst();

        if (dataLength < index + length) {
            return new ResultModel(Device.SYSTEM_FAIL);
        }

        byte[] josnBytes = new byte[length];
        System.arraycopy(bytes, index, josnBytes, 0, length);

        ResultModel resultModel = new ResultModel(josnBytes, classOfT);

        // if (bNeedRecycleRegisterServerSocket) {
        // out.close();
        // input.close();
        // registerServerSocket.close();
        // registerServerSocket = null;
        // }

        return resultModel;
    } catch (UnknownHostException e) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (SocketException e1) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    } catch (IOException e2) {
        return new ResultModel(Device.TRANSACTION_NET_FAIL);
    }
}

From source file:com.web.server.WebServer.java

/**
 * This methos is the implementation of the HTPP request and sends the response.
 *///  w w  w. ja v  a 2s . c  o  m
public void run() {
    byte[] response;
    byte[] content;
    byte[] uploadData = null;
    HttpHeaderClient httpHeaderClient = null;
    InputStream istream = null;
    OutputStream ostream = null;
    HttpHeaderServer serverParam = new HttpHeaderServer();
    StringBuffer buffer = new StringBuffer();
    String value;
    char c;
    String endvalue = "\r\n\r\n";
    String urlFormEncoded;
    int responseCode;
    try {
        ////System.out.println("value=");
        istream = socket.getInputStream();
        BufferedInputStream bistr = new BufferedInputStream(istream);
        //socket.setReceiveBufferSize(10000);
        //System.out.println("value1=");
        int availbleStream;
        int totalBytRead = 0;
        int ch;
        ByteArrayOutputStream bytout = new ByteArrayOutputStream();
        ByteArrayOutputStream contentout = new ByteArrayOutputStream();
        //System.out.println(istream.available());
        int bytesRead;
        int endbytIndex = 0;
        int contentbytIndex = 0;
        boolean httpHeaderEndFound = false;
        byte[] byt;
        while ((ch = bistr.read()) != -1) {
            bytout.write(ch);
            if (!httpHeaderEndFound && (char) ch == endvalue.charAt(endbytIndex)) {
                endbytIndex++;
                if (endbytIndex == endvalue.length()) {
                    byt = bytout.toByteArray();
                    value = new String(ObtainBytes(byt, 0, byt.length - 4));
                    //System.out.println(value);
                    httpHeaderClient = parseHttpHeaders(value);
                    httpHeaderEndFound = true;
                    bytout.close();
                    endbytIndex = 0;
                    if (httpHeaderClient.getContentLength() == null)
                        break;
                }
            } else {
                endbytIndex = 0;
            }
            if (httpHeaderClient != null && httpHeaderEndFound) {
                contentout.write(ch);
                contentbytIndex++;
                if (httpHeaderClient.getContentLength() != null
                        && contentbytIndex >= Integer.parseInt(httpHeaderClient.getContentLength())) {
                    break;
                }
            }
            totalBytRead++;
        }
        /*while(totalBytRead==0){
           while((ch = bistr.read())!=-1){
              System.out.println((char)ch);
              ////System.out.println("availableStream="+availbleStream);
              bytarrayOutput.write(ch);
              totalBytRead++;
           }
        }*/
        if (totalBytRead == 0) {
            System.out.println("Since byte is 0 sock and istream os closed");
            //istream.close();
            socket.close();
            return;
        }
        //istream.read(bt,0,9999999);
        System.out.println("bytes read");
        byte[] contentByte = contentout.toByteArray();
        contentout.close();
        //System.out.println("String="+new String(bt));
        /*int index=containbytes(bt,endvalue.getBytes());
        if(index==-1)index=totalBytRead;
        value=new String(ObtainBytes(bt,0,index));*/
        System.out.println("value2=");

        ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies();
        HttpSessionServer session = null;
        if (httpCookies != null) {
            Iterator<String> cookieNames = httpCookies.keySet().iterator();
            for (; cookieNames.hasNext();) {
                String cookieName = cookieNames.next();
                //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                if (cookieName.equals("SERVERSESSIONID")) {
                    session = (HttpSessionServer) sessionObjects.get(httpCookies.get(cookieName).getValue());
                    httpHeaderClient.setSession(session);
                    //break;
                }
            }
        }
        //System.out.println("Session="+session);
        if (session == null) {
            HttpCookie cookie = new HttpCookie();
            cookie.setKey("SERVERSESSIONID");
            cookie.setValue(UUID.randomUUID().toString());
            httpCookies.put("SERVERSESSIONID", cookie);
            session = new HttpSessionServer();
            sessionObjects.put(cookie.getValue(), session);
            httpHeaderClient.setSession(session);
        }
        if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
            ////System.out.println(new String(uploadData));
            ConcurrentHashMap paramMap = new MultipartFormData().parseContent(contentByte, httpHeaderClient);
            httpHeaderClient.setParameters(paramMap);
            ////logger.info(uploadData);
        } else if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)) {
            urlFormEncoded = new String(contentByte);
            ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded);
            httpHeaderClient.setParameters(paramMap);
        }
        ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
        ////System.out.println("value3=");

        ////logger.info(new String(bt));
        serverParam.setContentType("text/html");
        URLDecoder decoder = new URLDecoder();
        System.out.println("content Length= " + socket);
        responseCode = 200;
        File file = new File(deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
        FileContent fileContent = (FileContent) cache.get(httpHeaderClient.getResourceToObtain());
        if (fileContent != null && file.lastModified() == fileContent.getLastModified()) {
            System.out.println("In cache");
            content = (byte[]) fileContent.getContent();
        } else {
            content = ObtainContentExecutor(deployDirectory, httpHeaderClient.getResourceToObtain(),
                    httpHeaderClient, serverdigester, urlClassLoaderMap, servletMapping, session);
            System.out.println("content Length2= " + content);
            if (content == null) {
                //System.out.println("In caching content");
                content = obtainContent(
                        deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
                if (content != null) {
                    fileContent = new FileContent();
                    fileContent.setContent(content);
                    fileContent.setFileName(httpHeaderClient.getResourceToObtain());
                    fileContent.setLastModified(file.lastModified());
                    cache.put(httpHeaderClient.getResourceToObtain(), fileContent);
                }
            }
            ////System.out.println("value4=");

        }

        if (content == null) {
            responseCode = 404;
            content = ("<html><body><H1>The Request resource " + httpHeaderClient.resourceToObtain
                    + " Not Found</H1><body></html>").getBytes();
        }
        ////System.out.println("content Length3= ");
        serverParam.setContentLength("" + (content.length + 4));
        if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) {
            serverParam.setContentType("image/png");
        }
        ////System.out.println("value5=");

        ////System.out.println("content Length4= ");
        response = formHttpResponseHeader(responseCode, serverParam, content, httpHeaderClient.getCookies());
        ////System.out.println("value6=");
        ostream = socket.getOutputStream();
        //logger.info("Response="+new String(response));
        //System.out.println("value6=");
        //logger.info("Response="+new String(response));
        ////System.out.println("content "+"Response="+new String(response));
        ostream.write(response);
        ostream.flush();
        ostream.close();
        socket.close();
    } catch (IOException e) {
        Socket socket;
        e.printStackTrace();

        //logger.error(e);
        try {
            socket = new Socket("localhost", shutdownPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
            outputStream.close();
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        e.printStackTrace();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}