1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package com.mjh.switchrmi.transport.http;
27
28 import com.mjh.switchrmi.*;
29 import com.sonalb.net.http.cookie.*;
30
31 import java.io.ByteArrayOutputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35
36 import java.net.URL;
37 import java.net.URLConnection;
38
39 import java.util.*;
40
41 import org.apache.log4j.Logger;
42
43 public class HttpClientTransport
44 extends RmiTransportBase
45 {
46 private static final Logger log =
47 Logger.getLogger(HttpClientTransport.class.getName());
48 private URLConnection connection;
49 private ByteArrayOutputStream out;
50 private Client cookieClient = new Client();
51
52 public HttpClientTransport()
53 {
54 super.setType(RmiTransport.SYNCHRONOUS);
55 super.setName("http");
56 }
57
58 public void send(RmiContext context)
59 throws Exception
60 {
61 URL url = new URL(context.getUrl());
62
63 connection = url.openConnection();
64 connection.setRequestProperty(RmiHeaders.CONTENT_TYPE,
65 context.getProtocol().getMimeType());
66 connection.setRequestProperty(RmiHeaders.CONTENT_LENGTH,
67 String.valueOf(out.size()));
68 connection.setRequestProperty(RmiHeaders.LOCATION, context.getUrl());
69
70 CookieJar cookies = (CookieJar) context.getSessionIdentifier();
71
72 log.debug("send() cookies = " + cookies);
73
74 if (cookies != null)
75 {
76 cookieClient.setCookies(connection, cookies);
77 }
78
79 connection.setDoOutput(true);
80 out.writeTo(connection.getOutputStream());
81 out.close();
82 out = null;
83 }
84
85 public void recv(RmiContext context)
86 {
87 Object sessionID = getSessionIdentifier();
88
89 if (sessionID != null)
90 {
91 context.setSessionIdentifier(sessionID);
92 }
93 }
94
95 public InputStream getInputStream(RmiContext context)
96 throws IOException
97 {
98 return connection.getInputStream();
99 }
100
101 public OutputStream getOutputStream(RmiContext context)
102 throws IOException
103 {
104 out = new ByteArrayOutputStream();
105
106 return out;
107 }
108
109 public Object getSessionIdentifier()
110 {
111 CookieJar cookies = null;
112
113 try
114 {
115 cookies = cookieClient.getCookies(connection);
116
117 if (cookies.isEmpty())
118 {
119 cookies = null;
120 }
121
122 log.debug("getSessionIdentifier() cookies = " + cookies);
123 }
124 catch (Exception ex)
125 {
126 log.info("getSessionIdentifier()", ex);
127 }
128
129 return cookies;
130 }
131 }