Java API

his chapter shows the Java API, the interface for writing server functions in Java. The interface consists of four classes:

Class netscape.server.applet.HttpApplet

java.lang.Object 
	| 
	+----netscape.server.applet.ServerApplet 
		| 
		+----netscape.server.applet.HttpApplet
This class extends ServerApplet, and implements HTTP-specific features of server applets. You should subclass this class, and implement the run method to create server-side Java scripts.

Variables

The variables of the netscape.server.applet.HttpApplet class are shown below. By convention, constants are named in uppercase letters.

BAD_REQUEST

The constant BAD_REQUEST is a status code indicating the request was invalid.

Syntax

public final static int BAD_REQUEST

boundaryCount

The variable boundaryCount represents the top of the boundaryStack.

Syntax

protected int boundaryCount

See Also

boundaryStack, returnMultipartResponse

boundaryGen

The variable boundaryGen represents the counter used to automatically generate unique boundary markers.

Syntax

protected static int boundaryGen

See Also

returnMultipartResponse

boundaryStack

The variable boundaryStack is a stack of strings corresponding to the boundary markers for the currently in progress multipart responses. The boundaryCount property maintains the top of this stack.

Syntax

protected Vector boundaryStack

See Also

boundaryCount, returnMultipartResponse

FORBIDDEN

The constant FORBIDDEN is a status code indicating that access is forbidden.

Syntax

public final static int FORBIDDEN

formData

The variable formData is the Hashtable that is cached after calling getFormData. It is used later by getFormField.

Syntax

protected Hashtable formData

See Also

getFormData, getFormField

NO_RESPONSE

The constant NO_RESPONSE is a status code indicating no response is to be returned.

Syntax

public final static int NO_RESPONSE

NOT_FOUND

The constant NOT_FOUND is a status code indicating the requested document was not found.

Syntax

public final static int NOT_FOUND

NOT_IMPLEMENTED

The constant NOT_IMPLEMENTED is a status code indicating the requested feature is not implemented.

Syntax

public final static int NOT_IMPLEMENTED

NOT_MODIFIED

The constant NOT_MODIFIED is a status code indicating the requested document is not modified.

Syntax

public final static int NOT_MODIFIED

OK

The constant OK is a status code indicating no error.

Syntax

public final static int OK

REDIRECT

The constant REDIRECT is a status code indicating a redirect is to occur.

Syntax

public final static int REDIRECT

SERVER_ERROR

The constant SERVER_ERROR is a status code indicating that a server error has occurred.

Syntax

public final static int SERVER_ERROR

UNAUTHORIZED

The constant UNAUTHORIZED is a status code indicating that access was unauthorized.

Syntax

public final static int UNAUTHORIZED

Constructor

The constructor of the netscape.server.applet.HttpApplet class is shown below.

public HttpApplet()

Syntax

public HttpApplet()

Methods

The methods of the netscape.server.applet.HttpApplet class are shown below.

getMethod

The getMethod method gets the method of an HTTP request. This is a shorthand for getting the method request property.

Syntax

public String getMethod()

Returns

a String corresponding to the method of the client HTTP request (e.g. "GET", "HEAD", "POST")

getURI

The getURI method returns the URI portion of the client HTTP request as a URL object. The URL is formed relative to the URL returned by getURL.

Syntax

public URL getURI() throws MalformedURLException

Returns

a URL object representing the URI

Throws

MalformedURLException if for some reason the URL cannot be constructed.

See Also

getURL

getProtocol

The getProtocol method gets the protocol of an HTTP request. This is a shorthand for getting the protocol request property.

Syntax

public String getProtocol()

Returns

a String corresponding to the protocol

getQuery

The getQuery method gets the query string of an HTTP request. This is a shorthand for getting the query request property.

Syntax

public String getQuery()

Returns

a String corresponding to the query string

getPath

The getPath method gets the path of an HTTP request. This is a shorthand for getting the path server property.

Syntax

public String getPath()

Returns

a String corresponding to the path

setContentType

The setContentType method sets the content type for an HTTP response. This is a shorthand for setting the Content-Type response property.

Syntax

public void setContentType(String type)

Returns

a String corresponding to the query string

getURL

The getURL method gets the URL of an HTTP request. This is a shorthand for getting the url server property.

Syntax

public URL getURL() throws MalformedURLException

Returns

a URL object

returnNormalResponse--one parameter

The returnNormalResponse method starts an HTTP response to the request. The content type will be set to the specified value, any headers established by calling setResponseProperty will be sent and the status will be returned as OK.

Syntax

public boolean returnNormalResponse(String contentType) throws 
IOException
Calls to the returnNormalResponse method may be nested within returnMultipartResponse/endMultipartResponse blocks and will output the appropriate boundary and header information as needed.

Parameters

contentType--a String denoting the type of the content to be returned

Returns

returnNormalResponse--two parameters

The returnNormalResponse method starts an HTTP response to the request given a file to stat for appropriate header data. The content type will be set to the specified value, any headers established by calling setResponseProperty will be sent and the status will be returned as OK.

Syntax

public boolean returnNormalResponse(String contentType, 
	File statFile) throws IOException

Parameters

contentType--a String denoting the type of the content to be returned

statFile--the file to stat

Returns

returnFile--two parameters

The returnFile method starts an HTTP response to the request returning the contents of a file.

Syntax

public void returnFile(String contentType, 
File file) throws IOException

Parameters

contentType--a String denoting the type of the content to be returned

file--the file to stat and whose contents is to be returned

returnFile--one parameter

The returnFile method starts an HTTP response to the request returning the contents of a file. The file's content type is derived from the file's extension (e.g. movie.gif will be returned as type image/gif).

Syntax

public void returnFile(File file) throws IOException

returnErrorResponse--three parameters

The returnErrorResponse method starts an HTTP error response to the request.

Syntax

public boolean returnErrorResponse(String contentType, 
	int status, 
	String reason) throws IOException

Parameters

contentType--a String denoting the type of the content to be returned,

status--the error status code to be returned

reason--a String describing the error to be recorded in the server's error log

Example

try { 
... 
} catch (Exception e) { 
	if (returnErrorResponse("text/html", BAD_REQUEST, 
		"advise user: " + e)) { 
		PrintStream out = getOutputStream(); 
		out.println("<html>< title>Wrong!< /title>We're so sorry.  
				Please try again.< /html>"); 
	} 
}

returnErrorResponse--two parameters

The returnErrorResponse method starts an HTTP error response to the request without a reason message string.

Syntax

public boolean returnErrorResponse(String contentType, 
	int status) throws IOException

Parameters

contentType--a String denoting the type of the content to be returned

status--the error status code to be returned

returnMultipartResponse--one parameter

The returnMultipartResponse method initiates a multipart response. A boundary marker is automatically generated for this multipart response. Multipart responses must be terminated by calling endMultipartResponse. Multipart and normal responses can be nested arbitrarily, and the boundary markers will be automatically inserted between each response.

Syntax

public synchronized boolean returnMultipartResponse(String subtype) 
	throws IOException

Parameters

subtype--the subtype of the content-type to be returned (the string "multipart/" is prepended to this string)

Returns

returnMultipartResponse--two parameters

The returnMultipartResponse method initiates a multipart response with an explicit boundary marker.

Syntax

public boolean returnMultipartResponse(String subtype, 
	String boundary) throws IOException

Parameters

subtype--the subtype of the content-type to be returned (the string "multipart/" is prepended to this string),

boundary--a String to be used as a boundary marker

Returns

endMultipartResponse

The endMultipartResponse method ends a multipart response. This method must be called to close the most recent multipart scope causing the final boundary marker to be appended to the response.

Syntax

public void endMultipartResponse() throws IOException

See also

returnMultipartResponse

startResponse

The startResponse method starts the HTTP response to the request. Any headers established by calling setResponseProperty will be sent along with the status code established by setStatus. This is a low-level (protected) method that doesn't deal with multipart responses directly.

Syntax

protected int startResponse() throws IOException

Returns

setStatus--two parameters

The setStatus method sets the setStatus to the given integer code.

Syntax

public void setStatus(int n, String reason)

Parameters

n--the integer code status

reason--a description of the status

setStatus--one parameter

The setStatus method sets the status to the given integer code. The reason string will be a default internal string for the given code.

Syntax

public void setStatus(int n)

Parameters

n--the integer code status

setFileInfo

The setFileInfo method sets the HTTP response headers according to the given file. If the client gave a conditional request (that is, asks that the object be sent only if it has changed since a certain date), this function returns ABORTED to indicate that the calling function should not proceed with the request.

Syntax

public int setFileInfo(File file)

Parameters

file--the file to stat

Returns

translateURI

The translateURI method translates a URI or virtual path into a file system path using the server's name translation facilities.

Syntax

public String translateURI(String uri)

Parameters

uri--the String to translate

Returns

uri2url

The uri2url method generates a full URL from a prefix and suffix string. The prefix and suffix strings are concatenated to form the URL after the http://host:port part. Either prefix or suffix can be null.

Syntax

public static String uri2url(String prefix, String suffix)

Parameters

prefix--the prefix String

suffix--the suffix String

Returns

the full URL String

getFormData

The getFormData method returns a Hashtable of form data of the HTTP request. The name-value pairs are separated (delimited by '&&' characters) such that the names become the keys to the Hashtable. The values are also decoded from their URI-encoded form.

Syntax

public Hashtable getFormData() throws IOException

Returns

a Hashtable of the decoded form data

Throws

IOException

if the request does not have form data attached, or any of the parameters the client gave are not valid.

getFormField

The getFormField method returns a form field of the HTTP request.

Syntax

public String getFormField(String fieldName) throws IOException

Parameters

fieldName--the name of the form field to return

Returns

the decoded form data of the field

Throws

IOException

if the request does not have form data attached, or any of the parameters the client gave are not valid.

handleRequest

The server calls the handleRequest method to process an incoming client request. In addition to performing the work of the method inherited from ServerApplet, the content-type of the response is set to text/plain if left unspecified by the user.

Syntax

protected int handleRequest(int rq)

Overrides

handleRequest in class ServerApplet

Class netscape.server.applet.Server

java.lang.Object 
	| 
	+----netscape.server.applet.Server
The public class Server extends Object, and embodies properties of the server.

See Also:

getServer

Variables

The class netscape.server.applet.Server defines no variables.

Methods

The methods of the netscape.server.applet.Server class are shown below.

getAddress

The getAddress method returns the address of the server. The name of this address is a fully qualified domain name, and does not necessarily have to be the machine's host name, but it's what the administrator wants to appear in URLs.

Syntax

public InetAddress getAddress()

Returns

the address of the server

getListeningAddress

The getListeningAddress method returns the IP address to which this server listens. If the server does not listen to every IP address on the system, this specifies the specific address.

Syntax

public InetAddress getListeningAddress()

Returns

the IP address the server is listening to

getListeningPort

The getListeningPort method returns the port number to which this server listens.

Syntax

public int getListeningPort()

Returns

the port number the server is listening to

securityActive

The securityActive method determines whether this server is a Netscape Enterprise server encrypting data to and from the clients.

Syntax

public boolean securityActive()

Returns

true if security is active

Class netscape.server.applet.ServerApplet

java.lang.Object 
	| 
	+----netscape.server.applet.ServerApplet
This public class extends Object, and specifies the protocol-independent functionality of server applets. Server applets are the Java equivalent of CGI scripts. Subclasses of ServerApplet provide protocol-specific features to client requests (e.g. HttpApplet). Servers instantiate subclasses of ServerApplet to respond to client requests (e.g. ns-httpd constructs an HttpApplet for each client request). A server applet corresponds to a session, and the invocation of its run method corresponds to a particular request made during that session.

See Also:

HttpApplet

Variables

The variables of the netscape.server.applet.ServerApplet class are shown below. By convention, constants are named in uppercase letters.

ABORTED

The constant ABORTED is returned by the handleRequest method to indicate that an error was detected, and the request cannot proceed.

Syntax

protected final static int ABORTED

See Also

handleRequest

EXIT

The constant EXIT is returned by the handleRequest method to indicate that the client is unreachable. Processing of the request is stopped but an error is not reported.

Syntax

protected final static int EXIT

See Also

handleRequest

name

The variable name is the name of the server applet. This name is reported in all log messages.

Syntax

protected String name

NOACTION

The constant NOACTION is returned by the handleRequest method to indicate that no response is to be delivered to the client (presumably because the client performed a HEAD request).

Syntax

protected final static int NOACTION

See Also

handleRequest

PROCEED

The constant PROCEED is returned by the handleRequest method to indicate successful completion of the request.

Syntax

protected final static int PROCEED

See Also

handleRequest

responseStarted

The variable responseStarted is a boolean indicating whether a response has been initiated for the client request.

Syntax

protected boolean responseStarted

See Also

returnNormalResponse, returnMultipartResponse, returnFile, returnErrorResponse

socket

The variable socket is the socket of the incoming client request. For server-plug-in-API-based servers, this socket is associated with the inbuf netbuf of the Session structure.

Syntax

protected Socket socket

Constructor

ServerApplet

Syntax

public ServerApplet()

Methods

The methods of the netscape.server.applet.ServerApplet class are shown below.

getClientSocket

The getClientSocket method returns the socket which connects the server applet to the client. The IP address of the client can be obtained by calling getAddress on the socket returned.

Syntax

public Socket getClientSocket()

getClientProperty

The getClientProperty method retrieves properties of the client request. For server-plug-in-API-based servers, this corresponds to the client pblock of the Session structure. Of note are the properties:

getConfigProperty

The getConfigProperty method retrieves parameters given by the site administrator for this server applet's invocation. For server-plug-in-API-based servers, this corresponds to the pb pblock parameter of the server application function.

Syntax

public String getConfigProperty(String name)

Parameters

name--the name of the property to access

Returns

the value of the property

getHeader

The getHeader method retrieves headers from the request. For server-plug-in-API-based servers, this corresponds to the headers pblock of the Request structure.

HTTP requests have RFC822 headers attached, which are actually name-value pairs. Convert the header name you want to access to lowercase, and this function will return its value if the client sent it.

Syntax

public String getHeader(String name)

Example

Client sends: User-agent: Mozilla/1.1N

Then: getHeader("user-agent") == "Mozilla/1.1N"

Parameters

name--the name of the header to access

Returns

the value of the header

getInputStream

The getInputStream method returns the InputStream to be used for reading input from the client connection.

Syntax

public InputStream getInputStream() throws IOException

getOutputStream

The getOutputStream method returns the PrintStream to be used for writing text output which is to appear in the response to be sent to the client.

Syntax

public PrintStream getOutputStream() throws IOException

getRequestProperty

The getRequestProperty method retrieves properties of the client request. For server-plug-in-API-based servers, this corresponds to the reqpb pblock of the Request structure.

For HTTP, the request properties include:

Syntax

public String getRequestProperty(String name)

Parameters

name--the name of the property to access

Returns

the value of the property

getResponseProperty

The getResponseProperty method gets properties which are to be returned as the result of the client response. This is handy if you want to see what responses are going to be sent. For server-plug-in-API-based servers, this accesses the srvhdrs pblock of the Request structure.

Syntax

public String getResponseProperty(String name)

Parameters

name--the name of the property to access

Returns

the value of the property

getServer

The getServer method returns a Server object which may be queried for information about the server in which the server applet is running.

Syntax

public static Server getServer()

getServerProperty

The getServerProperty method retrieves properties representing the server's working variables. For server-plug-in-API-based servers, this corresponds to the vars pblock of the Request structure. The set of active variables is different depending on which step of the request the server is processing.

Syntax

public String getServerProperty(String name)

Parameters

name--the name of the property to access

Returns

the value of the property

handleRequest

The server calls the handleRequest method to process an incoming client request. It may be overridden by subclasses of ServerApplet to perform protocol-specific request handling (see HttpApplet.handleRequest).

The default implementation dispatches to the server applet's run method.

Syntax

protected int handleRequest(int rq)

Parameters

rq--the native request record structure

Returns

See Also

handleRequest, PROCEED, ABORTED, NOACTION, EXIT

inform

The inform method records an informational message in the server's error log.

Syntax

public void inform(String error)

Parameters

error--a String describing what went wrong

reportMisconfiguration

The reportMisconfiguration method records a misconfiguration, or a missing or illegal parameter in the server's error log.

Syntax

public void reportMisconfiguration(String error)

Parameters

error--a String describing what went wrong

reportCatastrophe

The reportCatastrophe method records a catastrophic failure in the server's error log.

Syntax

public void reportCatastrophe(String error)

Parameters

error--a String describing what went wrong

reportFailure

The reportFailure method records a general failure in the server's error log.

Syntax

public void reportFailure(String error)

Parameters

error--a String describing what went wrong

reportSecurity

The reportSecurity method records a security violation in the server's error log, or the fact that someone trying to access a resource they shouldn't.

Syntax

public void reportSecurity(String error)

Parameters

error--a String describing what went wrong

run

The run method performs the work fulfilling the request made to the server. It must be overridden by the individual server applets. Any exceptions raised by the run method will communicate failure of the request back to the client, and log the failure in the server's log file. The run method is called by the system, via handleRequest.

Syntax

public void run() throws Exception

Throws

any exception indicating failure of the request. The following exception classes cause log messages to be generated by the following report methods:

See Also

handleRequest

setResponseProperty

The setResponseProperty method sets properties to be returned as the result of the client response. For server-plug-in-API-based servers, this inserts into the srvhdrs pblock of the Request structure.

Syntax

public void setResponseProperty(String name, String value)

Parameters

name--the name of the property to access

value--the value to which the property is set

warn

The warn method records a warning in the server's error log.

Syntax

public void warn(String error)

Parameters

error--a String describing what went wrong.

Class netscape.server.applet.URIUtil

java.lang.Object 
	| 
	+----netscape.server.applet.URIUtil
The public class URIUtil extends Object, and provides utilities for dealing with URIs in ways a typical server application might need to. The terms used in this section are as follows:

Variables

The class netscape.server.applet.URIUtil defines no variables.

Methods

The methods of the netscape.server.applet.URIUtil class are shown below.

isEvil

The isEvil method checks a URI to make sure it is not going to be used to circumvent server access controls. It scans for any instance of

../

./

or //

in the URI. Although such URIs are legal, the Netscape server will not allow them, and will not parse them into other forms because it wants to make sure that only one URL can refer to each document.

Syntax

public static boolean isEvil(String uri)

Returns

splitFormData

The splitFormData method takes a String of form data, with each name-value pair separated by & characters, places them into a new Hashtable, and decodes any encoded characters in the values.

Syntax

public static Hashtable splitFormData(String data)

Returns

the new Hashtable

uriEscape

The uriEscape method takes an arbitrary String, and escapes it using the URL conventions. The ?, #, and : characters will be escaped, which is why this function should not be used for URLs. Returns a new String with characters that should be encoded replaced with %xx according to URL conventions.

Syntax

public static String uriEscape(String uri)

Returns

a new String with the characters ?, #, and : escaped

urlEscape

The urlEscape method takes an arbitrary String, and escapes it using the URL conventions. The ?, #, and : characters are not escaped, making this function suitable for URLs. Returns a new String with characters that should be encoded replaced with %xx according to URL conventions.

Syntax

public static String urlEscape(String url)

Returns

a new String with the characters ?, #, and : escaped

urlUnescape

The urlUnescape method takes a String which is encoded using URL conventions, and converts any %xx characters into their character equivalents. Returns a new String with the decoded message.

Syntax

public static String urlUnescape(String url) throws 
NumberFormatException

Returns

a new String with the characters ?, #, and : restored

Throws

NumberFormatException

when given a String with % characters but no number after it, such as foo%bar.