@Override public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e) throws Exception { final MappingHttpRequest request = MappingHttpMessage.extractMessage(e); final BaseMessage msg = BaseMessage.extractMessage(e); if (msg != null) { try { final Class<? extends ComponentId> compClass = ComponentMessages.lookup(msg); ComponentId compId = ComponentIds.lookup(compClass); if (compId.isAlwaysLocal() || Topology.isEnabledLocally(compClass)) { ctx.sendUpstream(e); } else { Handlers.sendRedirect(ctx, e, compClass, request); } } catch (final NoSuchElementException ex) { LOG.warn( "Failed to find reverse component mapping for message type: " + msg.getClass()); ctx.sendUpstream(e); } catch (final Exception ex) { Logs.extreme().error(ex, ex); ctx.sendUpstream(e); } } else { ctx.sendUpstream(e); } }
@Override public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e) throws Exception { if (!Bootstrap.isFinished()) { // TODO:GRZE: do nothing for the moment, not envouh info here. // throw new ServiceNotReadyException( "System has not yet completed booting." ); ctx.sendUpstream(e); } else { ctx.sendUpstream(e); } }
@Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent ce) throws Exception { if (!(ce instanceof MessageEvent)) { ctx.sendUpstream(ce); return; } MessageEvent e = (MessageEvent) ce; RedisConnection conn = (RedisConnection) e.getChannel().getAttachment(); ChannelBuffer cb = (ChannelBuffer) e.getMessage(); conn.replyFromBackend(cb.copy()); ctx.sendUpstream(ce); }
private void cleanup(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { try { ChannelBuffer cumulation = this.cumulation; if (cumulation == null) { return; } else { this.cumulation = null; } if (cumulation.readable()) { // Make sure all frames are read before notifying a closed // channel. callDecode(ctx, ctx.getChannel(), cumulation, null); } // Call decodeLast() finally. Please note that decodeLast() is // called even if there's nothing more to read from the buffer to // notify a user that the connection was closed explicitly. Object partialFrame = decodeLast(ctx, ctx.getChannel(), cumulation); if (partialFrame != null) { Channels.fireMessageReceived(ctx, partialFrame, null); } } finally { ctx.sendUpstream(e); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object m = e.getMessage(); if (!(m instanceof ChannelBuffer)) { ctx.sendUpstream(e); return; } ChannelBuffer input = (ChannelBuffer) m; if (!input.readable()) { return; } ChannelBuffer cumulation = cumulation(ctx); if (cumulation.readable()) { cumulation.discardReadBytes(); cumulation.writeBytes(input); callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress()); } else { callDecode(ctx, e.getChannel(), input, e.getRemoteAddress()); if (input.readable()) { cumulation.writeBytes(input); } } }
/* (non-Javadoc) * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) */ @Override public void messageReceived(final ChannelHandlerContext context, final MessageEvent e) throws Exception { String decoded; synchronized (stringWriter) { // extract the buffer from the message event final Object message = e.getMessage(); if (!(message instanceof ChannelBuffer)) { context.sendUpstream(e); return; } final ChannelBuffer buffer = (ChannelBuffer) message; if (!buffer.readable()) { return; } // read all bytes from the buffer to the decoder stream final byte[] bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); writerOutputStream.write(bytes); writerOutputStream.flush(); decoded = stringWriter.toString(); stringWriter.getBuffer().setLength(0); } // push all successfully decoded characters upstream Channels.fireMessageReceived(context, decoded, e.getRemoteAddress()); }
@Override @SuppressWarnings("unchecked") public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { S serverChannel = (S) ctx.getAttachment(); T childChannel = createChildChannel(serverChannel, e.getChannel()); fireChannelOpen(childChannel); ChannelAddress localAddress = serverChannel.getLocalAddress(); childChannel.setLocalAddress(localAddress); childChannel.setBound(); fireChannelBound(childChannel, localAddress); ctx.setAttachment(childChannel); ctx.sendUpstream(e); // TODO: fire CONNECTED_BARRIER event to next pipeline // then fire CONNECTED event when future completes successfully ChannelAddress remoteAddress = localAddress.newEphemeralAddress(); childChannel.setRemoteAddress(remoteAddress); childChannel.setConnected(); fireChannelConnected(childChannel, remoteAddress); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception { if (event.getMessage() instanceof MappingHttpRequest) { MappingHttpRequest httpRequest = (MappingHttpRequest) event.getMessage(); if (httpRequest.getMessage() instanceof ObjectStorageDataRequestType) { if (httpRequest.isChunked()) { // Chunked request, and beginning, setup map etc. initializeNewPut(ctx, (ObjectStorageDataRequestType) httpRequest.getMessage()); } } } else if (event.getMessage() instanceof HttpChunk) { // Add the chunk to the current streams channel buffer. HttpChunk chunk = (HttpChunk) event.getMessage(); appendChunk(chunk.getContent(), ctx.getChannel()); if (chunk.isLast()) { // Remove from the map Logs.extreme() .debug( "Removing data map due to last chunk processed event for channel: " + ctx.getChannel().getId()); dataMap.remove(ctx.getChannel()); } } // Always pass it on ctx.sendUpstream(event); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Throwable cause = e.getCause(); if (cause instanceof IOException) { if (cause instanceof ClosedChannelException) { synchronized (ignoreClosedChannelExceptionLock) { if (ignoreClosedChannelException > 0) { ignoreClosedChannelException--; logger.debug("Swallowing an exception raised while " + "writing non-app data", cause); return; } } } else if (engine.isOutboundDone()) { String message = String.valueOf(cause.getMessage()).toLowerCase(); if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) { // It is safe to ignore the 'connection reset by peer' or // 'broken pipe' error after sending closure_notify. logger.debug( "Swallowing a 'connection reset by peer / " + "broken pipe' error occurred while writing " + "'closure_notify'", cause); // Close the connection explicitly just in case the transport // did not close the connection automatically. Channels.close(ctx, succeededFuture(e.getChannel())); return; } } } ctx.sendUpstream(e); }
private void handleIncomingConfirmableCoapResponse(ChannelHandlerContext ctx, MessageEvent me) { InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress(); CoapResponse coapResponse = (CoapResponse) me.getMessage(); writeEmptyAcknowledgement(remoteEndpoint, coapResponse.getMessageID()); ctx.sendUpstream(me); }
@Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // This method will be invoked only if this handler was added // before channelOpen event is fired. If a user adds this handler // after the channelOpen event, initialize() will be called by beforeAdd(). initialize(ctx); ctx.sendUpstream(e); }
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (hOut == null) { OutputStream out = OutputStreamEncoder.getOutputStream(ctx); hOut = new Hessian2Output(out); if (_serializerFactory != null) hOut.getSerializerFactory().addFactory(_serializerFactory); } else hOut.reset(); ctx.sendUpstream(e); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception { if (!(me.getMessage() instanceof HttpRequest)) { ctx.sendUpstream(me); return; } HttpRequest request = (HttpRequest) me.getMessage(); Object response; // Look up resource String path = request.getUri(); String host = request.getHeader("host"); log.debug("Received request for path:" + path); boolean showHtml = false; if (path.endsWith("?html")) { showHtml = true; path = path.replace("?html", ""); } for (String service : resources.keySet()) { log.debug("Available Service: " + service); } Model model = resources.get(path); if (model != null) { if (request.getMethod() == HttpMethod.GET) { if (showHtml) { String html = HtmlCreator.createModelPage(model, new URI(path), host); response = ChannelBuffers.wrappedBuffer(html.getBytes(Charset.forName("UTF-8"))); log.debug("Returned html page for resource: " + path); } else { response = new SelfDescription(model, new URI(request.getUri())); log.debug("Resource found: " + path); } } else { response = new DefaultHttpResponse( request.getProtocolVersion(), HttpResponseStatus.METHOD_NOT_ALLOWED); log.debug("Method not allowed: " + request.getMethod()); } } else { response = HttpResponseFactory.createHttpResponse( request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND); log.debug("Resource not found: " + path); } // Send response ChannelFuture future = Channels.write(ctx.getChannel(), response); future.addListener(ChannelFutureListener.CLOSE); }
/** * {@inheritDoc} * * @see * org.jboss.netty.channel.ChannelUpstreamHandler#handleUpstream(org.jboss.netty.channel.ChannelHandlerContext, * org.jboss.netty.channel.ChannelEvent) */ @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof MessageEvent) { MessageEvent me = (MessageEvent) e; if (me.getMessage() instanceof ChannelBuffer) { ChannelBuffer postDetectBuffer = protocolSwitch(ctx, e.getChannel(), (ChannelBuffer) me.getMessage(), e); if (postDetectBuffer != null) { ctx.getPipeline().remove(this); ctx.sendUpstream( new UpstreamMessageEvent( e.getChannel(), postDetectBuffer, ((MessageEvent) e).getRemoteAddress())); } } } else { ctx.sendUpstream(e); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (handshakeComplete) { super.messageReceived(ctx, e); } else { if (e.getMessage() instanceof ChannelBuffer) { ChannelBuffer newBuffer = (ChannelBuffer) e.getMessage(); buffered = ChannelBuffers.copiedBuffer(buffered, newBuffer); if (buffered.readableBytes() < 8) { return; } int payloadLength = buffered.getInt(0); int revision = buffered.getInt(4); boolean handshakeSuccessful = false; if (revision == 1 || revision == -1) { if (buffered.readableBytes() < payloadLength + 4) { return; } buffered.skipBytes(8); if (revision == 1) { handshakeSuccessful = handleRevision1Response(ctx, payloadLength); } else { handshakeSuccessful = handleGenericResponse(ctx, payloadLength); } } else { handshakeSuccessful = handleUnknownRevisionResponse(ctx); } if (!handshakeSuccessful) { ctx.getChannel().close(); } if (keepAliveInterval.millis() > 0) { ctx.getPipeline() .addBefore( ctx.getName(), "found-connection-keep-alive", new ConnectionKeepAliveHandler(scheduler, keepAliveInterval)); } handshakeComplete = true; ChannelBuffer remaining = buffered.slice(); if (remaining.readableBytes() > 0) { ctx.sendUpstream( new UpstreamMessageEvent( ctx.getChannel(), remaining, ctx.getChannel().getRemoteAddress())); } ctx.getPipeline().remove(this); } } }
@Override public synchronized void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { if (this.framingEnabled) { super.messageReceived(ctx, e); } else { ctx.sendUpstream(e); } }
@Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent channelEvent) throws Exception { if (channelEvent instanceof ExceptionEvent) { exceptionCaught(ctx, (ExceptionEvent) channelEvent); } else { ctx.sendUpstream(channelEvent); } }
/* (non-Javadoc) * @see org.jboss.netty.channel.ChannelFutureListener#operationComplete(org.jboss.netty.channel.ChannelFuture) */ @Override public void operationComplete(ChannelFuture future) throws Exception { if (upstreamContext != null && bgpEvent != null) { upstreamContext.sendUpstream( new UpstreamMessageEvent( upstreamContext.getChannel(), bgpEvent, upstreamContext.getChannel().getRemoteAddress())); } }
public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent exceptionEvent) throws Exception { Throwable t = exceptionEvent.getCause(); if (t != null && IOException.class.isAssignableFrom(t.getClass())) { LOG.debug(t, t); } else { LOG.debug(t, t); } ctx.sendUpstream(exceptionEvent); }
@Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { Channel channel = e.getChannel(); System.out.println(channel.getRemoteAddress().toString()); System.out.println("channelConnected..."); String msg = "welcome rookiefly..."; ChannelBuffer buffer = ChannelBuffers.buffer(1024); buffer.writeBytes(msg.getBytes()); channel.write(buffer); ctx.sendUpstream(e); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object message = e.getMessage(); if (message instanceof SubscribeChannelRequest) { String channelName = ((SubscribeChannelRequest) message).channelName(); this.channelSubscriptions.subscribe(e.getChannel(), channelName); } else { ctx.sendUpstream(e); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { Object m = e.getMessage(); if (!(m instanceof Value)) { ctx.sendUpstream(e); return; } Value msg = (Value) m; handler.handleMessage(adaptor, msg); }
@Override public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e) throws Exception { final MappingHttpMessage request = MappingHttpMessage.extractMessage(e); final BaseMessage msg = BaseMessage.extractMessage(e); if ((request != null) && (msg != null)) { final User user = Contexts.lookup(request.getCorrelationId()).getUser(); if (user.isSystemAdmin() || ServiceOperations.isUserOperation(msg)) { ctx.sendUpstream(e); } else { Contexts.clear(Contexts.lookup(msg.getCorrelationId())); ctx.getChannel() .write( new MappingHttpResponse( request.getProtocolVersion(), HttpResponseStatus.FORBIDDEN)); } } else { ctx.sendUpstream(e); } }
private void handleIncomingConfirmableCoapRequest(ChannelHandlerContext ctx, MessageEvent me) { InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress(); CoapMessage coapMessage = (CoapMessage) me.getMessage(); IncomingReliableMessageExchange newMessageExchange = new IncomingReliableMessageExchange(remoteEndpoint, coapMessage.getMessageID()); IncomingMessageExchange oldMessageExchange = ongoingMessageExchanges.get(remoteEndpoint, coapMessage.getMessageID()); // Check if there is an ongoing if (oldMessageExchange != null) { if (oldMessageExchange instanceof IncomingReliableMessageExchange) { // if the old message exchange is reliable and the empty ACK was already sent send another // empty ACK if (((IncomingReliableMessageExchange) oldMessageExchange).isAcknowledgementSent()) writeEmptyAcknowledgement(remoteEndpoint, coapMessage.getMessageID()); } // if the old message was unreliable and the duplicate message is confirmable send empty ACK else writeEmptyAcknowledgement(remoteEndpoint, coapMessage.getMessageID()); // As the message is already being processed there is nothing more to do return; } // try to add new reliable message exchange boolean added = false; synchronized (monitor) { Long time = System.currentTimeMillis() + MIN_EMPTY_ACK_DELAY_MILLIS; // Add message exchange to set of ongoing exchanges to detect duplicates if (!ongoingMessageExchanges.contains(remoteEndpoint, coapMessage.getMessageID())) { ongoingMessageExchanges.put(remoteEndpoint, coapMessage.getMessageID(), newMessageExchange); added = true; } // If the scheduling of the empty ACK does not work then it was already scheduled if (!emptyAcknowledgementSchedule.put(time, newMessageExchange)) { log.error("Could not schedule empty ACK for message: {}", coapMessage); ongoingMessageExchanges.remove(remoteEndpoint, coapMessage.getMessageID()); added = false; } } // everything is fine, so further process message if (added) ctx.sendUpstream(me); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { // have we sent our secret key ? if (_decodeCipher != null) { MessageEvent m = Util.code(_decodeCipher, e, true); ctx.sendUpstream(m); } else { ChannelBuffer b = (ChannelBuffer) e.getMessage(); // is this our first message ? if (_cryptedIvKeyMessage == null) { int size = b.readInt(); // consistency check, so we do not get an out of memory exception if (size > 1024) { ctx.getChannel().close(); return; } _cryptedIvKeyMessage = new byte[size]; } // readin the client's secret key and iv int available = b.readableBytes(); int toRead = Math.min(_cryptedIvKeyMessage.length - _bytesRead, available); b.readBytes(_cryptedIvKeyMessage, _bytesRead, toRead); _bytesRead += toRead; // we have completed receiption ? if (_bytesRead == _cryptedIvKeyMessage.length) { boolean ok = false; try { createCiphers(); ok = true; } catch (Exception ex) { ex.printStackTrace(); ctx.getChannel().close(); } // inform pipline that we are ready for encrypted communication if (ok) ctx.sendUpstream(_connectedEvent); } } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); if (request.getContent().readableBytes() == 0) { BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected."); return; } transportMetrics.messagesReceived.mark(); transportMetrics.messagesReceivedSize.update(request.getContent().readableBytes()); // logger.debug("Received {}", request.getContent().toString(CharsetUtil.UTF_8)); String contentTypeHeader = request.getHeader(CONTENT_TYPE); if (contentTypeHeader == null) { contentTypeHeader = BaseTransport.CONTENT_TYPE_PLAIN; } String decodedContent; if (BaseTransport.CONTENT_TYPE_FORM.equals(contentTypeHeader)) { QueryStringDecoder decoder = new QueryStringDecoder("?" + request.getContent().toString(CharsetUtil.UTF_8)); List<String> d = decoder.getParameters().get("d"); if (d == null) { BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected."); return; } decodedContent = d.get(0); } else { decodedContent = request.getContent().toString(CharsetUtil.UTF_8); } if (decodedContent.length() == 0) { BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected."); return; } String[] messages = MAPPER.readValue(decodedContent, String[].class); for (String message : messages) { SockJsMessage jsMessage = new SockJsMessage(message); ctx.sendUpstream(new UpstreamMessageEvent(e.getChannel(), jsMessage, e.getRemoteAddress())); } if (isJsonpEnabled) { BaseTransport.respond(e.getChannel(), OK, "ok"); } else { BaseTransport.respond(e.getChannel(), NO_CONTENT, ""); } }
@Override public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e) throws Exception { final MappingHttpRequest request = MappingHttpMessage.extractMessage(e); final BaseMessage msg = BaseMessage.extractMessage(e); if (msg != null) { try { if (msg instanceof ServiceTransitionType && !Hosts.isCoordinator()) { // TODO:GRZE: extra epoch check and redirect Topology.touch((ServiceTransitionType) msg); ctx.sendUpstream(e); } else if (Topology.check(msg)) { ctx.sendUpstream(e); } else { final Class<? extends ComponentId> compClass = ComponentMessages.lookup(msg); Handlers.sendRedirect(ctx, e, compClass, request); } } catch (final Exception ex) { Logs.extreme().error(ex, ex); ctx.sendUpstream(e); } } }
@Override public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e) throws Exception { Object o = null; if ((e instanceof MessageEvent) && this.first.compareAndSet(true, false) && ((o = ((MessageEvent) e).getMessage()) instanceof ChannelBuffer) && !maybeSsl((ChannelBuffer) o)) { ctx.getPipeline().removeFirst(); ctx.sendUpstream(e); } else { super.handleUpstream(ctx, e); } }
@Override public void handleUpstream( final ChannelHandlerContext channelHandlerContext, final ChannelEvent channelEvent) throws Exception { LOG.debug(this.getClass().getSimpleName() + "[incoming]: " + channelEvent); if (channelEvent instanceof MessageEvent) { final MessageEvent msgEvent = (MessageEvent) channelEvent; this.incomingMessage(channelHandlerContext, msgEvent); } else if (channelEvent instanceof ExceptionEvent) { this.exceptionCaught(channelHandlerContext, (ExceptionEvent) channelEvent); } if (!waitForNext) channelHandlerContext.sendUpstream(channelEvent); if (processedFirstChunk) waitForNext = false; }
/* (non-Javadoc) * @see org.rzo.netty.ahessian.auth.AuthToken#authenticate(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) */ public int authenticate(ChannelHandlerContext ctx, MessageEvent e) { ChannelBuffer b = (ChannelBuffer) e.getMessage(); int toCopy = Math.min(_receivedBytes.length - _receivedLength, b.readableBytes()); byte[] bytes = new byte[toCopy]; b.readBytes(bytes); System.arraycopy(bytes, 0, _receivedBytes, _receivedLength, bytes.length); _receivedLength += toCopy; if (_receivedLength == _password.length) { if (Arrays.equals(_receivedBytes, _password)) { logger.info("authenticated"); if (b.readableBytes() != 0) ctx.sendUpstream(e); return PASSED; } else return FAILED; } else return NOT_COMPLETE; }