Example usage for org.springframework.web.socket WebSocketSession getRemoteAddress

List of usage examples for org.springframework.web.socket WebSocketSession getRemoteAddress

Introduction

In this page you can find the example usage for org.springframework.web.socket WebSocketSession getRemoteAddress.

Prototype

@Nullable
InetSocketAddress getRemoteAddress();

Source Link

Document

Return the address of the remote client.

Usage

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpClearWebSocketProcessor.java

private <AGBM extends AbstractGameBootMessage> boolean isDeleteRequest(WebSocketSession session, AGBM agbm) {
    OtpKeyRequest keyRequest = (OtpKeyRequest) agbm;

    boolean d = KeyFunction.DELETE == keyRequest.getKeyFunction();

    Long sysId = keyRequest.getOtpSystemId();
    SystemIdKey thisSysId = getSystemId(session);
    boolean ok = d && isEncrypting(session) && thisSysId.getValue().equals(sysId);

    if (!ok)// w  w w . j av a2 s .co m
        log.error("Delete key for {} received on {}, key {}", sysId, session.getRemoteAddress(), thisSysId);

    return ok;
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

/**
 * Process for binary./*ww w . j  a  va  2s  . co m*/
 *
 * @param session
 *          the session
 * @param msg
 *          the msg
 * @throws Exception
 *           the exception
 */
protected void processForBinary(WebSocketSession session, byte[] msg) throws Exception {
    OtpKeyRequest message = converter.fromJson(msg);

    if (!validateChannel(session, message))
        return;

    Response r = processor.process(message);

    if (r == null || !r.isSuccess()) {
        log.error("Unexpected response {}, disconnecting {}", r, session);
        session.close();
        return;
    }

    BinaryMessage bm = new BinaryMessage(converter.toJsonArray(r));
    session.sendMessage(bm);

    log.debug("Successful send of {} to {}", message.getType(), session.getRemoteAddress());

    Thread.sleep(50);
    session.close(CloseStatus.NORMAL);
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

/**
 * Validates that the clear channel exists. Override to provide additional
 * validation.//from ww  w . ja  v  a2s  .c  o  m
 *
 * @param session
 *          the session
 * @param message
 *          the message
 * @return true, if successful
 * @throws Exception
 *           the exception
 */
protected boolean validateChannel(WebSocketSession session, OtpKeyRequest message) throws Exception {
    if (message.getKeyFunction() == null) {
        log.error("No key function, closing channel");
        session.close();
        return false;
    }

    switch (message.getKeyFunction()) {
    case NEW:
        break;
    default:
        log.error("Cannot process {}, closing OTP New Key session {}", message, session);
        session.close();
        return false;
    }

    Long systemId = message.getOtpSystemId();
    if (systemId == null) {
        log.error("System id missing from {}, disconnecting {}", message, session);

        session.close();
        return false;
    }

    SystemIdKey sik = new SystemIdKey(systemId);

    WebSocketSession clearChannel = registry.get(sik);
    if (clearChannel == null || !clearChannel.isOpen()) {
        log.error("No clear channel for {}, from encrypted channel {}, disconnecting", systemId,
                session.getRemoteAddress());
        session.close();
        return false;
    }

    return true;
}

From source file:cn.com.inhand.devicenetworks.ap.websocket.WSDNAccessPoint.java

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    System.out/*  www  .j  av a  2s  .c  om*/
            .println("Debug in WSDNAccessPoint.java [Ln:81] : WebSocketSession session=" + session.toString());

    super.handleTextMessage(session, message);
    TextMessage returnMessage = new TextMessage(message.getPayload() + " received at server");
    //session.sendMessage(returnMessage);
    System.out.println("Debug in WSDNAccessPoint.java [Ln:57] : WebSocketSession recv:" + message.getPayload());

    try {
        String string = message.getPayload();
        if (string == null || string.trim().equals("") || string.equals("undefined")) {
            System.out.println("Debug in WSDNAccessPoint.java [Ln:64] : WebSocketSession recv:null msg");

            return;
        }
        DNMessage msg = parser.unwrap(message.getPayload().getBytes());

        WSDNSession wsdnsn = this.cinfo.getWsdnsn(session.toString());

        if (wsdnsn == null) {
            if (msg.getName().equals("login")) {
                try {
                    this.onLogin(msg, session, wsdnsn);
                } catch (PacketException pe) {
                    //
                    Logger.getLogger(WSDNAccessPoint.class.getName()).warning(
                            "Failed to Login from " + session.getRemoteAddress() + ":" + pe.toString());
                    this.close(session);
                }
            } else {
                //?login
                Logger.getLogger(WSDNAccessPoint.class.getName()).warning(
                        "Illegal connection from + " + session.getRemoteAddress() + ", the msg:" + string);
                this.close(session);
            }
        } else if (!wsdnsn.isIsLogin()) {
            wsdnsn.setSession(session);
            try {

                this.onLogin(msg, session, wsdnsn);
            } catch (PacketException pe) {
                //
                Logger.getLogger(WSDNAccessPoint.class.getName())
                        .warning("Failed to Login from " + session.getRemoteAddress() + ":" + pe.toString());
                this.close(session);
            }
        } else {
            //?

            if (msg.getName().equalsIgnoreCase("heartbeat") && msg.getType() == 0) {
                this.onHeartbeat(msg, session, wsdnsn);

                this.updateStatus(2, wsdnsn);
            } else if (msg.getName().equalsIgnoreCase("logout")) {//&& msg.getType() == 0) {
                this.onLogout(msg, session, wsdnsn);
                session.close();
            } else if (msg.getType() == 1) {
                this.onAck(msg, session, wsdnsn);
            } else {
                this.onUnkownMsg(msg, session, wsdnsn);
                Logger.getLogger(WSDNAccessPoint.class.getName())
                        .warning("Unsupported msg from " + session.getRemoteAddress() + ":" + msg.toString());
                //this.close(session);
            }

        }

    } catch (PacketException ex) {
        Logger.getLogger(WSv1Processor.class.getName()).log(Level.SEVERE, "while handling a text message", ex);
    }

}

From source file:org.metis.push.PusherBean.java

@Override
/**//from w w  w  .j a  v a  2s.  c  o  m
 * This method handles an incoming message from the web socket client. 
 */
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    if (session == null) {
        LOG.error(getBeanName() + ": null session");
        throw new Exception(getBeanName() + ":handleTextMessage, null session was received");
    }

    // the session should be in the registry
    WdsSocketSession wdsSession = getWdsSessions().get(session.getId());
    if (wdsSession == null) {
        LOG.error(getBeanName() + ":handleTextMessage, session with this id is not in registry: "
                + session.getId());
        session.close(new CloseStatus(SERVER_ERROR.getCode(),
                "ERROR, session with this id not in registry: " + session.getId()));
        return;
    }

    // some sort of message should have been received
    if (message == null) {
        LOG.error(getBeanName() + ":handleTextMessage, null message parameter");
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, session with this id gave a null message " + "parameter: " + session.getId()));
        return;
    }

    // we're supposed to receive a JSON object
    String jsonMsg = message.getPayload();

    if (jsonMsg == null) {
        LOG.error(getBeanName() + ":handleTextMessage, getPayload returns null or empty string");
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, session with this id did not return a payload: " + session.getId()));
        return;
    }

    if (jsonMsg.isEmpty()) {
        LOG.error(getBeanName() + ":handleTextMessage, getPayload returns zero-length string");
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, session with this id returns zero-length payload: " + session.getId()));
        return;
    }

    // dump the request if trace is on
    if (LOG.isTraceEnabled()) {
        LOG.trace(getBeanName() + ":***** processing new request *****");
        LOG.trace(getBeanName() + ":session id = " + session.getId());
        LOG.trace(getBeanName() + ":session remote address = " + session.getRemoteAddress().toString());
        LOG.trace(getBeanName() + ":session uri  = " + session.getUri().toString());
        LOG.trace(getBeanName() + ":session json object = " + jsonMsg);
    }

    // parse the json object
    List<Map<String, String>> jParams = null;
    try {
        jParams = Utils.parseJson(jsonMsg);
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":caught this " + "exception while parsing json object: " + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }

        session.close(new CloseStatus(SERVER_ERROR.getCode(),
                "ERROR, got this json parsing exception: " + exc.getMessage()));
        return;
    }

    if (jParams == null || jParams.isEmpty()) {
        LOG.error(getBeanName() + ":json parser returns null or " + "empty json array");
        session.close(
                new CloseStatus(SERVER_ERROR.getCode(), "ERROR, json parser returns null or empty json array"));
        return;
    }

    // if trace is on, dump the params (if any) to the log
    if (LOG.isDebugEnabled()) {
        LOG.debug(
                getBeanName() + ": handleRequestInternal, received these params: " + jParams.get(0).toString());
    }

    // get the command portion of the json message
    Map<String, String> map = jParams.get(0);
    String command = map.remove(WS_COMMAND);
    if (command == null) {
        LOG.error(getBeanName() + ":command field not present");
        session.close(POLICY_VIOLATION);
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, command string not present or improperly set: " + command));
        return;
    }

    if (!command.equals(WS_SUBSCRIBE) && !command.equals(WS_PING)) {
        LOG.error(getBeanName() + ":received this unknown command = " + command);
        session.close(POLICY_VIOLATION);
        session.close(new CloseStatus(POLICY_VIOLATION.getCode(),
                "ERROR, received this unknown command =  " + command));
        return;
    }

    // Get the SQL Job, if any, that this session is currently subscribed to
    SqlJob job = wdsSession.getMyJob();

    // if this is a ping command, return session's current subscription
    if (command.equals(WS_PING)) {
        LOG.debug(getBeanName() + ":received ping command");
        List<Map<String, Object>> response = new ArrayList<Map<String, Object>>();
        Map<String, Object> map0 = new HashMap<String, Object>();
        if (job != null) {
            LOG.debug(getBeanName() + ": client is subscribed");
            map0.put(WS_STATUS, WS_SUBSCRIBED);
            map = job.getParams();
            if (map != null && !map.isEmpty()) {
                for (String key : map.keySet()) {
                    map0.put(key, map.get(key));
                }
            }
        } else {
            LOG.debug(getBeanName() + ": client is not subscribed");
            map0.put(WS_STATUS, WS_OK);
        }
        response.add(map0);
        // send response back to client
        session.sendMessage(new TextMessage(Utils.generateJson(response)));
        return;
    }

    // find a sql statement that matches the incoming session request's
    // params
    SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null)
            : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet());

    // if getMatch could not find a match, then return error to client
    if (sqlStmnt == null) {
        LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this map: " + map.toString());
        List<Map<String, Object>> response = new ArrayList<Map<String, Object>>();
        Map<String, Object> map0 = new HashMap<String, Object>();
        if (map != null && !map.isEmpty()) {
            for (String key : map.keySet()) {
                map0.put(key, map.get(key));
            }
        }
        map0.put(WS_STATUS, WS_NOT_FOUND);
        // send response back to client
        session.sendMessage(new TextMessage(Utils.generateJson(response)));
        return;
    }

    // other than a ping, the only other command from the client is a
    // subscription command

    // Does this session already exist in one of the sql jobs? Note that the
    // client can switch subscriptions.
    if (job != null) {
        // the session pertains to a job, but does that job's map match
        // that of this session's subscription request
        if (job.isParamMatch(map)) {
            // if so, we're done
            return;
        } else {
            // else remove this session from that job - the client is
            // switching subscriptions
            job.removeSession(wdsSession.getId());
        }
    }

    mainLock.lock();
    try {
        // if we've gotten this far, the session does not pertain to a job
        // or it is a subscription change. so we now need to find an
        // existing job whose params match that of the incoming session. if
        // no job was found, then create and start one
        if (sqlStmnt.findSqlJob(map, wdsSession) == null) {
            sqlStmnt.createSqlJob(map, wdsSession);
        }
    } finally {
        mainLock.unlock();
    }
}