/*
* $Id: QuoteHandler.html,v 1.4 2004/03/22 16:52:57 suhrin Exp $
*
* Copyright (c) 1999-2003 Gnome Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Gnome Ltd. You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms
* of the license agreement you entered into with Gnome Ltd.
*/
package SK.gnome.dwarf.sample;
import java.io.*;
import java.net.*;
import SK.gnome.dwarf.*;
import SK.gnome.dwarf.tcpip.*;
/**
* Handles the Quote of the Day Service (RFC 865) protocol.
*/
public class QuoteHandler extends TCPHandler implements Reportable
{ private String report = "_";
/**
* Creates a new <tt>QuoteHandler</tt>.
*/
public QuoteHandler(String name)
{ super(name);
}
/**
* Initializes the service.
*
* <p>It forces the parent server to be an instance of the {@link QuoteServer} class.
*
* <p>Since we need to call the server's {@link QuoteServer#getQuote()} method to obtain the
* quote strings, the initialization process must interrupt if the parent server is not an
* instance of the {@link QuoteServer} class. In order to do it we throw a
* {@link IllegalServiceClassException} to indicate the incompatible container type.
*/
public void init(Server parent) throws ServiceException
{ if (!(parent instanceof QuoteServer))
throw new IllegalServiceClassException(QuoteServer.class);
super.init(parent);
}
/**
* Handles the client connection.
*
* <p>This method does the actual Quote of the Day protocol handling.
*
* <p>The quote string is sent to the client via the socket output stream, followed by the
* CRLF character sequence. The quote string is obtained from the {@link QuoteServer} via
* its {@link QuoteServer#getQuote()} method.
*/
protected void handle(Socket socket)
{ report = socket.toString();
try
{ Writer out = new OutputStreamWriter(socket.getOutputStream());
out.write(((QuoteServer)parent).getQuote());
out.write("\r\n");
out.flush();
out.close();
}
catch (IOException exception)
{ log(LOG_ERROR, "Error while processing request", exception);
}
finally
{ try
{ socket.close();
}
catch (IOException e)
{
}
report = "_";
}
}
/**
* Returns the service report.
*
* <p>It returns the string representation of a socket beeing currently handled, or a string
* with single underscore character, if no socket is handled currently. If the handler is
* stopped at this time, it returns the <tt>"x"</tt> string instead.
*/
public String report()
{ return getName() + ": " + (getState(STARTED) ? report : "x");
}
}
|