1 package org.sapia.ubik.rmi.server.transport.http; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.IOException ; 5 import java.io.OutputStream ; 6 import java.net.HttpURLConnection ; 7 import java.net.MalformedURLException ; 8 import java.net.URL ; 9 import java.rmi.RemoteException ; 10 11 import org.sapia.ubik.net.ServerAddress; 12 import org.sapia.ubik.rmi.server.VmId; 13 import org.sapia.ubik.rmi.server.transport.MarshalInputStream; 14 import org.sapia.ubik.rmi.server.transport.MarshalOutputStream; 15 import org.sapia.ubik.rmi.server.transport.RmiConnection; 16 17 18 29 public class JdkRmiClientConnection implements RmiConnection { 30 private static final int DEFAULT_BUFSZ = 1024; 31 private static final String POST_METHOD = "POST"; 32 private static final String CONTENT_LENGTH_HEADER = "Content-Length"; 33 private HttpAddress _address; 34 private URL _url; 35 private boolean _closed; 36 private HttpURLConnection _conn; 37 private int _bufsz = DEFAULT_BUFSZ; 38 39 public JdkRmiClientConnection() { 40 } 41 42 45 public void send(Object o, VmId associated, String transportType) 46 throws IOException , RemoteException { 47 _conn = (HttpURLConnection ) _url.openConnection(); 48 _conn.setDoInput(true); 49 _conn.setDoOutput(true); 50 _conn.setUseCaches(false); 51 _conn.setRequestMethod(POST_METHOD); 52 53 ByteArrayOutputStream bos = new ByteArrayOutputStream (_bufsz); 54 MarshalOutputStream mos = new MarshalOutputStream(bos); 55 56 if ((associated != null) && (transportType != null)) { 57 mos.setUp(associated, transportType); 58 } 59 60 mos.writeObject(o); 61 mos.flush(); 62 mos.close(); 63 64 byte[] data = bos.toByteArray(); 65 66 if (data.length > _bufsz) { 67 _bufsz = data.length; 68 } 69 70 _conn.setRequestProperty(CONTENT_LENGTH_HEADER, "" + data.length); 71 72 OutputStream os = _conn.getOutputStream(); 73 os.write(data); 74 os.flush(); 75 os.close(); 76 } 77 78 81 public void close() { 82 if ((_conn != null) && !_closed) { 83 _conn.disconnect(); 84 _closed = true; 85 } 86 } 87 88 91 public ServerAddress getServerAddress() { 92 return _address; 93 } 94 95 98 public Object receive() 99 throws IOException , ClassNotFoundException , RemoteException { 100 if (_conn == null) { 101 throw new IllegalStateException ("Cannot receive; data was not posted"); 102 } 103 104 MarshalInputStream is = new MarshalInputStream(_conn.getInputStream()); 105 106 try { 107 return is.readObject(); 108 } finally { 109 is.close(); 110 } 111 } 112 113 116 public void send(Object o) throws IOException , RemoteException { 117 send(o, null, null); 118 } 119 120 JdkRmiClientConnection setUp(HttpAddress addr) throws RemoteException { 121 _closed = false; 122 123 if (_url == null) { 124 try { 125 _url = new URL (addr.toString()); 126 } catch (MalformedURLException e) { 127 throw new RemoteException (addr.toString(), e); 128 } 129 } 130 131 _address = addr; 132 133 return this; 134 } 135 } 136 | Popular Tags |