use of org.eclipse.jetty.websocket.api.WriteCallback in project jetty.project by eclipse.
the class DeflateFrameExtensionTest method testCompressAndDecompressBigPayload.
@Test
public void testCompressAndDecompressBigPayload() throws Exception {
byte[] input = new byte[1024 * 1024];
// Make them not compressible.
new Random().nextBytes(input);
int maxMessageSize = (1024 * 1024) + 8192;
DeflateFrameExtension clientExtension = new DeflateFrameExtension();
clientExtension.setBufferPool(bufferPool);
clientExtension.setPolicy(WebSocketPolicy.newClientPolicy());
clientExtension.getPolicy().setMaxBinaryMessageSize(maxMessageSize);
clientExtension.getPolicy().setMaxBinaryMessageBufferSize(maxMessageSize);
clientExtension.setConfig(ExtensionConfig.parse("deflate-frame"));
final DeflateFrameExtension serverExtension = new DeflateFrameExtension();
serverExtension.setBufferPool(bufferPool);
serverExtension.setPolicy(WebSocketPolicy.newServerPolicy());
serverExtension.getPolicy().setMaxBinaryMessageSize(maxMessageSize);
serverExtension.getPolicy().setMaxBinaryMessageBufferSize(maxMessageSize);
serverExtension.setConfig(ExtensionConfig.parse("deflate-frame"));
// Chain the next element to decompress.
clientExtension.setNextOutgoingFrames(new OutgoingFrames() {
@Override
public void outgoingFrame(Frame frame, WriteCallback callback, BatchMode batchMode) {
LOG.debug("outgoingFrame({})", frame);
serverExtension.incomingFrame(frame);
callback.writeSuccess();
}
});
final ByteArrayOutputStream result = new ByteArrayOutputStream(input.length);
serverExtension.setNextIncomingFrames(new IncomingFrames() {
@Override
public void incomingFrame(Frame frame) {
LOG.debug("incomingFrame({})", frame);
try {
result.write(BufferUtil.toArray(frame.getPayload()));
} catch (IOException x) {
throw new RuntimeIOException(x);
}
}
@Override
public void incomingError(Throwable t) {
}
});
BinaryFrame frame = new BinaryFrame();
frame.setPayload(input);
frame.setFin(true);
clientExtension.outgoingFrame(frame, null, BatchMode.OFF);
Assert.assertArrayEquals(input, result.toByteArray());
}
use of org.eclipse.jetty.websocket.api.WriteCallback in project joynr by bmwcarit.
the class WebSocketJettyClient method writeBytes.
@Override
public synchronized void writeBytes(Address to, byte[] message, long timeout, TimeUnit unit, final SuccessAction successAction, final FailureAction failureAction) {
if (messageListener == null) {
throw new JoynrDelayMessageException(20, "WebSocket write failed: receiver has not been set yet");
}
if (sessionFuture == null) {
try {
reconnect();
} catch (Exception e) {
throw new JoynrDelayMessageException(10, "WebSocket reconnect failed. Will try later", e);
}
}
try {
Session session = sessionFuture.get(timeout, unit);
session.getRemote().sendBytes(ByteBuffer.wrap(message), new WriteCallback() {
@Override
public void writeSuccess() {
successAction.execute();
}
@Override
public void writeFailed(Throwable error) {
if (error instanceof WebSocketException) {
reconnect();
failureAction.execute(new JoynrDelayMessageException(reconnectDelay, error.getMessage()));
} else {
failureAction.execute(error);
}
}
});
} catch (WebSocketException | ExecutionException e) {
reconnect();
throw new JoynrDelayMessageException(10, "WebSocket write timed out", e);
} catch (TimeoutException e) {
throw new JoynrDelayMessageException("WebSocket write timed out", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
use of org.eclipse.jetty.websocket.api.WriteCallback in project incubator-pulsar by apache.
the class ConsumerHandler method receiveMessage.
private void receiveMessage() {
if (log.isDebugEnabled()) {
log.debug("[{}:{}] [{}] [{}] Receive next message", request.getRemoteAddr(), request.getRemotePort(), topic, subscription);
}
consumer.receiveAsync().thenAccept(msg -> {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] [{}] Got message {}", getSession().getRemoteAddress(), topic, subscription, msg.getMessageId());
}
ConsumerMessage dm = new ConsumerMessage();
dm.messageId = Base64.getEncoder().encodeToString(msg.getMessageId().toByteArray());
dm.payload = Base64.getEncoder().encodeToString(msg.getData());
dm.properties = msg.getProperties();
dm.publishTime = DateFormatter.format(msg.getPublishTime());
if (msg.getEventTime() != 0) {
dm.eventTime = DateFormatter.format(msg.getEventTime());
}
if (msg.hasKey()) {
dm.key = msg.getKey();
}
final long msgSize = msg.getData().length;
try {
getSession().getRemote().sendString(ObjectMapperFactory.getThreadLocal().writeValueAsString(dm), new WriteCallback() {
@Override
public void writeFailed(Throwable th) {
log.warn("[{}/{}] Failed to deliver msg to {} {}", consumer.getTopic(), subscription, getRemote().getInetSocketAddress().toString(), th.getMessage());
pendingMessages.decrementAndGet();
// schedule receive as one of the delivery failed
service.getExecutor().execute(() -> receiveMessage());
}
@Override
public void writeSuccess() {
if (log.isDebugEnabled()) {
log.debug("[{}/{}] message is delivered successfully to {} ", consumer.getTopic(), subscription, getRemote().getInetSocketAddress().toString());
}
updateDeliverMsgStat(msgSize);
}
});
} catch (JsonProcessingException e) {
close(WebSocketError.FailedToSerializeToJSON);
}
int pending = pendingMessages.incrementAndGet();
if (pending < maxPendingMessages) {
// Start next read in a separate thread to avoid recursion
service.getExecutor().execute(() -> receiveMessage());
}
}).exceptionally(exception -> {
return null;
});
}
use of org.eclipse.jetty.websocket.api.WriteCallback in project incubator-pulsar by apache.
the class ReaderHandler method receiveMessage.
private void receiveMessage() {
if (log.isDebugEnabled()) {
log.debug("[{}:{}] [{}] [{}] Receive next message", request.getRemoteAddr(), request.getRemotePort(), topic, subscription);
}
reader.readNextAsync().thenAccept(msg -> {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] [{}] Got message {}", getSession().getRemoteAddress(), topic, subscription, msg.getMessageId());
}
ConsumerMessage dm = new ConsumerMessage();
dm.messageId = Base64.getEncoder().encodeToString(msg.getMessageId().toByteArray());
dm.payload = Base64.getEncoder().encodeToString(msg.getData());
dm.properties = msg.getProperties();
dm.publishTime = DateFormatter.format(msg.getPublishTime());
if (msg.getEventTime() != 0) {
dm.eventTime = DateFormatter.format(msg.getEventTime());
}
if (msg.hasKey()) {
dm.key = msg.getKey();
}
final long msgSize = msg.getData().length;
try {
getSession().getRemote().sendString(ObjectMapperFactory.getThreadLocal().writeValueAsString(dm), new WriteCallback() {
@Override
public void writeFailed(Throwable th) {
log.warn("[{}/{}] Failed to deliver msg to {} {}", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString(), th.getMessage());
pendingMessages.decrementAndGet();
// schedule receive as one of the delivery failed
service.getExecutor().execute(() -> receiveMessage());
}
@Override
public void writeSuccess() {
if (log.isDebugEnabled()) {
log.debug("[{}/{}] message is delivered successfully to {} ", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString());
}
updateDeliverMsgStat(msgSize);
}
});
} catch (JsonProcessingException e) {
close(WebSocketError.FailedToSerializeToJSON);
}
int pending = pendingMessages.incrementAndGet();
if (pending < maxPendingMessages) {
// Start next read in a separate thread to avoid recursion
service.getExecutor().execute(() -> receiveMessage());
}
}).exceptionally(exception -> {
log.warn("[{}/{}] Failed to deliver msg to {} {}", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString(), exception);
return null;
});
}
use of org.eclipse.jetty.websocket.api.WriteCallback in project joynr by bmwcarit.
the class WebSocketJettyServer method writeBytes.
@Override
public synchronized void writeBytes(Address toAddress, byte[] message, long timeout, TimeUnit unit, final SuccessAction successAction, final FailureAction failureAction) {
if (!(toAddress instanceof WebSocketClientAddress)) {
throw new JoynrIllegalStateException("Web Socket Server can only send to WebSocketClientAddresses");
}
WebSocketClientAddress toClientAddress = (WebSocketClientAddress) toAddress;
Session session = sessionMap.get(toClientAddress.getId());
if (session == null) {
// TODO We need a delay with invalidation of the stub
throw new JoynrDelayMessageException("no active session for WebSocketClientAddress: " + toClientAddress.getId());
}
try {
session.getRemote().sendBytes(ByteBuffer.wrap(message), new WriteCallback() {
@Override
public void writeSuccess() {
successAction.execute();
}
@Override
public void writeFailed(Throwable error) {
if (shutdown) {
return;
}
failureAction.execute(error);
}
});
} catch (WebSocketException e) {
// Jetty throws WebSocketException when expecting [OPEN or CONNECTED] but found a different state
// The client must reconnect, but the message can be queued in the mean time.
sessionMap.remove(toClientAddress.getId());
// TODO We need a delay with invalidation of the stub
throw new JoynrDelayMessageException(e.getMessage(), e);
}
}
Aggregations