/** * {@inheritDoc} * * @see * org.jboss.netty.channel.SimpleChannelUpstreamHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, * org.jboss.netty.channel.MessageEvent) */ public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { final SocketAddress remote = e.getRemoteAddress(); ChannelBuffer buff = (ChannelBuffer) e.getMessage(); if (buff.equals(BYE_BUFF)) { e.getChannel() .write(BYE_MSG, remote) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { future.getChannel().close(); } }); return; } e.getChannel() .write(e.getMessage(), remote) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.info(" S:OK"); } else { logger.info(" S:FAILED"); } } }); }
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof KafkaRequest) { ctx.setAttachment(((KafkaRequest) e.getMessage()).getResponseHandler()); } super.writeRequested(ctx, e); }
@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 messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { if (!chunked) { final HttpRequest request = (HttpRequest) e.getMessage(); final ChannelBuffer buffer = request.getContent(); receivedData.write(buffer.array()); // System.out.println("received "+buffer.array() ); // System.out.println(buffer.array().length); if (!request.isChunked()) { processRequest(e); } else { chunked = true; } // final boolean keepAlive = isKeepAlive(request); } else { final HttpChunk chunk = (HttpChunk) e.getMessage(); final ChannelBuffer buffer = chunk.getContent(); receivedData.write(buffer.array()); if (chunk.isLast()) { processRequest(e); } } }
@Override public void incomingMessage(ChannelHandlerContext ctx, MessageEvent event) throws Exception { if (event.getMessage() instanceof MappingHttpRequest) { MappingHttpRequest httpRequest = (MappingHttpRequest) event.getMessage(); if (httpRequest.getMessage() instanceof WalrusRequestType) { WalrusRequestType request = (WalrusRequestType) httpRequest.getMessage(); BucketLogData logData = request.getLogData(); if (logData != null) { long currentTime = System.currentTimeMillis(); logData.setTotalTime(currentTime); logData.setTurnAroundTime(currentTime); logData.setUri(httpRequest.getUri()); String referrer = httpRequest.getHeader(HttpHeaders.Names.REFERER); if (referrer != null) logData.setReferrer(referrer); String userAgent = httpRequest.getHeader(HttpHeaders.Names.USER_AGENT); if (userAgent != null) logData.setUserAgent(userAgent); logData.setTimestamp( String.format("[%1$td/%1$tb/%1$tY:%1$tH:%1$tM:%1$tS %1$tz]", Calendar.getInstance())); User user = Contexts.lookup(httpRequest.getCorrelationId()).getUser(); if (user != null) logData.setAccessorId(user.getUserId()); if (request.getBucket() != null) logData.setBucketName(request.getBucket()); if (request.getKey() != null) logData.setKey(request.getKey()); if (ctx.getChannel().getRemoteAddress() instanceof InetSocketAddress) { InetSocketAddress sockAddress = (InetSocketAddress) ctx.getChannel().getRemoteAddress(); logData.setSourceAddress(sockAddress.getAddress().getHostAddress()); } } } } }
/* (non-Javadoc) * @see org.jboss.netty.channel.SimpleChannelDownstreamHandler#writeRequested(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) */ public synchronized void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (msg instanceof FlushRequestMessage) { hOut.flush(e.getFuture()); e.getFuture().await(5000); return; } try { // if (e.getMessage() instanceof Integer) // { // hOut.flush(); // return; // } HessianRPCReplyMessage message = (HessianRPCReplyMessage) e.getMessage(); // Constants.ahessianLogger.warn("encode reply for // #"+message.getHeaders().get(Constants.CALL_ID_STRING)); hOut.resetReferences(); hOut.writeReply(message); // hOut.flush(); // e.getFuture().setSuccess(); } catch (Exception ex) { Constants.ahessianLogger.warn("", ex); e.getFuture().setFailure(ex); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Send back the received message to the remote peer. transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes()); e.getChannel().write(e.getMessage()); System.out.println("Server: " + e.getMessage()); }
@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); }
/** * If the message to be written is a {@link CoapResponse} this method decides whether the message * type is {@link MessageType.Name#ACK} (if there wasn't an empty acknowledgement sent yet) or * {@link MessageType.Name#CON} (if there was already an empty acknowledgement sent). In the * latter case it additionally cancels the sending of an empty acknowledgement (which was * scheduled by the <code>messageReceived</code> method when the request was received). * * @param ctx The {@link ChannelHandlerContext} connecting relating this class (which implements * the {@link ChannelUpstreamHandler} interface) to the datagramChannel that received the * message. * @param me the {@link MessageEvent} containing the actual message * @throws Exception if an error occurred */ @Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent me) throws Exception { if (isShutdown()) return; if (me.getMessage() instanceof CoapResponse) handleOutgoingCoapResponse(ctx, me); else if (me.getMessage() instanceof InternalApplicationShutdownMessage) handleApplicationShutdown(ctx, me); else ctx.sendDownstream(me); }
@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 void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object attachment = ctx.getAttachment(); if (e.getMessage() instanceof KafkaResponse && attachment instanceof ResponseHandler) { ((ResponseHandler) attachment).received((KafkaResponse) e.getMessage()); } else { super.messageReceived(ctx, e); } }
public void handleDownstream(final ChannelHandlerContext context, final ChannelEvent evt) throws Exception { if (evt instanceof ChannelStateEvent) { ChannelStateEvent e = (ChannelStateEvent) evt; switch (e.getState()) { case OPEN: case CONNECTED: case BOUND: if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) { closeOutboundAndChannel(context, e); return; } } } if (!(evt instanceof MessageEvent)) { context.sendDownstream(evt); return; } MessageEvent e = (MessageEvent) evt; if (!(e.getMessage() instanceof ChannelBuffer)) { context.sendDownstream(evt); return; } // Do not encrypt the first write request if this handler is // created with startTLS flag turned on. if (startTls && sentFirstMessage.compareAndSet(false, true)) { context.sendDownstream(evt); return; } // Otherwise, all messages are encrypted. ChannelBuffer msg = (ChannelBuffer) e.getMessage(); PendingWrite pendingWrite; if (msg.readable()) { pendingWrite = new PendingWrite( evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes())); } else { pendingWrite = new PendingWrite(evt.getFuture(), null); } synchronized (pendingUnencryptedWrites) { boolean offered = pendingUnencryptedWrites.offer(pendingWrite); assert offered; } wrap(context, evt.getChannel()); }
/** * Get the message from within a ChannelEvent. Returns null if no message found. * * @param <T> * @param e * @return message or null if no msg. */ public static <T extends MappingHttpMessage> T extractMessage(ChannelEvent e) { if (e instanceof MessageEvent) { final MessageEvent msge = (MessageEvent) e; if (msge.getMessage() instanceof MappingHttpRequest) { return (T) msge.getMessage(); } else if (msge.getMessage() instanceof MappingHttpResponse) { return (T) msge.getMessage(); } else { return null; } } else { return null; } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) { LOG.debug("Got Message: {}", event.getMessage().toString()); Object evm = event.getMessage(); if (evm instanceof ControlMessage) { LOG.debug("Got control message: {}", evm.toString()); return; } else if (evm instanceof HBMessage) { client.gotMessage((HBMessage) evm); } else { LOG.warn("Got unexpected message: {} from server.", evm); } }
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { logger.info("server writeRequested start."); if (e.getMessage() instanceof Message) { Message msg = (Message) e.getMessage(); ChannelBuffer totalBuffer = CodecUtil.encodeMessage(msg); Channels.write(ctx, e.getFuture(), totalBuffer); } else { logger.info("Channel message is not instance of Message"); } logger.info("server writeRequested end."); }
/** Invoked when a packet is received */ @Override public final void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { GameSession session = (GameSession) ctx.getAttachment(); if (e.getMessage() instanceof Message) { if (session != null) { synchronized (LogicService.getWorkerThread()) { Message packet = (Message) e.getMessage(); session.pushPacket(packet); } } } if (e.getMessage() instanceof ChannelBuffer) { ctx.getChannel().write(ctx); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof EslMessage) { EslMessage message = (EslMessage) e.getMessage(); String contentType = message.getContentType(); if (contentType.equals(Value.TEXT_EVENT_PLAIN) || contentType.equals(Value.TEXT_EVENT_XML)) { // transform into an event EslEvent eslEvent = new EslEvent(message); handleEslEvent(ctx, eslEvent); } else { handleEslMessage(ctx, (EslMessage) e.getMessage()); } } else { throw new IllegalStateException("Unexpected message type: " + e.getMessage().getClass()); } }
/** * 用户接受客户端发来的消息,在有客户端消息到达时触发 * * @author lihzh * @alia OneCoder */ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { System.out.println("messageReceived"); ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); System.out.println(buffer.toString(Charset.defaultCharset())); System.out.println( "MessageServerHandler::messageReceived buffer:: " + buffer.toString(Charset.defaultCharset())); ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally ClientInfoBean bean = null; try { bean = mapper.readValue(buffer.toString(Charset.defaultCharset()), ClientInfoBean.class); System.out.println(bean.getClientId()); } catch (JsonParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (JsonMappingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(buffer.toString(Charset.defaultCharset())); }
@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 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { receivedMessages.mark(); ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); byte[] readable = new byte[buffer.readableBytes()]; buffer.toByteBuffer().get(readable, buffer.readerIndex(), buffer.readableBytes()); GELFMessage msg = new GELFMessage(readable); switch (msg.getGELFType()) { case CHUNKED: dispatchedMessageChunk.mark(); server.getGELFChunkManager().insert(msg); break; case ZLIB: case GZIP: case UNCOMPRESSED: case UNSUPPORTED: dispatchedUnchunkedMessage.mark(); processor.messageReceived(msg); break; } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Cast to a String first. // We know it is a String because we put some codec in TelnetPipelineFactory. String request = (String) e.getMessage(); // Generate and write a response. String response; boolean close = false; if (request.length() == 0) { response = "Please type something.\r\n"; } else if (request.toLowerCase().equals("bye")) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = e.getChannel().write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
@Override public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception { if (e.getMessage() instanceof HttpRequest) { HttpRequest message = (HttpRequest) e.getMessage(); HttpResponse response; if (new QueryStringDecoder(message.getUri()).getPath().equals(START_TIME_PATH)) { response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader("Access-Control-Allow-Origin", "*"); response.setContent( ChannelBuffers.copiedBuffer(getApplicationStartTime(), CharsetUtil.US_ASCII)); } else { response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); } context.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Функция принимает уже готовые AbstractPacket'ы от игрока, поэтому их можно сразу посылать в // worker. За их формирование отвечает другой обработчик. // log.info("messageReceived"); if (e.getChannel().isOpen()) worker.acceptPacket((AbstractPacket) e.getMessage()); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String message = e.getMessage().toString(); for (String input : inputBuffer.processMessage(message)) { processMessage(input); } }
/** * If the incoming message is a confirmable {@link CoapRequest} it schedules the sending of an * empty acknowledgement to the sender if there wasn't a piggy-backed response within a period of * 2 seconds. * * <p>If the incoming message is a confirmable {@link CoapResponse} it immediately sends a proper * acknowledgement if there was an open request waiting for a seperate response or * update-notification. It immediately sends an RST if there was no such response expected. * * @param ctx The {@link ChannelHandlerContext} relating this handler (which implements the {@link * ChannelUpstreamHandler} interface) to the datagramChannel that received the message. * @param me the {@link MessageEvent} containing the actual message * @throws Exception if an error occured */ @Override public void messageReceived(final ChannelHandlerContext ctx, MessageEvent me) throws Exception { log.debug("Upstream from {}: {}.", me.getRemoteAddress(), me.getMessage()); if (isShutdown()) return; if (me.getMessage() instanceof CoapMessage) { CoapMessage coapMessage = (CoapMessage) me.getMessage(); if (coapMessage.getMessageTypeName() == MessageType.Name.CON) handleIncomingConfirmableCoapMessage(ctx, me); else if (coapMessage.getMessageTypeName() == MessageType.Name.NON) handleIncomingNonConfirmableMessage(ctx, me); else ctx.sendUpstream(me); } else ctx.sendUpstream(me); }
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 messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof Pressluft) { Pressluft prsslft = ((Pressluft) e.getMessage()); switch (prsslft.getType()) { case QUERY: handleQuery(Query.fromByteArray(prsslft.getPayload()), e.getChannel()); break; case RESULT: handleResult(Result.fromByteArray(prsslft.getPayload()), e.getRemoteAddress()); break; default: logger.error("can not handle pressluft : " + prsslft.getType()); break; } } }
/** * Get the message from within a ChannelEvent. Returns null if no message found. * * @param <T> * @param e * @return message or null if no msg. */ public static <T extends BaseMessage> T extractMessage(ChannelEvent e) { if (e instanceof MessageEvent) { final MessageEvent msge = (MessageEvent) e; MappingHttpMessage msgHttp = null; if (msge.getMessage() instanceof BaseMessage) { return (T) msge.getMessage(); } else if (msge.getMessage() instanceof MappingHttpMessage && (msgHttp = (MappingHttpMessage) msge.getMessage()).getMessage() instanceof BaseMessage) { return (T) msgHttp.getMessage(); } else { return null; } } else { return null; } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { ChannelBuffer buf = (ChannelBuffer) e.getMessage(); while (buf.readable()) { System.out.println((char) buf.readByte()); System.out.flush(); } }