use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.
the class TestHttpResponseProcessor method testErrorServerResponseChunking.
@Test
public void testErrorServerResponseChunking() throws DatabusException {
Logger log = Logger.getLogger("GenericHttpResponseHandler.testErrorServerResponseChunking");
final GenericHttpResponseHandler responseHandler = new GenericHttpResponseHandler(KeepAliveType.KEEP_ALIVE);
responseHandler.getLog().setLevel(_logLevel);
TestHttpResponseProcessor respProcessor = new TestHttpResponseProcessor(log);
TestConnectListener connectListener = new TestConnectListener(log);
TestSendRequestListener requestListener = new TestSendRequestListener(log);
TestCloseListener closeListener = new TestCloseListener(log);
responseHandler.setConnectionListener(connectListener);
Channel channel = createClientBootstrap(responseHandler);
SocketAddress clientAddr = channel.getLocalAddress();
try {
setListeners(responseHandler, respProcessor, requestListener, closeListener);
channel.write(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/test"));
//It seems that there is a race condition between the writeFuture succeeding
//and the writeComplete message getting to the handler. Make sure that the
//writeComplete has got to the handler before we do anything else with
//the channel.
final GenericHttpResponseHandler handler = getResponseHandler(channel);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return handler._messageState.hasSentRequest();
}
}, "request sent", 1000, log);
HttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE);
resp.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
sendServerResponse(clientAddr, resp, 2000);
HttpChunk chunk1 = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer("chunk1".getBytes(Charset.defaultCharset())));
sendServerResponse(clientAddr, chunk1, 1000);
sendServerResponse(clientAddr, new DefaultHttpChunkTrailer(), 1000);
final List<String> callbacks = respProcessor.getCallbacks();
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return 4 == callbacks.size();
}
}, "waiting for response processed", 1000, null);
final List<String> connectCallbacks = connectListener.getCallbacks();
final List<String> requestCallbacks = requestListener.getCallbacks();
final List<String> closeCallbacks = closeListener.getCallbacks();
stateSanityCheck(connectCallbacks, requestCallbacks, callbacks, closeCallbacks);
Assert.assertEquals(callbacks.get(0), "startResponse");
Assert.assertEquals(callbacks.get(1), "addChunk");
Assert.assertEquals(callbacks.get(2), "addTrailer");
Assert.assertEquals(callbacks.get(3), "finishResponse");
TestUtil.sleep(500);
//make sure that no new callbacks have showed up
Assert.assertEquals(callbacks.size(), 4);
} finally {
channel.close();
}
}
use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.
the class TestHttpResponseProcessor method testEarlyServerCloseChunking.
@Test
public void testEarlyServerCloseChunking() throws DatabusException {
Logger log = Logger.getLogger("GenericHttpResponseHandler.testEarlyServerCloseChunking");
final GenericHttpResponseHandler responseHandler = new GenericHttpResponseHandler(KeepAliveType.KEEP_ALIVE);
responseHandler.getLog().setLevel(_logLevel);
TestHttpResponseProcessor respProcessor = new TestHttpResponseProcessor(log);
TestConnectListener connectListener = new TestConnectListener(log);
TestSendRequestListener requestListener = new TestSendRequestListener(log);
TestCloseListener closeListener = new TestCloseListener(log);
responseHandler.setConnectionListener(connectListener);
Channel channel = createClientBootstrap(responseHandler);
Assert.assertTrue(channel.isConnected());
final SocketAddress clientAddr = channel.getLocalAddress();
try {
setListeners(responseHandler, respProcessor, requestListener, closeListener);
channel.write(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/test"));
//It seems that there is a race condition between the writeFuture succeeding
//and the writeComplete message getting to the handler. Make sure that the
//writeComplete has got to the handler before we do anything else with
//the channel.
final GenericHttpResponseHandler handler = getResponseHandler(channel);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return handler._messageState.hasSentRequest();
}
}, "request sent", 1000, log);
HttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
resp.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return null != _dummyServer.getChildChannel(clientAddr);
}
}, "make sure we have all tracking populated for client connection", 1000, log);
sendServerResponse(clientAddr, resp, 1000);
HttpChunk chunk1 = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer("chunk1".getBytes(Charset.defaultCharset())));
sendServerResponse(clientAddr, chunk1, 1000);
TestUtil.sleep(200);
sendServerClose(clientAddr, -1);
final List<String> callbacks = respProcessor.getCallbacks();
final List<String> closeCallbacks = closeListener.getCallbacks();
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return 3 == callbacks.size() && 1 == closeCallbacks.size();
}
}, "waiting for response processed", 1000, null);
final List<String> connectCallbacks = connectListener.getCallbacks();
final List<String> requestCallbacks = requestListener.getCallbacks();
stateSanityCheck(connectCallbacks, requestCallbacks, callbacks, closeCallbacks);
Assert.assertEquals(callbacks.get(0), "startResponse");
Assert.assertEquals(callbacks.get(1), "addChunk");
// we get Exception, no ChannelClose
Assert.assertTrue(callbacks.get(2).startsWith("channelException"));
//make sure that no new callbacks have showed up
Assert.assertEquals(callbacks.size(), 3);
} finally {
channel.close();
}
}
use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.
the class DummySuccessfulErrorCountingConsumer method captureAndReplyRegisterRequest.
private void captureAndReplyRegisterRequest(SimpleObjectCaptureHandler objCapture, SimpleTestServerConnection relay, SocketAddress clientAddr, final DatabusSourcesConnection clientConn, Logger log) throws JsonGenerationException, JsonMappingException, IOException {
log.debug("process the /register request");
NettyTestUtils.waitForHttpRequest(objCapture, "/register.*", 1000);
objCapture.clear();
log.debug("send back the /register response");
RegisterResponseEntry entry = new RegisterResponseEntry(1L, (short) 1, SOURCE1_SCHEMA_STR);
String responseStr = NettyTestUtils.generateRegisterResponse(entry);
HttpResponse registerResp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
HttpChunk body = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer(responseStr.getBytes(Charset.defaultCharset())));
NettyTestUtils.sendServerResponses(relay, clientAddr, registerResp, body);
log.debug("make sure the client processes the response /register correctly");
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
DispatcherState dispState = clientConn.getRelayDispatcher().getDispatcherState();
return null != dispState.getSchemaMap() && 1 == dispState.getSchemaMap().size();
}
}, "client processes /register response", 100, log);
}
use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.
the class DummySuccessfulErrorCountingConsumer method testInStreamError.
/**
* Tests the logic of the client to disconnect from a relay while still processing
* data from the relay. We want to make sure that ChunkedBodyReadableByteChannel
* and thus the StreamHttpResponseProcessor do net get blocked with unprocessed data.
* One way to trigger such an error is to insert some invalid data inside the
* response and then some more data ( > 4MB which is the current buffer size). */
@Test
public void testInStreamError() throws Exception {
final Logger log = Logger.getLogger("TestDatabusHttpClient.testInStreamError");
//log.setLevel(Level.DEBUG);
final int eventsNum = 20;
DbusEventInfo[] eventInfos = createSampleSchema1Events(eventsNum);
//simulate relay buffers
DbusEventBuffer relayBuffer = new DbusEventBuffer(_bufCfg);
relayBuffer.start(0);
writeEventsToBuffer(relayBuffer, eventInfos, 4);
//prepare stream response
Checkpoint cp = Checkpoint.createFlexibleCheckpoint();
final DbusEventsStatisticsCollector stats = new DbusEventsStatisticsCollector(1, "test1", true, false, null);
ChannelBuffer streamResPrefix = NettyTestUtils.streamToChannelBuffer(relayBuffer, cp, 20000, stats);
final StringBuilder alotOfDeadbeef = new StringBuilder();
for (int i = 0; i < 1024 * 1024; ++i) {
alotOfDeadbeef.append("DEADBEEF ");
}
ChannelBuffer streamResSuf = ChannelBuffers.wrappedBuffer(alotOfDeadbeef.toString().getBytes("UTF-8"));
final ChannelBuffer streamRes = ChannelBuffers.wrappedBuffer(streamResPrefix, streamResSuf);
//create client
_stdClientCfgBuilder.getContainer().setReadTimeoutMs(DEFAULT_READ_TIMEOUT_MS);
final DatabusHttpClientImpl client = new DatabusHttpClientImpl(_stdClientCfgBuilder.build());
final TestConsumer consumer = new TestConsumer();
client.registerDatabusStreamListener(consumer, null, SOURCE1_NAME);
client.start();
try {
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return client._relayConnections.size() == 1;
}
}, "sources connection present", 100, log);
final DatabusSourcesConnection clientConn = client._relayConnections.get(0);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return null != clientConn.getRelayPullThread().getLastOpenConnection();
}
}, "relay connection present", 100, log);
final NettyHttpDatabusRelayConnection relayConn = (NettyHttpDatabusRelayConnection) clientConn.getRelayPullThread().getLastOpenConnection();
final NettyHttpDatabusRelayConnectionInspector relayConnInsp = new NettyHttpDatabusRelayConnectionInspector(relayConn);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return null != relayConnInsp.getChannel() && relayConnInsp.getChannel().isConnected();
}
}, "client connected", 200, log);
//figure out the connection to the relay
Channel clientChannel = relayConnInsp.getChannel();
InetSocketAddress relayAddr = (InetSocketAddress) clientChannel.getRemoteAddress();
SocketAddress clientAddr = clientChannel.getLocalAddress();
int relayPort = relayAddr.getPort();
log.info("relay selected: " + relayPort);
SimpleTestServerConnection relay = null;
for (int i = 0; i < RELAY_PORT.length; ++i) {
if (relayPort == RELAY_PORT[i])
relay = _dummyServer[i];
}
assertTrue(null != relay);
final SocketAddress testClientAddr = clientAddr;
final SimpleTestServerConnection testRelay = relay;
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return null != testRelay.getChildChannel(testClientAddr);
}
}, "relay detects new connection", 1000, log);
Channel serverChannel = relay.getChildChannel(clientAddr);
assertTrue(null != serverChannel);
ChannelPipeline serverPipeline = serverChannel.getPipeline();
SimpleObjectCaptureHandler objCapture = (SimpleObjectCaptureHandler) serverPipeline.get("3");
//process the /sources request
NettyTestUtils.waitForHttpRequest(objCapture, SOURCES_REQUEST_REGEX, 1000);
objCapture.clear();
//send back the /sources response
HttpResponse sourcesResp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
sourcesResp.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
sourcesResp.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
HttpChunk body = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer(("[{\"id\":1,\"name\":\"" + SOURCE1_NAME + "\"}]").getBytes(Charset.defaultCharset())));
NettyTestUtils.sendServerResponses(relay, clientAddr, sourcesResp, body);
//make sure the client processes the response correctly
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
String idListString = clientConn.getRelayPullThread()._currentState.getSourcesIdListString();
return "1".equals(idListString);
}
}, "client processes /sources response", 100, log);
log.debug("process the /register request");
NettyTestUtils.waitForHttpRequest(objCapture, "/register.*", 1000);
objCapture.clear();
log.debug("send back the /register response");
RegisterResponseEntry entry = new RegisterResponseEntry(1L, (short) 1, SOURCE1_SCHEMA_STR);
String responseStr = NettyTestUtils.generateRegisterResponse(entry);
body = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer(responseStr.getBytes(Charset.defaultCharset())));
NettyTestUtils.sendServerResponses(relay, clientAddr, sourcesResp, body);
log.debug("make sure the client processes the response /register correctly");
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
DispatcherState dispState = clientConn.getRelayDispatcher().getDispatcherState();
return null != dispState.getSchemaMap() && 1 == dispState.getSchemaMap().size();
}
}, "client processes /register response", 100, log);
log.debug("process /stream call and return a response with garbled suffix");
NettyTestUtils.waitForHttpRequest(objCapture, "/stream.*", 1000);
objCapture.clear();
final HttpResponse streamResp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
streamResp.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
streamResp.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
//send the response asynchronously in case the client blocks
final Thread streamRespThread = new Thread(new Runnable() {
@Override
public void run() {
NettyTestUtils.sendServerResponses(testRelay, testClientAddr, streamResp, new DefaultHttpChunk(streamRes), 60000);
}
}, "send /stream resp");
streamRespThread.setDaemon(true);
streamRespThread.start();
log.debug("make sure the client disconnects and recovers from the /stream response");
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return null != relayConnInsp.getChannel() && !relayConnInsp.getChannel().isConnected();
}
}, "client disconnected", 30000, log);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return clientConn.getRelayPullThread().getLastOpenConnection() != relayConn;
}
}, "new netty connection", 30000, log);
//make sure the relay send thread is dead
streamRespThread.join(100);
Assert.assertTrue(!streamRespThread.isAlive());
log.debug("PHASE 2: make sure the client has fully recovered and able to connect to another relay");
final NettyHttpDatabusRelayConnection newRelayConn = (NettyHttpDatabusRelayConnection) clientConn.getRelayPullThread().getLastOpenConnection();
final NettyHttpDatabusRelayConnectionInspector newRelayConnInsp = new NettyHttpDatabusRelayConnectionInspector(newRelayConn);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
return null != newRelayConnInsp.getChannel() && newRelayConnInsp.getChannel().isConnected();
}
}, "client connected to new relay", 200, log);
//figure out the connection to the relay
clientChannel = newRelayConnInsp.getChannel();
relayAddr = (InetSocketAddress) clientChannel.getRemoteAddress();
clientAddr = clientChannel.getLocalAddress();
relayPort = relayAddr.getPort();
log.info("new relay selected: " + relayPort);
relay = null;
int relayIdx = 0;
for (; relayIdx < RELAY_PORT.length; ++relayIdx) {
if (relayPort == RELAY_PORT[relayIdx])
relay = _dummyServer[relayIdx];
}
assertTrue(null != relay);
serverChannel = relay.getChildChannel(clientAddr);
assertTrue(null != serverChannel);
serverPipeline = serverChannel.getPipeline();
objCapture = (SimpleObjectCaptureHandler) serverPipeline.get("3");
//process the /sources request
NettyTestUtils.waitForHttpRequest(objCapture, SOURCES_REQUEST_REGEX, 1000);
objCapture.clear();
//send back the /sources response
body = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer(("[{\"id\":1,\"name\":\"" + SOURCE1_NAME + "\"}]").getBytes(Charset.defaultCharset())));
NettyTestUtils.sendServerResponses(relay, clientAddr, sourcesResp, body);
//make sure the client processes the response correctly
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
String idListString = clientConn.getRelayPullThread()._currentState.getSourcesIdListString();
return "1".equals(idListString);
}
}, "client processes /sources response", 100, log);
//process the /register request
NettyTestUtils.waitForHttpRequest(objCapture, "/register.*", 1000);
objCapture.clear();
//send back the /register response
body = new DefaultHttpChunk(ChannelBuffers.wrappedBuffer(responseStr.getBytes(Charset.defaultCharset())));
NettyTestUtils.sendServerResponses(relay, clientAddr, sourcesResp, body);
//make sure the client processes the response correctly
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
DispatcherState dispState = clientConn.getRelayDispatcher().getDispatcherState();
return null != dispState.getSchemaMap() && 1 == dispState.getSchemaMap().size();
}
}, "client processes /register response", 100, log);
//process /stream call and return a partial window
Matcher streamMatcher = NettyTestUtils.waitForHttpRequest(objCapture, "/stream.*checkPoint=([^&]*)&.*", 1000);
String cpString = streamMatcher.group(1);
log.debug("/stream checkpoint: " + cpString);
objCapture.clear();
NettyTestUtils.sendServerResponses(relay, clientAddr, streamResp, new DefaultHttpChunk(streamResPrefix));
//make sure the client processes the response correctly
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
log.debug("lastWrittenScn=" + clientConn.getDataEventsBuffer().lastWrittenScn());
return clientConn.getDataEventsBuffer().lastWrittenScn() == 20;
}
}, "client receives /stream response", 1100, log);
TestUtil.assertWithBackoff(new ConditionCheck() {
@Override
public boolean check() {
log.debug("events num=" + consumer.getEventNum());
return stats.getTotalStats().getNumDataEvents() == consumer.getEventNum();
}
}, "client processes /stream response", 11000, log);
} finally {
client.shutdown();
}
}
use of org.jboss.netty.handler.codec.http.HttpResponse in project databus by linkedin.
the class MockServerChannelHandler method printMessage.
//auxiliary method to print messages
private void printMessage(String prefix, MessageEvent e) {
Object msgO = e.getMessage();
String resp;
if (msgO instanceof HttpRequest) {
HttpRequest msgReq = (HttpRequest) msgO;
//Matcher result = pattern.matcher(msgReq.getUri());
resp = msgReq.getUri();
} else if (msgO instanceof HttpResponse) {
HttpResponse msgReq = (HttpResponse) msgO;
resp = msgReq.toString();
} else if (msgO instanceof HttpChunk) {
HttpChunk msgReq = (HttpChunk) msgO;
resp = msgReq.toString();
} else {
ChannelBuffer msg = (ChannelBuffer) msgO;
byte[] bytes = new byte[msg.capacity()];
msg.readBytes(bytes);
msg.setIndex(0, bytes.length);
StringBuilder out = new StringBuilder("MSG: ").append(e.getChannel().getRemoteAddress());
out.append("\nMESSAGE length=").append(bytes.length).append("\n").append(new String(bytes));
resp = out.toString();
}
LOG.debug(prefix + resp);
}
Aggregations