wjhk.jupload2.upload.helper
Class HTTPConnectionHelper

java.lang.Object
  extended by java.io.OutputStream
      extended by wjhk.jupload2.upload.helper.HTTPConnectionHelper
All Implemented Interfaces:
java.io.Closeable, java.io.Flushable

public class HTTPConnectionHelper
extends java.io.OutputStream

This class contains utilities to delegate network manipulation. It hides the management for the current upload policy connection parameters.
This class goes through the following states, stored in the private connectionStatus attribute:

  • STATUS_NOT_INITIALIZED: default status when the instance in created. Only available action: initRequest(URL, String, boolean, boolean)
  • STATUS_BEFORE_SERVER_CONNECTION: the instance is initialized, and the caller may begin writing the request to this ConnectionHelper. All data written to it, will be stored in a ByteArrayEncoderHTTP. The connection switches to this status when the initRequest(URL, String, boolean, boolean) is called.
  • STATUS_WRITING_REQUEST: The network connection to the server is now opened. The content of the ByteArrayEncoderHTTP has been sent to the server. All subsequent calls to write methods will directly write on the socket to the server. The sendRequest() method changes the connection to this status.
  • STATUS_READING_RESPONSE: The request to the server has been totally written. No more calls to the write methods are allowed. The readHttpResponse() is responsible to put the connectionHelper to this status.
  • STATUS_CONNECTION_CLOSED: The response has been read. All getters can be called, to get information about the server response. The only other method allowed is the initRequest(URL, String, boolean, boolean), to start a new request to the server. Using the same connectionHelper allows to use the same network connection, when the allowHttpPersistent applet parameter is used.
  • Author:
    etienne_sf

    Field Summary
    private  boolean bChunkEnabled
              Is chunk upload on for this request ?
    private  boolean bLastChunk
              Is it the last chunk ?
    private  java.lang.String boundary
              http boundary, for the posting multipart post.
    private  ByteArrayEncoder byteArrayEncoder
              The encoder that will contain the HTTP request.
    private  int connectionStatus
              Indicates where data sent to appendXxx method should be added.
    private  HTTPInputStreamReader httpInputStreamReader
              Contains the HTTP reader.
    private  java.io.PushbackInputStream inputStream
              This stream allows the applet to get the server response.
    private  java.lang.String method
              The HTTP method: POST, GET, HEAD...
    private  java.io.DataOutputStream outputStream
              This stream is open by sendRequest().
    private  java.net.Proxy proxy
              The current proxy, if any
    private  java.net.Socket socket
              The network socket where the bytes should be written.
    private static int STATUS_BEFORE_SERVER_CONNECTION
              Indicates that the network connection to the server has not been opened.
    private static int STATUS_CONNECTION_CLOSED
              Indicates that the network connection to the server is now closed, that is: we've written the request, read the response, and free the server connection.
    private static int STATUS_NOT_INITIALIZED
              Indicates that the connection has not been initialized.
    private static int STATUS_READING_RESPONSE
              Indicates that the network connection to the server is opened, but the request has not been totally sent to the server.
    private static int STATUS_WRITING_REQUEST
              Indicates that the network connection to the server is opened, but the request has not been totally sent to the server.
    private  UploadPolicy uploadPolicy
              The current upload policy
    private  java.net.URL url
              The current URL
    private  boolean useProxy
              Should we use a proxy
    private  boolean useSSL
              Is SSL mode on ?
     
    Constructor Summary
    HTTPConnectionHelper(UploadPolicy uploadPolicy)
              The standard constructor for this class.
    HTTPConnectionHelper(java.net.URL url, java.lang.String method, boolean bChunkEnabled, boolean bLastChunk, UploadPolicy uploadPolicy)
              The standard constructor for this class.
     
    Method Summary
     HTTPConnectionHelper append(byte[] bytes)
              Append bytes to the current query.
     HTTPConnectionHelper append(byte[] bytes, int off, int len)
              Append bytes to the current query.
     HTTPConnectionHelper append(ByteArrayEncoder bae)
              Appends a string to the current HTTP request.
     HTTPConnectionHelper append(int b)
              Append bytes to the current query.
     HTTPConnectionHelper append(java.lang.String str)
              write a string to the current HTTP request.
    private  java.lang.String calculateRandomBoundary()
              Construction of a random boundary, to separate the uploaded files, in the HTTP upload request.
     void close()
              This method is the override of OutputStream.close() one.
     void dispose()
              Releases all reserved resources.
     void flush()
              Flushes the output stream.
     java.lang.String getBoundary()
               
     ByteArrayEncoder getByteArrayEncoder()
              Return the current ByteArrayEncoder.
     java.io.PushbackInputStream getInputStream()
              get the input stream, where HTTP server response can be read.
     java.lang.String getMethod()
              Get the HTTP method (HEAD, POST, GET...)
     java.io.OutputStream getOutputStream()
              get the output stream, where HTTP data can be written.
     java.lang.String getResponseBody()
              Get the last response body.
     java.lang.String getResponseHeaders()
              Get the headers of the HTTP response.
     java.lang.String getResponseMsg()
              Get the last response message.
    (package private)  java.net.Socket getSocket()
              Get the current socket.
     java.lang.String getStatusLabel()
              Get the label describing the current state of this connection helper.
    private  void initByteArrayEncoder()
              creating of a new ByteArrayEncoderHTTP, and initializing of the following header items: First line (POST currentProtocol URI), Host, Connection, Keep-Alive, Proxy-Connection.
     void initRequest(java.net.URL url, java.lang.String method, boolean bChunkEnabled, boolean bLastChunk)
              The standard constructor for this class.
    private  boolean isKeepAlive()
              Indicates whether the current socket should be reused ... if any.
     int readHttpResponse()
              Read the response of the server.
     void sendRequest()
              Closes the byteArrayEncoder, create the socket (or not, depending on the current uploadPolicy, and upload history), send the request, and create the InputStream to read the server response.
     void write(byte[] b)
              
     void write(byte[] b, int off, int len)
              
     void write(int b)
              
     
    Methods inherited from class java.lang.Object
    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
     

    Field Detail

    STATUS_NOT_INITIALIZED

    private static final int STATUS_NOT_INITIALIZED
    Indicates that the connection has not been initialized. The only authorized action in this state is a call to initRequest(URL, String, boolean, boolean).

    See Also:
    Constant Field Values

    STATUS_BEFORE_SERVER_CONNECTION

    private static final int STATUS_BEFORE_SERVER_CONNECTION
    Indicates that the network connection to the server has not been opened. All data sent to the ConnectionHelper with write methods are sent to the current ByteArrayEncoder.

    See Also:
    Constant Field Values

    STATUS_WRITING_REQUEST

    private static final int STATUS_WRITING_REQUEST
    Indicates that the network connection to the server is opened, but the request has not been totally sent to the server. All data sent to the ConnectionHelper with write methods is sent to the network connection, that is: to the current OutputStream.
    That is: the ByteArrayEncoder is now read only (closed).

    See Also:
    Constant Field Values

    STATUS_READING_RESPONSE

    private static final int STATUS_READING_RESPONSE
    Indicates that the network connection to the server is opened, but the request has not been totally sent to the server. All data sent to the ConnectionHelper with write methods is sent to the network connection, that is: to the current OutputStream.
    That is: the ByteArrayEncoder is now read only (closed).

    See Also:
    Constant Field Values

    STATUS_CONNECTION_CLOSED

    private static final int STATUS_CONNECTION_CLOSED
    Indicates that the network connection to the server is now closed, that is: we've written the request, read the response, and free the server connection. If the keepAlive parameter is used, the connection may remain opened for the next request.
    No more action may be done on this connection helper, out of reading data, until the application do a call to initRequest(URL, String, boolean, boolean).

    See Also:
    Constant Field Values

    boundary

    private java.lang.String boundary
    http boundary, for the posting multipart post.


    bChunkEnabled

    private boolean bChunkEnabled
    Is chunk upload on for this request ?


    bLastChunk

    private boolean bLastChunk
    Is it the last chunk ? If yes, we'll try to keep the connection open, according to the current applet configuration.


    byteArrayEncoder

    private ByteArrayEncoder byteArrayEncoder
    The encoder that will contain the HTTP request.


    connectionStatus

    private int connectionStatus
    Indicates where data sent to appendXxx method should be added. It must be one of the SENDING_XXX private strings.


    httpInputStreamReader

    private HTTPInputStreamReader httpInputStreamReader
    Contains the HTTP reader. All data coming from the server response are read from it. If this attribute is null, it means that the server response has not been read.


    inputStream

    private java.io.PushbackInputStream inputStream
    This stream allows the applet to get the server response. It is opened and closed as the outputStream.


    method

    private java.lang.String method
    The HTTP method: POST, GET, HEAD...


    outputStream

    private java.io.DataOutputStream outputStream
    This stream is open by sendRequest(). It is closed by the readHttpResponse() method.

    See Also:
    sendRequest(), readHttpResponse(), getOutputStream()

    proxy

    private java.net.Proxy proxy
    The current proxy, if any


    socket

    private java.net.Socket socket
    The network socket where the bytes should be written.


    uploadPolicy

    private UploadPolicy uploadPolicy
    The current upload policy


    url

    private java.net.URL url
    The current URL


    useProxy

    private boolean useProxy
    Should we use a proxy


    useSSL

    private boolean useSSL
    Is SSL mode on ?

    Constructor Detail

    HTTPConnectionHelper

    public HTTPConnectionHelper(UploadPolicy uploadPolicy)
    The standard constructor for this class.

    Parameters:
    uploadPolicy - The current upload policy.

    HTTPConnectionHelper

    public HTTPConnectionHelper(java.net.URL url,
                                java.lang.String method,
                                boolean bChunkEnabled,
                                boolean bLastChunk,
                                UploadPolicy uploadPolicy)
                         throws JUploadIOException
    The standard constructor for this class.

    Parameters:
    url - The target URL
    method - The HTTP method (POST, GET, HEAD...)
    bChunkEnabled - Indicates if chunkUpload is enabled for this query. Put false, if non chunked request or if it is not relevant.
    bLastChunk - Indicates whether this chunk is the last one. Put true, if non chunked request or if it is not relevant.
    uploadPolicy - The current upload policy.
    Throws:
    JUploadIOException
    Method Detail

    initRequest

    public void initRequest(java.net.URL url,
                            java.lang.String method,
                            boolean bChunkEnabled,
                            boolean bLastChunk)
                     throws JUploadIOException
    The standard constructor for this class.

    Parameters:
    url - The target URL
    bChunkEnabled - Indicates if chunkUpload is enabled for this query. Put false, if non chunked request or if it is not relevant.
    method - The HTTP method (POST, GET, HEAD...)
    bLastChunk - Indicates whether this chunk is the last one. Put true, if non chunked request or if it is not relevant.
    Throws:
    JUploadIOException

    getByteArrayEncoder

    public ByteArrayEncoder getByteArrayEncoder()
                                         throws JUploadIOException
    Return the current ByteArrayEncoder. If it was not created, it is initialized.

    Returns:
    The current ByteArrayEncoder, null if called before the first initialization.
    Throws:
    JUploadIOException
    See Also:
    initRequest(URL, String, boolean, boolean)

    getBoundary

    public java.lang.String getBoundary()
    Returns:
    Returns the boundary for this HTTP request.

    sendRequest

    public void sendRequest()
                     throws JUploadIOException
    Closes the byteArrayEncoder, create the socket (or not, depending on the current uploadPolicy, and upload history), send the request, and create the InputStream to read the server response.

    Throws:
    JUploadIOException

    dispose

    public void dispose()
                 throws JUploadIOException
    Releases all reserved resources.

    Throws:
    JUploadIOException

    getOutputStream

    public java.io.OutputStream getOutputStream()
    get the output stream, where HTTP data can be written.

    Returns:
    The current output stream to the server, where things can be written, event after the socket is open, if the byteArrayEncoder did not contain the full request.

    getInputStream

    public java.io.PushbackInputStream getInputStream()
    get the input stream, where HTTP server response can be read.

    Returns:
    The current input stream of the socket.

    getMethod

    public java.lang.String getMethod()
    Get the HTTP method (HEAD, POST, GET...)

    Returns:
    The HTTP method

    getResponseBody

    public java.lang.String getResponseBody()
    Get the last response body.

    Returns:
    The full response body, that is: the HTTP body of the server response.

    getResponseHeaders

    public java.lang.String getResponseHeaders()
    Get the headers of the HTTP response.

    Returns:
    The HTTP headers.

    getResponseMsg

    public java.lang.String getResponseMsg()
    Get the last response message.

    Returns:
    the response message, like "200 OK"

    getStatusLabel

    public java.lang.String getStatusLabel()
    Get the label describing the current state of this connection helper.

    Returns:
    A text describing briefly the current connection status.

    getSocket

    java.net.Socket getSocket()
    Get the current socket.

    Returns:
    return the current Socket, opened toward the server.

    append

    public HTTPConnectionHelper append(int b)
                                throws JUploadIOException
    Append bytes to the current query. The bytes will be written to the current ByteArrayEncoder if the the connection to the server is not open, or directly to the server if the connection is opened.

    Parameters:
    b - The byte to send to the server.
    Returns:
    Returns the current ConnectionHelper, to allow coding like StringBuffers: a.append(b).append(c);
    Throws:
    JUploadIOException

    append

    public HTTPConnectionHelper append(byte[] bytes)
                                throws JUploadIOException
    Append bytes to the current query. The bytes will be written to the current ByteArrayEncoder if the the connection to the server is not open, or directly to the server if the connection is opened.

    Parameters:
    bytes - The bytes to send to the server.
    Returns:
    Returns the current ConnectionHelper, to allow coding like StringBuffers: a.append(b).append(c);
    Throws:
    JUploadIOException

    append

    public HTTPConnectionHelper append(byte[] bytes,
                                       int off,
                                       int len)
                                throws JUploadIOException
    Append bytes to the current query. The bytes will be written to the current ByteArrayEncoder if the the connection to the server is not open, or directly to the server if the connection is opened.

    Parameters:
    bytes - The bytes to send to the server.
    off - The first byte to send
    len - Number of bytes to send.
    Returns:
    Returns the current ConnectionHelper, to allow coding like StringBuffers: a.append(b).append(c);
    Throws:
    JUploadIOException

    append

    public HTTPConnectionHelper append(java.lang.String str)
                                throws JUploadIOException
    write a string to the current HTTP request.

    Parameters:
    str - The string to write
    Returns:
    The current HTTPConnectionHelper
    Throws:
    JUploadIOException - If any problem occurs during the writing operation.
    See Also:
    append(byte[])

    append

    public HTTPConnectionHelper append(ByteArrayEncoder bae)
                                throws JUploadIOException
    Appends a string to the current HTTP request.

    Parameters:
    bae - The ByteArrayEncoder to write. It is expected to be correctly encoded. That is: it is up to the caller to check that its encoding is the same as the current HTTP request encoding.
    Returns:
    The current HTTPConnectionHelper
    Throws:
    JUploadIOException - If any problem occurs during the writing operation.
    See Also:
    append(byte[])

    readHttpResponse

    public int readHttpResponse()
                         throws JUploadException
    Read the response of the server. This method delegates the work to the HTTPInputStreamReader. handles the chunk HTTP response.

    Returns:
    The HTTP status. Should be 200, when everything is right.
    Throws:
    JUploadException

    initByteArrayEncoder

    private void initByteArrayEncoder()
                               throws JUploadIOException
    creating of a new ByteArrayEncoderHTTP, and initializing of the following header items: First line (POST currentProtocol URI), Host, Connection, Keep-Alive, Proxy-Connection.

    Throws:
    JUploadIOException

    isKeepAlive

    private boolean isKeepAlive()
    Indicates whether the current socket should be reused ... if any.


    calculateRandomBoundary

    private final java.lang.String calculateRandomBoundary()
    Construction of a random boundary, to separate the uploaded files, in the HTTP upload request.

    Returns:
    The calculated boundary.

    write

    public void write(int b)
               throws java.io.IOException

    Specified by:
    write in class java.io.OutputStream
    Throws:
    java.io.IOException

    write

    public void write(byte[] b,
                      int off,
                      int len)
               throws java.io.IOException

    Overrides:
    write in class java.io.OutputStream
    Throws:
    java.io.IOException

    write

    public void write(byte[] b)
               throws java.io.IOException

    Overrides:
    write in class java.io.OutputStream
    Throws:
    java.io.IOException

    close

    public void close()
               throws java.io.IOException
    This method is the override of OutputStream.close() one. It may not been called. You must use the sendRequest() or readHttpResponse() methods instead.

    Specified by:
    close in interface java.io.Closeable
    Overrides:
    close in class java.io.OutputStream
    Throws:
    java.io.IOException
    See Also:
    OutputStream.close()

    flush

    public void flush()
               throws java.io.IOException
    Flushes the output stream. Useful only when the HTTPConnectionHelper is writing to the socket toward the server, that is when the status is: STATUS_WRITING_REQUEST.

    Specified by:
    flush in interface java.io.Flushable
    Overrides:
    flush in class java.io.OutputStream
    Throws:
    java.io.IOException
    See Also:
    OutputStream.flush()