| 1 package org.sapia.ubik.rmi.server.transport.http; 2 3 import java.io.ByteArrayInputStream ; 4 import java.io.ByteArrayOutputStream ; 5 import java.io.IOException ; 6 import java.rmi.RemoteException ; 7 8 import org.apache.commons.httpclient.HttpClient; 9 import org.apache.commons.httpclient.methods.PostMethod; 10 import org.sapia.ubik.net.ServerAddress; 11 import org.sapia.ubik.rmi.server.VmId; 12 import org.sapia.ubik.rmi.server.transport.MarshalInputStream; 13 import org.sapia.ubik.rmi.server.transport.MarshalOutputStream; 14 import org.sapia.ubik.rmi.server.transport.RmiConnection; 15 16 17 32 public class HttpRmiClientConnection implements RmiConnection { 33 private static final int DEFAULT_BUFSZ = 1024; 34 private HttpAddress _address; 35 private HttpClient _client; 36 private PostMethod _post; 37 private boolean _closed; 38 private int _bufsz = DEFAULT_BUFSZ; 39 40 44 public HttpRmiClientConnection() { 45 } 46 47 50 public void send(Object o, VmId associated, String transportType) 51 throws IOException , RemoteException { 52 _post = new PostMethod(_address.toString()); 53 54 ByteArrayOutputStream bos = new ByteArrayOutputStream (_bufsz); 55 MarshalOutputStream mos = new MarshalOutputStream(bos); 56 57 if ((associated != null) && (transportType != null)) { 58 mos.setUp(associated, transportType); 59 } 60 61 mos.writeObject(o); 62 mos.flush(); 63 mos.close(); 64 65 byte[] data = bos.toByteArray(); 66 67 if (data.length > _bufsz) { 68 _bufsz = data.length; 69 } 70 71 _post.setRequestContentLength(data.length); 72 _post.setRequestBody(new ByteArrayInputStream (data)); 73 _client.executeMethod(_post); 74 } 75 76 79 public void close() { 80 if ((_post != null) && !_closed) { 81 _post.releaseConnection(); 82 _closed = true; 83 } 84 } 85 86 89 public ServerAddress getServerAddress() { 90 return _address; 91 } 92 93 96 public Object receive() 97 throws IOException , ClassNotFoundException , RemoteException { 98 if (_post == null) { 99 throw new IllegalStateException ("Cannot receive; data was not posted"); 100 } 101 102 MarshalInputStream is = new MarshalInputStream(_post.getResponseBodyAsStream()); 103 104 try { 105 return is.readObject(); 106 } catch (IOException ioe) { 107 System.err.println(((ioe.getMessage() + "\nHTTP RESPONSE:\n" + _post) == null) 108 ? "null" : _post.getResponseBodyAsString()); 109 throw ioe; 110 } finally { 111 is.close(); 112 } 113 } 114 115 118 public void send(Object o) throws IOException , RemoteException { 119 send(o, null, null); 120 } 121 122 HttpRmiClientConnection setUp(HttpClient client, HttpAddress addr) { 123 _closed = false; 124 _client = client; 125 _address = addr; 126 127 return this; 128 } 129 } 130 | Popular Tags |