home *** CD-ROM | disk | FTP | other *** search
Java Source | 1996-08-14 | 2.6 KB | 135 lines |
- // Message.java
- // A message for sending and receiving. Consists of headers (name and values)
- // and possibly data.
- import java.util.Vector;
- import CryptConnection;
- import java.io.IOException;
- import java.io.EOFException;
-
- public class Message
- {
- Vector names = new Vector();
- Vector values = new Vector();
- byte data[];
-
- // Construct and empty message
- Message()
- {
- }
-
- // Construct a message from a connection
- Message(LineInputStream c) throws IOException,EOFException
- {
- String line;
- // Skip non-headers
- while(true) {
- line = c.gets();
- int cln = line.indexOf(':'), spc = line.indexOf(' ');
- if (cln != -1 && (spc == -1 || spc > cln))
- break; // this is valid
- }
-
- // Read headers
- do {
- int cln = line.indexOf(':');
- if (cln < 0 || cln == line.length()-1)
- throw new IOException("Bogus header");
- add(line.substring(0, cln), line.substring(cln+1).trim());
- line = c.gets();
- } while(line.length() > 0);
-
- // Read data (if there is any)
- String cl = find("Content-length");
- if (cl != null) {
- data = new byte[Integer.parseInt(cl)];
- c.readdata(data);
- }
- }
-
- // find
- // Get the value for a named header, or null.
- public String find(String name)
- {
- for(int i=0; i<names.size(); i++)
- if (((String)names.elementAt(i)).equalsIgnoreCase(name))
- return (String)values.elementAt(i);
- return null;
- }
-
- // name
- // Get the name of header i
- public String name(int i)
- {
- return (String)names.elementAt(i);
- }
-
- // value
- // Get the value of header i
- public String value(int i)
- {
- return (String)values.elementAt(i);
- }
-
- // size
- // Return the number of headers
- public int size()
- {
- return names.size();
- }
-
- // send
- // Transmit the message
- public void send(LineOutputStream c)
- {
- try {
- for(int i=0; i<names.size(); i++) {
- String n = (String)names.elementAt(i);
- String v = (String)values.elementAt(i);
- c.puts(n+": "+v);
- }
- c.puts("");
- if (data != null)
- c.write(data);
- }
- catch(IOException e);
- }
-
- // add
- // Add a header-value pair, overwriting any existing pair with
- // the same name.
- public void add(String name, String val)
- {
- delete(name);
- names.addElement(name);
- values.addElement(val);
- }
-
- // delete
- // Remove the header with the given name (if it exists)
- void delete(String h)
- {
- String v = find(h);
- if (v != null) {
- int idx = values.indexOf(v);
- names.removeElementAt(idx);
- values.removeElementAt(idx);
- }
- }
-
- // setdata
- // Set the data to be sent
- public void setdata(byte b[])
- {
- data = b;
- if (b != null) add("Content-length",String.valueOf(b.length));
- }
-
- // getdata
- // Get the data received
- public byte []getdata()
- {
- return data;
- }
- }
-
-