Package net.helipilot50.stocktrade.framework

Source Code of net.helipilot50.stocktrade.framework.ExternalConnectionSSL

/*
Copyright (c) 2003-2009 ITerative Consulting Pty Ltd. All Rights Reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

o Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
 
o Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
   
o This jcTOOL Helper Class software, whether in binary or source form may not be used within,
or to derive, any other product without the specific prior written permission of the copyright holder

 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/
package net.helipilot50.stocktrade.framework;


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;

/**
* Similar to ExternalConnection, however, it only does single socket read and writes.  It does not use Javas nio (non blocking I/O), as Javas nio does not support SSL.
* If you want non blocking I/O, you will need to create multiple instances of this class and manage it yourself.
*
* @author Craig Mitchell
* @since 12/07/2007
*/
public class ExternalConnectionSSL {
    private Socket socket;
    private InputStreamReader inStream;
    private OutputStream outStream;

    public ExternalConnectionSSL() {
        socket = null;
    }

    /**
     * The Open method opens an outbound network connection through an ExternalConnection object.
     * @param address This parameter, used for all protocols, must be one of the following representations of the external endpoint:
     * <li>a hostname in the current domain, for example 'tzu'</li>
     * <li>a hostname with a fully qualified domain, for example 'tzu.forte.com'</li>
     * <li>an IP address, for example '192.104.236.238'</li>
     * @param port the TCP/IP port number of the external listener to connect to.
     */
    public void open(TextData address, int port) {
        open(address.getValue(), port);
    }

    public void open(String pAddress, int pPort) {
        // Create a socket connection
        SocketFactory factory = SSLSocketFactory.getDefault();
        try {
            socket = factory.createSocket(pAddress, pPort);
            InputStream in = socket.getInputStream();
            inStream = new InputStreamReader(in);
            outStream = socket.getOutputStream();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Closes the current external connection.
     */
    public void close() {
        try {
            inStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        socket = null;
    }

    /**
     * The Read method reads the specified number of characters from the network to the
     * specified MemoryStream buffer. Note that the task that invokes Read will block, waiting
     * until it begins to receive data from the network (until the first network I/O).
     * <p>
     * @param dataBuffer The dataBuffer parameter specifies the buffer into which the data is to be placed.
     * @param readLength The readLength I/O parameter sets the number of bytes to read. After
     * the Read has completed, readLength indicates the actual number of bytes read. If the
     * input value for readLength is greater than the length of MemoryStream, readLength will
     * not exceed MemoryStream. Read automatically places data at the beginning of the MemoryStream buffer.
     */
    public int read(MemoryStream pStream, int readLength) {
        int _Result = 0;
        if (pStream == null) {
            NullPointerException errorVar = new NullPointerException("pStream must not be null");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        if (readLength < 0) {
            UsageException errorVar = new UsageException("readLength must be >= 0");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        if (socket == null){
            UsageException errorVar = new UsageException("socketChannel not open");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        readLength = Math.min(readLength, pStream.size());

        // Read the data from it
        try {
            String str = "";
            char[] chars = new char[readLength];
            int x = inStream.read(chars, 0, readLength);
            if (x > 0) {
                str += new String(chars, 0, x);
            }
            _Result = Math.min(readLength, x);
            pStream.write(str.getBytes());
            pStream.setOffset(0);
            pStream.setExplicitLength(_Result);
                System.out.println("MARSHA Sent Us: "+str);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return _Result;
    }

    public void read(MemoryStream pStream, ParameterHolder readLength) {
        int result = this.read(pStream, readLength.getInt());
        readLength.setInt(result >= 0 ? result : 0);
    }

    /**
     * Keep reading from the socket until there is no more data
     * @return
     */
    public String readAll() {
        String str = "";

        try {
            int bufferSize = 1024;
            char[] chars = new char[bufferSize];
            int x = bufferSize;

            while (x == bufferSize) {
                x = inStream.read(chars, 0, bufferSize);
                if (x > 0) {
                    str += new String(chars, 0, x);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("MARSHA Sent Us: "+str);

        return str;
    }

    /**
     * The Write method sends the specified number of characters from the specified MemoryStream buffer across the network to the external endpoint.
     * @param dataBuffer The dataBuffer parameter specifies the buffer that contains the data to be sent.
     * @param writeLength The writeLength input parameter sets the number of bytes to write. The output parameter indicates the actual number of bytes written and is reset after each write. If the value for writeLength exceeds the actual size of the MemoryStream, only the MemoryStream is written.
     * To write (send) data over the network, first put the data to be sent into the MemoryStream buffer. Then use the Write method to send the data in the buffer over the network to the endpoint.
     */
    public void write(MemoryStream dataBuffer, ParameterHolder writeLength) {
        if (dataBuffer == null) {
            NullPointerException errorVar = new NullPointerException("dataBuffer must not be null");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        int length = writeLength.getInt();
        if (length <=0) {
            UsageException errorVar = new UsageException("Write length must be greater than 0");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }
        if (socket == null) {
            UsageException errorVar = new UsageException("socketChannel not open");
            ErrorMgr.addError(errorVar);
            throw errorVar;
        }

        try {
            length = Math.min(dataBuffer.size(), length);
            byte[] tmpBytes = dataBuffer.getByteArray();
            byte[] bytes = new byte[length];

            for (int i=0; i<length; i++) {
                bytes[i] = tmpBytes[i];
            }

            System.out.println("Sent to MARSHA: "+new String(bytes));

            // Write the data to it
            outStream.write(bytes);
            outStream.flush();
            writeLength.setInt(length);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
TOP

Related Classes of net.helipilot50.stocktrade.framework.ExternalConnectionSSL

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.