Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 8cf016a217aa9e5be31fb8541f989c41ec501ea3 (plain) (blame)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/***************************************************************************
 * Copyright (c) 2004 - 2008 Eike Stepper, Germany.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/
package org.eclipse.net4j.internal.http;

import org.eclipse.net4j.channel.IChannel;
import org.eclipse.net4j.connector.ConnectorException;
import org.eclipse.net4j.connector.ConnectorLocation;
import org.eclipse.net4j.http.INet4jTransportServlet;
import org.eclipse.net4j.internal.util.lifecycle.Worker;
import org.eclipse.net4j.protocol.IProtocol;
import org.eclipse.net4j.util.io.ExtendedDataInputStream;
import org.eclipse.net4j.util.io.ExtendedDataOutputStream;
import org.eclipse.net4j.util.io.IOHandler;
import org.eclipse.net4j.util.io.IORuntimeException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;

/**
 * @author Eike Stepper
 */
public class HTTPClientConnector extends HTTPConnector
{
  private String url;

  private HttpClient httpClient;

  private int maxIdleTime = UNKNOWN_MAX_IDLE_TIME;

  private int pollInterval = DEFAULT_POLL_INTERVAL;

  private long lastRequest = System.currentTimeMillis();

  private boolean requesting;

  private Worker poller = new Worker()
  {
    @Override
    protected void work(WorkContext context) throws Exception
    {
      boolean moreBuffers = tryBuffersRequest();
      context.nextWork(moreBuffers ? 0 : 1000);
    }
  };

  public HTTPClientConnector()
  {
  }

  public ConnectorLocation getLocation()
  {
    return ConnectorLocation.CLIENT;
  }

  public String getURL()
  {
    return url;
  }

  public void setURL(String url)
  {
    this.url = url;
  }

  public int getMaxIdleTime()
  {
    return maxIdleTime;
  }

  public int getPollInterval()
  {
    return pollInterval;
  }

  public void setPollInterval(int pollInterval)
  {
    this.pollInterval = pollInterval;
  }

  @Override
  public void multiplexChannel(IChannel channel)
  {
    super.multiplexChannel(channel);
    tryBuffersRequest();
  }

  @Override
  public String toString()
  {
    if (getUserID() == null)
    {
      return MessageFormat.format("HTTPClientConnector[{0}]", getURL()); //$NON-NLS-1$
    }

    return MessageFormat.format("HTTPClientConnector[{1}@{0}]", getURL(), getUserID()); //$NON-NLS-1$
  }

  @Override
  protected void doBeforeActivate() throws Exception
  {
    super.doBeforeActivate();
    checkArg(url, "url == null");
  }

  @Override
  protected void doActivate() throws Exception
  {
    super.doActivate();
    poller.activate();
    httpClient = createHTTPClient();
    connect();
  }

  @Override
  protected void doDeactivate() throws Exception
  {
    poller.deactivate();
    httpClient = null;
    super.doDeactivate();
  }

  protected HttpClient createHTTPClient()
  {
    return new HttpClient();
  }

  protected PostMethod createHTTPMethod(String url)
  {
    return new PostMethod(url);
  }

  @Override
  protected void registerChannelWithPeer(final int channelID, final short channelIndex, final IProtocol protocol)
      throws ConnectorException
  {
    try
    {
      request(new IOHandler()
      {
        public void handleOut(ExtendedDataOutputStream out) throws IOException
        {
          out.writeByte(INet4jTransportServlet.OPCODE_OPEN_CHANNEL);
          out.writeString(getConnectorID());
          out.writeInt(channelID);
          out.writeShort(channelIndex);
          out.writeString(protocol.getType());
        }

        public void handleIn(ExtendedDataInputStream in) throws IOException
        {
          boolean ok = in.readBoolean();
          if (!ok)
          {
            throw new ConnectorException("Could not open channel");
          }
        }
      });
    }
    catch (RuntimeException ex)
    {
      throw ex;
    }
    catch (IOException ex)
    {
      throw new ConnectorException(ex);
    }
  }

  private void connect() throws IOException
  {
    request(new IOHandler()
    {
      public void handleOut(ExtendedDataOutputStream out) throws IOException
      {
        out.writeByte(INet4jTransportServlet.OPCODE_CONNECT);
        out.writeString(getUserID());
      }

      public void handleIn(ExtendedDataInputStream in) throws IOException
      {
        String connectorID = in.readString();
        maxIdleTime = in.readInt();

        setConnectorID(connectorID);
        leaveConnecting();
      }
    });
  }

  private void request(IOHandler handler) throws IOException, HttpException
  {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ExtendedDataOutputStream out = new ExtendedDataOutputStream(baos);
    handler.handleOut(out);
    out.flush();
    byte[] content = baos.toByteArray();
    PostMethod method = createHTTPMethod(url);
    method.setRequestEntity(new ByteArrayRequestEntity(content));

    httpClient.executeMethod(method);
    InputStream bodyInputStream = method.getResponseBodyAsStream();
    ExtendedDataInputStream in = new ExtendedDataInputStream(bodyInputStream);
    handler.handleIn(in);
    method.releaseConnection();
  }

  private boolean tryBuffersRequest()
  {
    synchronized (poller)
    {
      if (requesting)
      {
        return false;
      }

      if (getOutputQueue().isEmpty() && System.currentTimeMillis() - lastRequest < pollInterval)
      {
        return false;
      }

      requesting = true;
    }

    try
    {
      final boolean moreBuffers[] = { false };
      request(new IOHandler()
      {
        public void handleOut(ExtendedDataOutputStream out) throws IOException
        {
          out.writeByte(INet4jTransportServlet.OPCODE_BUFFERS);
          out.writeString(getConnectorID());
          moreBuffers[0] = writeOutputBuffers(out);
        }

        public void handleIn(ExtendedDataInputStream in) throws IOException
        {
          readInputBuffers(in);
        }
      });

      lastRequest = System.currentTimeMillis();
      return moreBuffers[0];
    }
    catch (IOException ex)
    {
      throw new IORuntimeException(ex);
    }
    finally
    {
      synchronized (poller)
      {
        requesting = false;
      }
    }
  }
}

Back to the top