@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()); } } } } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e, XmlDocument d) { MessageEvent s = e; // Convert to a String first. XmlDocument doc = d; // new XmlDocument(); // doc.LoadXml((String)message); // String cAction = doc.DocumentElement.ChildNodes[0].Attributes["action"].Value; String cAction = doc.getDocumentElement().getChildren().get(0).getAttribute("action").getValue(); InetSocketAddress remoteAddress = (InetSocketAddress) s.getChannel().getRemoteAddress(); String strIpPort = remoteAddress.getAddress().getHostAddress() + ":" + String.valueOf(remoteAddress.getPort()); // // //create item SessionMessage item = new SessionMessage(e, doc, false, true); // // //save ChChessLPU.getInstance().getmsgList().Opp(QueueMethod.Add, item); // // // if (cAction.equals(ClientAction.heartBeat)) { // 不打印 } else { // log Log.WriteStrByRecv(cAction, strIpPort); } }
@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.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 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); }
/* (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()); }
/** * {@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 messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Функция принимает уже готовые AbstractPacket'ы от игрока, поэтому их можно сразу посылать в // worker. За их формирование отвечает другой обработчик. // log.info("messageReceived"); if (e.getChannel().isOpen()) worker.acceptPacket((AbstractPacket) e.getMessage()); }
@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 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 writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof KafkaRequest) { ctx.setAttachment(((KafkaRequest) e.getMessage()).getResponseHandler()); } super.writeRequested(ctx, 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 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); }
@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) { Channel ch = e.getChannel(); DefaultNetSocket sock = socketMap.get(ch); if (sock != null) { ChannelBuffer buff = (ChannelBuffer) e.getMessage(); sock.handleDataReceived(new Buffer(buff.slice())); } }
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { UnixTime time = (UnixTime) e.getMessage(); ChannelBuffer buf = buffer(4); buf.writeInt(time.getValue()); Channels.write(ctx, e.getFuture(), buf); }
/** * 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 { Object attachment = ctx.getAttachment(); if (e.getMessage() instanceof KafkaResponse && attachment instanceof ResponseHandler) { ((ResponseHandler) attachment).received((KafkaResponse) e.getMessage()); } else { super.messageReceived(ctx, e); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object message = e.getMessage(); if (message instanceof HttpRequest) { eventBus.post(message); httpRequestReceived((HttpRequest) message, e.getChannel()); } }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object message = e.getMessage(); if (message instanceof OperatorMessage) { System.out.println("Server --------------Message is: " + message.toString()); OperatorMessage om = (OperatorMessage) message; // e.getChannel().write(excMethod(om));//执行用户方法 e.getChannel().write("TEST is over!"); } }
@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 writeRequested(ChannelHandlerContext ctx, MessageEvent e) { // logger.info("Mongo message encoding..."); Message message = (Message) e.getMessage(); ChannelBuffer buf = message.encode(null); Channels.write(ctx, e.getFuture(), buf); }
@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 requestJson = (String) e.getMessage(); System.out.println("received Message:\n " + requestJson); if (this.jsonStrings != null) { this.jsonStrings.offer(requestJson); } Message info = null; try { info = new Message(requestJson); } catch (JSONException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } int resFlag = 0; long receiveTime = new Date().getTime(); try { List<TableMap> maps = this.tableMaps.getTableMapsBySourceInfo(info.getSourceInfo()); if (maps == null || maps.size() == 0) System.out.println("maps is null"); System.out.println(info.getSourceInfo()); for (TableMap tableMap : maps) { Message msg = DataTranslator.transData(info, tableMap); SourceInfo sourceInfo = tableMap.getToTable().getSourceInfo(); Tenant tanent = this.tanentPool.getTanentByOthers( sourceInfo.getIp(), sourceInfo.getPort(), sourceInfo.getDBName(), sourceInfo.getUserName()); resFlag = new OperateDB( msg, tableMap, this.conPool.getCon( tanent.getUrl(), tanent.getUserName(), tanent.getPassword())) .synData(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Generate and write a response. String response = ""; ReturnMsg returnMsg = new ReturnMsg(); returnMsg.setStatus(resFlag); returnMsg.setRecordId(info.getRecordId()); returnMsg.setReceiveTime(receiveTime); response = returnMsg.toString(); e.getChannel().write(response + "\r\n"); System.out.println("sendReturnMsg:" + response); }
@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); }
@Override public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception { ChannelBuffer msg = (ChannelBuffer) e.getMessage(); // System.out.println(">>> " + ChannelBuffers.hexDump(msg)); synchronized (trafficLock) { outboundChannel.write(msg); // If outboundChannel is saturated, do not read until notified in // OutboundHandler.channelInterestChanged(). if (!outboundChannel.isWritable()) { e.getChannel().setReadable(false); } } }
public static void send(MessageEvent event, Integer transactionId, Long connectionId) throws Exception { logger.debug("ConnectionResponse::send to " + event.getRemoteAddress()); ChannelBuffer responseBuffer = ChannelBuffers.buffer(4 + 4 + 8); responseBuffer.writeInt(Action.CONNECT.getId()); responseBuffer.writeInt(transactionId); responseBuffer.writeLong(connectionId); logger.debug("ConnectionResponse DUMP: " + Utils.getHexString(responseBuffer.array())); event.getChannel().write(responseBuffer, event.getRemoteAddress()); }
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); }
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()); }
@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); } }