websocket 消息 处理
@param webSocketSession
@param webSocketMessage
@throws Exception
775142
@Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        try {
            JSONObject json = new JSONObject(((TextMessage) webSocketMessage).getPayload());
            ValidMessage rm = (ValidMessage) tgtools.util.JsonParseHelper.parseToObject(json, ValidMessage.class);
            validLogin(webSocketSession, rm);
            mWebsocketCommand.process(rm.getOperation(), rm.getData());
        } catch (Exception e) {
            try {
                ResponseMessage data = new ResponseMessage();
                data.setStatus(false);
                data.setData(e.getMessage());
                webSocketSession.sendMessage(new TextMessage(tgtools.util.JsonParseHelper.parseToJsonObject(data).toString()));
            } catch (Exception ex) {
                LogHelper.error("","AbstractSingleWebSocketHandler 初始化失败；原因："+e.toString(),"AbstractSingleWebSocketHandler.handleMessage",e);

            }
        }

    }
257811
@Override
    public void processConnect(WebSocketChannel channel, WSURI uri, String[] protocols) {
        LOG.entering(CLASS_NAME, "connect", channel);
        
        if (((WebSocketSelectedChannel)channel).readyState == ReadyState.CLOSED) {
            throw new IllegalStateException("WebSocket is already closed");
        }
        
        nextHandler.processConnect(channel, uri, protocols);
    }
817855
public void onMessage(final byte[] message, final Session session) {
        final SynchronizeFXWebsocketChannel channel = getChannelOrFail(session);

        channel.newMessage(message, session);
    }
440014
@Override
    public synchronized void processConnect(WebSocketChannel channel, WSURI uri, String[] protocols) {
        LOG.entering(CLASS_NAME, "processConnect", new Object[] { uri, protocols });

        try {
            WebSocketNativeChannel nativeChannel = (WebSocketNativeChannel)channel;
            if (nativeChannel.getProxy() != null) {
                throw new IllegalStateException("Bridge proxy previously set");
            }
            
            Proxy proxy = BridgeUtil.createProxy(uri.getURI(), this);
            proxy.setPeer(channel);
            nativeChannel.setProxy(proxy);
            
            String[] params;
            if (protocols != null) {
                String s = "";
                for (int i=0; i<protocols.length; i++) {
                    if (i>0) {
                        s += ",";
                    }
                    s += protocols[i];
                }
                params = new String[] { "WEBSOCKET", uri.toString(), s, ""};
            } else {
                params = new String[] { "WEBSOCKET", uri.toString() };
            }
            proxy.processEvent(XoaEventKind.CREATE, params);
        }
        catch (Exception e) {
            LOG.log(Level.FINE, "While initializing WebSocket proxy: "+e.getMessage(), e);
            listener.connectionFailed(channel, e);
        }
    }
562461
public void sendSync(BasicMessageWithExtraData<? extends BasicMessage> messageWithData) throws Exception {
        if (!isConnected()) {
            throw new IllegalStateException("WebSocket connection was closed. Cannot send any messages");
        }

        BasicMessage message = messageWithData.getBasicMessage();
        configurationAuthentication(message);

        if (messageWithData.getBinaryData() == null) {
            String messageString = ApiDeserializer.toHawkularFormat(message);
            @SuppressWarnings("resource")
            Buffer buffer = new Buffer().writeUtf8(messageString);
            RequestBody requestBody = RequestBody.create(WebSocket.TEXT, buffer.readByteArray());
            FeedCommProcessor.this.webSocket.sendMessage(requestBody);
        } else {
            BinaryData messageData = ApiDeserializer.toHawkularFormat(message, messageWithData.getBinaryData());

            RequestBody requestBody = new RequestBody() {
                @Override
                public MediaType contentType() {
                    return WebSocket.BINARY;
                }

                @Override
                public void writeTo(BufferedSink bufferedSink) throws IOException {
                    emitToSink(messageData, bufferedSink);
                }
            };

            FeedCommProcessor.this.webSocket.sendMessage(requestBody);

        }
    }
1111682
@Override
	public void sessionOpened(IoSession session) throws Exception {
		log.debug("Session opened for sensor {}.", session);
		if (this.sensorIoAdapter != null) {
			this.sensorIoAdapter.sensorConnected(session);
		}
	}
1044222
public void connect() throws Exception {
        logger.debug("[connect] initializing new connection");

        if (timer != null) {
            timer.cancel();
        }

        if (isConnected()) {
            return;
        }

        synchronized (webSocketHandler.getNotifyConnectionObject()) {
            webSocketConnectionManager.start();

            try {
                webSocketHandler.getNotifyConnectionObject().wait(TimeUnit.SECONDS.toMillis(WEBSOCKET_TIMEOUT));
            }
            catch (InterruptedException e) {
                onConnectionClosed();
                logger.debug("[connect] not open");
                throw new Exception("websocket connection not open");
            }

            if (!isConnected()) {
                onConnectionClosed();
                logger.debug("[connect] timeout");
                throw new Exception("websocket connection timeout");
            }
        }
    }
1272783
@Override
	public void processMessage(final WebSocketMessage webSocketData) {

		setDoTransactionNotifications(true);

		final SecurityContext securityContext = getWebSocket().getSecurityContext();

		try {

			final String uuid  = webSocketData.getId();
			int sequenceNumber = webSocketData.getNodeDataIntegerValue("chunkId");
			int chunkSize      = webSocketData.getNodeDataIntegerValue("chunkSize");
			int chunks         = webSocketData.getNodeDataIntegerValue("chunks");
			Object rawData     = webSocketData.getNodeData().get("chunk");

			byte[] data        = new byte[0];

			if (rawData != null) {

				if (rawData instanceof String) {

					logger.debug("Raw data: {}", rawData);

//                                        data = Base64.decodeBase64(((String)rawData).getBytes("UTF-8"));
					data = Base64.decode(((String) rawData));

					logger.debug("Decoded data: {}", data);

				}

			}

			final File file = (File) getNode(uuid);
			if (file.isTemplate()) {

				logger.warn("No write permission, file is in template mode: {}", new Object[] {file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission, file is in template mode").code(400).build(), true);
				return;

			}

			if (!file.isGranted(Permission.write, securityContext)) {

				logger.warn("No write permission for {} on {}", new Object[] {getWebSocket().getCurrentUser().toString(), file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission").code(400).build(), true);
				return;

			}

			getWebSocket().handleFileChunk(uuid, sequenceNumber, chunkSize, data, chunks);

			if (sequenceNumber+1 == chunks) {

				FileHelper.updateMetadata(file);

				file.increaseVersion();

				getWebSocket().removeFileUploadHandler(uuid);

				logger.debug("File upload finished. Checksum: {}, size: {}", new Object[]{ file.getChecksum(), file.getSize() });

			}

			final long currentSize = (long)(sequenceNumber * chunkSize) + data.length;

			// This should trigger setting of lastModifiedDate in any case
			getWebSocket().send(MessageBuilder.status().code(200).message("{\"id\":\"" + file.getUuid() + "\", \"name\":\"" + file.getName() + "\",\"size\":" + currentSize + "}").build(), true);

		} catch (IOException | FrameworkException ex) {

			String msg = ex.toString();

			// return error message
			getWebSocket().send(MessageBuilder.status().code(400).message("Could not process chunk data: ".concat((msg != null)
				? msg
				: "")).build(), true);
		}
	}
686343
@Override
    public void messageSent(IoSession session, Object message) throws Exception {
        MessageHandler<Object> handler = findSentMessageHandler(message.getClass());
        if (handler != null) {
            handler.handleMessage(session, message);
        } else {
            throw new UnknownMessageTypeException(
                    "No handler found for message type: " +
                    message.getClass().getSimpleName());
        }
    }
478385
public void onOpen(WebSocketSession session) {
        WsonrpcRemotes.addRemote(session, wsonrpcControl.getConfig());
        fireOpen(session);
    }
634028
private void callOnMessageError(WebSocketException cause, List<WebSocketFrame> frames)
    {
        mWebSocket.getListenerManager().callOnMessageError(cause, frames);
    }
273676
@Override
	public final void onMessageSent(Session session, Object msg) {
		Command command = (Command) msg;
		((HandlerSocketSession) session).addCommand(command);

	}
339222
public void consumeMessages(LockedMessageEnumeration messages) throws Exception
  {
    if (tc.isEntryEnabled())
      SibTr.entry(tc, "consumeMessages", new Object[] { messages });

    SIBusMessage jsMessage = null;
    
    while (messages.hasNext())
    {    
      try
      {
        jsMessage = messages.nextLocked();
      }
      catch (SIException e)
      {
        FFDCFilter.processException(
          e,
          "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
          "1:157:1.73",
          this);
          
        SibTr.exception(tc, e);
      }
  
      if (jsMessage!=null && 
          ((JsMessage) jsMessage).getJsMessageType() != MessageType.SUBSCRIPTION)
      {
        if (tc.isDebugEnabled())
          SibTr.debug(
            tc,
            "Message On incorrect Destination, expecting message "
              + "of Type "
              + MessageType.SUBSCRIPTION
              + " received "
              + ((JsMessage) jsMessage).getJsMessageType());
              
        if (tc.isEntryEnabled()) SibTr.exit(tc, "consumeMessages");
        return;
      }
  
      // Only continue if the message returned is not null
      if (jsMessage!=null)
      {    
        SubscriptionMessage subMessage = null;     
        
        try
        {
          subMessage = ((JsMessage) jsMessage).makeInboundSubscriptionMessage();
        }
        catch (IncorrectMessageTypeException e)
        {
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
            "1:193:1.73",
            this);
            
          SibTr.exception(tc, e);
        }
        
        // Invoke the limited ME comms trace again now that we have fluffed up the message
        if (TraceComponent.isAnyTracingEnabled()) {
          MECommsTrc.traceMessage(tc, 
              iProxyHandler.getMessageProcessor(), 
              subMessage.getGuaranteedSourceMessagingEngineUUID(),
              MECommsTrc.OP_SUBMSG_CONSUME, 
              null, 
              subMessage);
        }
        
        LocalTransaction transaction = null;
        
        // Switch on the Type of the Message to understand what we need to 
        // process
        try
        {
          
          // Get a transaction to operate under
          transaction = iProxyHandler.getTransactionManager().createLocalTransaction(true);
    
          switch (subMessage.getSubscriptionMessageType().toInt())
          {
            case SubscriptionMessageType.CREATE_INT :
    
              // Create a new Proxy subscription
              handleCreateProxySubscription(subMessage, (Transaction) transaction);
    
              break;
    
            case SubscriptionMessageType.DELETE_INT :
    
              // Delete a proxy subscription
              handleDeleteProxySubscription(subMessage, (Transaction) transaction);
    
              break;
    
            case SubscriptionMessageType.RESET_INT :
    
              // Reset the subscription state.
              handleResetState(subMessage, (Transaction) transaction, false);
    
              break;
    
            case SubscriptionMessageType.REQUEST_INT :
    
              // Reset the subscription state.
              handleResetState(subMessage, (Transaction) transaction, true);
    
              break;
  
            case SubscriptionMessageType.REPLY_INT :
    
              // Reset the subscription state.
              handleResetState(subMessage, (Transaction) transaction, false);
    
              break;
            default :
              // Log Message
              break;
          }
    
          // Delete the current message from the destination as we 
          // have now read it.
          messages.deleteCurrent(transaction);
        
          // Commit the transaction.
          transaction.commit();
        }      
        catch (SIException e)
        {        
          // If there are any exceptions, then this is bad, log a FFDC
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
            "1:273:1.73",
            this);
            
          SibTr.exception(tc, e);
          
          handleRollback(subMessage, transaction);                
        }
        catch (RuntimeException e)
        {        
          // If there are any exceptions, then this is bad, log a FFDC
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
            "1:286:1.73",
            this);
            
          SibTr.exception(tc, e);
          
          handleRollback(subMessage, transaction);        
          
          if (tc.isEntryEnabled()) SibTr.exit(tc, "consumeMessages", e);
          
          throw e;
        }
  
      }
    }

    if (tc.isEntryEnabled())
      SibTr.exit(tc, "consumeMessages");
  }
347411
@Override
    public void messageSent(final NextFilter nextFilter,
            final IoSession session, final WriteRequest writeRequest)
            throws Exception {
        if (writeRequest.getMessage() != null
                && writeRequest.getMessage() instanceof ProxyHandshakeIoBuffer) {
            // Ignore buffers used in handshaking
            return;
        }

        nextFilter.messageSent(session, writeRequest);
    }
997470
@Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        log.debug("onBytes");
        TioWebsocketMethodMapper onBytes = methods.getOnBytes();
        if (onBytes != null) {
            onBytes.getMethod().invoke(onBytes.getInstance(), channelContext, bytes);
        } else {
            TioWebsocketMethodMapper onBeforeBytes = methods.getOnBeforeBytes();
            if (onBeforeBytes != null) {
                TioWebsocketRequest invoke = (TioWebsocketRequest) onBeforeBytes.getMethod().invoke(onBeforeBytes.getInstance(), channelContext, bytes);
                onMapEvent(invoke, channelContext);
            }
        }
        return null;
    }
837261
public final void mWS() throws RecognitionException {
		try {
			int _type = WS;
			int _channel = DEFAULT_TOKEN_CHANNEL;
			// druidG.g:669:2: ( ( ' ' | '\\t' | NEWLINE )+ )
			// druidG.g:669:4: ( ' ' | '\\t' | NEWLINE )+
			{
			// druidG.g:669:4: ( ' ' | '\\t' | NEWLINE )+
			int cnt37=0;
			loop37:
			while (true) {
				int alt37=4;
				switch ( input.LA(1) ) {
				case ' ':
					{
					alt37=1;
					}
					break;
				case '\t':
					{
					alt37=2;
					}
					break;
				case '\n':
				case '\r':
					{
					alt37=3;
					}
					break;
				}
				switch (alt37) {
				case 1 :
					// druidG.g:669:5: ' '
					{
					match(' '); 
					}
					break;
				case 2 :
					// druidG.g:669:11: '\\t'
					{
					match('\t'); 
					}
					break;
				case 3 :
					// druidG.g:669:18: NEWLINE
					{
					mNEWLINE(); 

					}
					break;

				default :
					if ( cnt37 >= 1 ) break loop37;
					EarlyExitException eee = new EarlyExitException(37, input);
					throw eee;
				}
				cnt37++;
			}

			}

			state.type = _type;
			state.channel = _channel;
		}
		finally {
			// do for sure before leaving
		}
	}
1168510
@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

		if (cause instanceof TransportException) {
			notifyAllChannelsOfErrorAndClose(cause);
		}
		else {
			final SocketAddress remoteAddr = ctx.channel().remoteAddress();

			final TransportException tex;

			// Improve on the connection reset by peer error message
			if (cause instanceof IOException
					&& cause.getMessage().equals("Connection reset by peer")) {

				tex = new RemoteTransportException(
						"Lost connection to task manager '" + remoteAddr + "'. This indicates "
								+ "that the remote task manager was lost.", remoteAddr, cause);
			}
			else {
				SocketAddress localAddr = ctx.channel().localAddress();
				tex = new LocalTransportException(
					String.format("%s (connection to '%s')", cause.getMessage(), remoteAddr),
					localAddr,
					cause);
			}

			notifyAllChannelsOfErrorAndClose(tex);
		}
	}