CADI.Server.Core
Class Worker

java.lang.Object
  extended by java.lang.Thread
      extended by CADI.Server.Core.Worker
All Implemented Interfaces:
StatusCodes, EORCodes, java.lang.Runnable

public class Worker
extends java.lang.Thread
implements StatusCodes, EORCodes

This class performs the client request processing and it sends the server response to the client. It does the following tasks: manages the client sessions, manages logical targets, check restrictions, sends the response (data or errors), etc.

This thread is launched and it will be waiting for a task. Tasks are passed to this worker through a TaskQueue queue (the Scheduler puts the task into the queue and the Worker get them).

This thread is always running or waiting for a task. Therefore, it only can be finished if the finish is set to true.

Usage example:
  construct
  setParameters
  run
  ....
  finish

Version:
1.1.2 2009/08/15
Author:
Group on Interactive Coding of Images (GICI)

Nested Class Summary
 
Nested classes/interfaces inherited from class java.lang.Thread
java.lang.Thread.State, java.lang.Thread.UncaughtExceptionHandler
 
Field Summary
private  boolean busy
          Indicates if the thread is carrying out a task.
private  java.lang.String cachePath
          Is the path directory that will be used to save the temporary files used to cache client data.
private static java.lang.String channelFieldPath
           
private  int deliveryProgressionOrder
          Is the progression order which will be used to delivery the data.
private  boolean finish
          Indicates whether the thread has to finish when it is working with a request with the keep-alive mode set.
private  HTTPRequest httpRequest
          Definition in HTTPRequest.
private  HTTPResponse httpResponse
           
private  HTTPResponseSender httpResponseSender
           
private  boolean independentMessageHeaders
          Definition in JPIPMessageEncoder.independentForm.
private  boolean initializeCache
          This attribute is used in the logicalTargetsManager(String, String) and the cacheManager() methods to indicate if the cache must be created.
private  long initStageTime
          Used for verbose information (time for stage).
private  long initTime
          Used for verbose information (total time).
private  boolean isStatelessRequest
          Indicates whether the actual request is a stateles request or a request with a session.
private  JPIPRequestFields jpipRequestFields
          Definition in JPIPRequestFields.
private  JPIPResponseFields jpipResponseFields
           
private  int keepAliveTimeout
          Definition in Scheduler.keepAliveTimeout.
private  ClientSessions listOfClientSessions
          Definition in Scheduler.clientSessions.
private  CADILog log
          Definition in Scheduler.log.
private  ServerLogicalTarget logicalTarget
          Contains a pointer to the parameters of the logical target which is being requested.
private  LogicalTargetList logicalTargetList
          Definition in Scheduler.logicalTargetList.
private  float maxTxRate
          Definition in Scheduler.maxTxRate.
private  java.io.OutputStream os
          Is an output stream that will be used to send the server response to the client.
private  int rateDistortionMethod
          Definition in JP2LogicalTarget.rateDistortionMethod.
private  int RDSubType
          Indicates a type within the rate distortion method.
private  boolean sendLogicalTargetData
           
private  ServerCache serverCache
           
private  ServerLogicalTargetManager serverLogicalTargetManager
           
private  Session session
          Contains the session object where is data about the actual session is saved.
private  java.lang.String sessionID
          It is the session identifier of the request which is being processed.
private  boolean setTID
           
private  java.net.Socket socket
          Contains the client socket of which request is being processed.
private  java.lang.String targetsPath
          Is the path directory where the logical targets are stored.
private  TasksQueue tasksQueue
          Definition in Scheduler.tasksQueue
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Fields inherited from interface CADI.Common.Network.HTTP.StatusCodes
ACCEPTED, BAD_REQUEST, NOT_FOUND, NOT_IMPLEMENTED, OK, SERVICE_UNAVAILABLE, UNSUPPORTED_MEDIA_TYPE
 
Fields inherited from interface CADI.Common.Network.JPIP.EORCodes
BYTE_LIMIT_REACHED, IMAGE_CHANGE, IMAGE_DONE, NON_ESPECIFIED_REASON, QUALITY_LIMIT_REACHED, RESPONSE_LIMIT_REACHED, SESSION_LIMIT_REACHED, WINDOW_DONE
 
Constructor Summary
Worker(java.lang.String threadName, TasksQueue tasksQueue, LogicalTargetList logicalTargetList, ClientSessions clientSessions, CADILog log)
          Constructor.
 
Method Summary
private  java.lang.String[] availableReturnTypes()
          Gets the available image return types.
private  void cacheManager()
          This method is used to manage the caches when a session is created or when a cache needs to be update with data received from the client.
private  void checkJPIPParameters()
          This method tests several JPIP restrictions of the parameters
private  void closeChannels(java.lang.String cid, java.lang.String[] cclose)
          This method is used to close session channels.
private  void encodeJPIPResponseFields()
          JPIP HEADERS (See ISO/IEC 15444-9 Annex D)
 void finish()
          This method is used to indicate that the thread has to finish.
 java.lang.Thread.State getState()
           
 boolean isBusy()
          This method is used to indicate if the thread is or no busy processing a task.
private  void listenNewRequest()
          This method will be used to read a HTTP client request.
private  void logicalTargetsManager(java.lang.String target, java.lang.String tid)
          This method is used to manage the list of loaded targets.
private  void processRequest()
          This method performs the core to process the client requests.
private  void resetTime()
          Set the time attributes to 0.
 void run()
          This method implements the control of the thread.
private  void sendHTTPResponseError(int statusCode, java.lang.String reasonPhrase)
          This method will be used to send an HTTP error response to the client.
private  void sendHTTPResponseHeader(HTTPResponse httpResponse)
           
 void sessionsManager()
          This method is used to manage the client sessions.
 void setCachePath(java.lang.String cachePath)
          Sets the cachePath attribute.
 void setDeliveryProgressionOrder(int deliveryProgressionOrder)
          Sets the deliveryProgressionOrder attribute.
 void setIndependentMessageHeaders(boolean independentMessageHeaders)
          Sets the #independentMesssageHeaders attribute.
 void setKeepAliveTimeout(int keepAliveTimeout)
          Sets the keepAliveTimeout attribute.
 void setMaxTxRate(float maxTxRate)
          Sets the maxTxRate attribute.
 void setRateDistortionMethod(int rateDistortionMethod, int RDSubType)
          Sets the rate-distortion method and the subrate-distortion method.
 void setTargetsPath(java.lang.String targetsPath)
          Sets the targetsPath attribute.
private  java.lang.String showTimeMemory(java.lang.String stage)
          Show some time and memory usage statisticals.
private  void updateCache(java.util.ArrayList jpipMessageData)
          This method is used to update the cache with the data that has been sent to the client.
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

tasksQueue

private TasksQueue tasksQueue
Definition in Scheduler.tasksQueue


logicalTargetList

private LogicalTargetList logicalTargetList
Definition in Scheduler.logicalTargetList.


listOfClientSessions

private ClientSessions listOfClientSessions
Definition in Scheduler.clientSessions.


log

private CADILog log
Definition in Scheduler.log.


targetsPath

private java.lang.String targetsPath
Is the path directory where the logical targets are stored.


cachePath

private java.lang.String cachePath
Is the path directory that will be used to save the temporary files used to cache client data.


rateDistortionMethod

private int rateDistortionMethod
Definition in JP2LogicalTarget.rateDistortionMethod.


RDSubType

private int RDSubType
Indicates a type within the rate distortion method.


deliveryProgressionOrder

private int deliveryProgressionOrder
Is the progression order which will be used to delivery the data. If this parameters is not set, the default file codestream order will be used.


keepAliveTimeout

private int keepAliveTimeout
Definition in Scheduler.keepAliveTimeout.


maxTxRate

private float maxTxRate
Definition in Scheduler.maxTxRate.


independentMessageHeaders

private boolean independentMessageHeaders
Definition in JPIPMessageEncoder.independentForm.


socket

private java.net.Socket socket
Contains the client socket of which request is being processed.


httpRequest

private HTTPRequest httpRequest
Definition in HTTPRequest.


jpipRequestFields

private JPIPRequestFields jpipRequestFields
Definition in JPIPRequestFields.


finish

private boolean finish
Indicates whether the thread has to finish when it is working with a request with the keep-alive mode set.

See Also:
finish()

busy

private boolean busy
Indicates if the thread is carrying out a task. If the thread is waiting for a new task, the busy attribute is false.


os

private java.io.OutputStream os
Is an output stream that will be used to send the server response to the client.


httpResponseSender

private HTTPResponseSender httpResponseSender

httpResponse

private HTTPResponse httpResponse

jpipResponseFields

private JPIPResponseFields jpipResponseFields

logicalTarget

private ServerLogicalTarget logicalTarget
Contains a pointer to the parameters of the logical target which is being requested.


serverLogicalTargetManager

private ServerLogicalTargetManager serverLogicalTargetManager

serverCache

private ServerCache serverCache

initializeCache

private boolean initializeCache
This attribute is used in the logicalTargetsManager(String, String) and the cacheManager() methods to indicate if the cache must be created.


isStatelessRequest

private boolean isStatelessRequest
Indicates whether the actual request is a stateles request or a request with a session.


session

private Session session
Contains the session object where is data about the actual session is saved.


sessionID

private java.lang.String sessionID
It is the session identifier of the request which is being processed.


setTID

private boolean setTID

sendLogicalTargetData

private boolean sendLogicalTargetData

channelFieldPath

private static java.lang.String channelFieldPath

initStageTime

private long initStageTime
Used for verbose information (time for stage).

0 is initial time.


initTime

private long initTime
Used for verbose information (total time).

0 is initial time.

Constructor Detail

Worker

public Worker(java.lang.String threadName,
              TasksQueue tasksQueue,
              LogicalTargetList logicalTargetList,
              ClientSessions clientSessions,
              CADILog log)
Constructor.

Parameters:
threadName - is a string with the name of the thread.
tasksQueue - definition in tasksQueue.
logicalTargetList - definition in logicalTargetList.
clientSessions - definition in listOfClientSessions.
log - definition in log.
Method Detail

setTargetsPath

public void setTargetsPath(java.lang.String targetsPath)
Sets the targetsPath attribute.

Parameters:
targetsPath - definition in targetsPath.

setCachePath

public void setCachePath(java.lang.String cachePath)
Sets the cachePath attribute.

Parameters:
cachePath - definition in cachePath.

setRateDistortionMethod

public void setRateDistortionMethod(int rateDistortionMethod,
                                    int RDSubType)
Sets the rate-distortion method and the subrate-distortion method.

Parameters:
rateDistortionMethod - definition in rateDistortionMethod.
RDSubType - definition in RDSubType.

setDeliveryProgressionOrder

public void setDeliveryProgressionOrder(int deliveryProgressionOrder)
Sets the deliveryProgressionOrder attribute.

Parameters:
deliveryProgressionOrder - definition in deliveryProgressionOrder.

setKeepAliveTimeout

public void setKeepAliveTimeout(int keepAliveTimeout)
Sets the keepAliveTimeout attribute.

Parameters:
keepAliveTimeout - definition in keepAliveTimeout.

setMaxTxRate

public void setMaxTxRate(float maxTxRate)
Sets the maxTxRate attribute.

Parameters:
maxTxRate - definition in maxTxRate attribute.

setIndependentMessageHeaders

public void setIndependentMessageHeaders(boolean independentMessageHeaders)
Sets the #independentMesssageHeaders attribute.

Parameters:
independentMesssageHeaders - definition in #independentMesssageHeaders attribute.

run

public void run()
This method implements the control of the thread.

When the Scheduler assigns a task, it will be awake. The task may be:

  • Process a client request.
  • Sends a message error to the client.
Moreover, when the keep-alive mode of a client request is set, the thread is dedicated to wait for a new request until the timeout value is reached.

The thread will be running until the finish attribute is false.

Specified by:
run in interface java.lang.Runnable
Overrides:
run in class java.lang.Thread

finish

public void finish()
This method is used to indicate that the thread has to finish.


isBusy

public boolean isBusy()
This method is used to indicate if the thread is or no busy processing a task.

Returns:
true if the thread is processing a task. Otherwise, it returns false.

getState

public java.lang.Thread.State getState()
Overrides:
getState in class java.lang.Thread

processRequest

private void processRequest()
                     throws WarningException
This method performs the core to process the client requests. It is a manager that uses several auxiliary classess and methods to process the client request and to make the server response.

Throws:
WarningException

sessionsManager

public void sessionsManager()
                     throws WarningException
This method is used to manage the client sessions.

Tests if it is a stateless request, if it is a request which belongs to a previous session, or it is a request for a new session. When a stateless request is used, a temporary session is created and it must be removed when the request process finishes. When the request is for a new session, a new entry in the listOfClientSessions is created with the client preferences and capabilities. And if the request belongs to a previous session, then, client data (logical target, image return type, cache, preferences, capabilites, etc. ) are read from the listOfClientSessions.

When an error in the request is found (p.e. session identifier does not exist or are wrong, logical target does not exist, etc.), an error message is sent to the client and a WarningException is thrown.

Throws:
WarningException - when something anomalous (p.e. session identifier does not exist or are wrong, logical target does not exist, etc.) this exception will be thrown.

logicalTargetsManager

private void logicalTargetsManager(java.lang.String target,
                                   java.lang.String tid)
                            throws WarningException
This method is used to manage the list of loaded targets. The targed will be passed through the jpip target field, the jpip tid field, or both.

If the requested target has been loaded in a previous request, it will be in the list of loaded targets. So, its parameters will be recovered from that list.

Otherwise, target will be searched in disk. And if it is in disk, it will be loaded to the list.

Parameters:
target - definition in TargetField.target
tid - definition in TargetField.tid
Throws:
WarningException

cacheManager

private void cacheManager()
This method is used to manage the caches when a session is created or when a cache needs to be update with data received from the client.


listenNewRequest

private void listenNewRequest()
                       throws WarningException,
                              ErrorException
This method will be used to read a HTTP client request. It will be used when the HTTP keep-alive mode is set. Then, this thread is assigned to this client. The received request data will be stored in the httpRequestFields (see

Throws:
WarningException - when an
ErrorException - when the client has closed the socket, the socket reaches its timeout, or an I/O error has occured while client request was being received.

sendHTTPResponseHeader

private void sendHTTPResponseHeader(HTTPResponse httpResponse)
                             throws WarningException
Parameters:
httpResponse -
Throws:
WarningException

sendHTTPResponseError

private void sendHTTPResponseError(int statusCode,
                                   java.lang.String reasonPhrase)
This method will be used to send an HTTP error response to the client.

Parameters:
statusCode - definition in StatusCodes.
reasonPhrase - a reason phrase related with the status code.

encodeJPIPResponseFields

private void encodeJPIPResponseFields()
JPIP HEADERS (See ISO/IEC 15444-9 Annex D)


checkJPIPParameters

private void checkJPIPParameters()
                          throws WarningException
This method tests several JPIP restrictions of the parameters

Throws:
WarningException

closeChannels

private void closeChannels(java.lang.String cid,
                           java.lang.String[] cclose)
This method is used to close session channels.

Parameters:
cid - definition in ChannelField.cid
cclose - definition in ChannelField.cclose

updateCache

private void updateCache(java.util.ArrayList jpipMessageData)
This method is used to update the cache with the data that has been sent to the client. Therefore, it must be called after the response has been sent to the client.

Parameters:
jpipMessageData - an array list with the data that has been sent.

availableReturnTypes

private java.lang.String[] availableReturnTypes()
Gets the available image return types.

Returns:
returns an one-dimension array with the available return types.

resetTime

private void resetTime()
Set the time attributes to 0.


showTimeMemory

private java.lang.String showTimeMemory(java.lang.String stage)
Show some time and memory usage statisticals.

Parameters:
stage - string that will be displayed


CADI - Copyright (C) 2007
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

Group on Interactive Coding of Images (GICI) (contact)