Example usage for javax.websocket Session getId

List of usage examples for javax.websocket Session getId

Introduction

In this page you can find the example usage for javax.websocket Session getId.

Prototype

String getId();

Source Link

Document

Provides a unique identifier for the session.

Usage

From source file:org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint.SuperTenantSubscriptionEndpoint.java

/**
 * Web socket onMessage - When client sens a message
 *
 * @param session    - Users registered session.
 * @param message    - Status code for web-socket close.
 * @param streamName - StreamName extracted from the ws url.
 *///from  w w  w  . j  a va2 s  .c o m
@OnMessage
public void onMessage(Session session, String message, @PathParam("streamname") String streamName) {
    if (log.isDebugEnabled()) {
        log.debug("Received and dropped message from client. Message: " + message + ", " + "for Session id: "
                + session.getId() + ", for the Stream:" + streamName);
    }
}

From source file:org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint.TenantSubscriptionEndpoint.java

/**
 * Web socket onOpen - When client sends a message
 *
 * @param session - Users registered session.
 * @param streamName - StreamName extracted from the ws url.
 * @param version -  Version extracted from the ws url.
 * @param tdomain - Tenant domain extracted from ws url.
 *///w ww  .ja va2 s .  com
@OnOpen
public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName,
        @PathParam("version") String version, @PathParam("tdomain") String tdomain) {
    if (log.isDebugEnabled()) {
        log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName);
    }
    Map<String, List<String>> sessionQueryParam = new HashedMap();
    List<String> sessionQueryParamList = new LinkedList<>();
    sessionQueryParamList.add(session.getQueryString());
    sessionQueryParam.put(Constants.QUERY_STRING, sessionQueryParamList);
    Authenticator authenticator = ServiceHolder.getWebsocketValidationService().getAuthenticator();
    AuthenticationInfo authenticationInfo = authenticator.isAuthenticated(sessionQueryParam);
    if (authenticationInfo != null && authenticationInfo.isAuthenticated()) {
        Authorizer authorizer = ServiceHolder.getWebsocketValidationService().getAuthorizer();
        boolean isAuthorized = authorizer.isAuthorized(authenticationInfo, session, streamName);
        if (isAuthorized) {
            try {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext()
                        .setTenantDomain(authenticationInfo.getTenantDomain(), true);
                ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService()
                        .subscribeWebsocket(streamName, version, session);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
        } else {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access"));
            } catch (IOException e) {
                log.error("Failed to disconnect the unauthorized client.", e);
            }
        }
    } else {
        try {
            session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access"));
        } catch (IOException e) {
            log.error("Failed to disconnect the unauthorized client.", e);
        }
    }
}

From source file:org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint.TenantSubscriptionEndpoint.java

/**
 * Web socket onMessage - When client sens a message
 *
 * @param session - Users registered session.
 * @param message  - Status code for web-socket close.
 * @param streamName - StreamName extracted from the ws url.
 *//*from  w ww.j  a v a2 s  . co m*/
@OnMessage
public void onMessage(Session session, String message, @PathParam("streamname") String streamName,
        @PathParam("tdomain") String tdomain) {
    if (log.isDebugEnabled()) {
        log.debug("Received and dropped message from client. Message: " + message + ", for Session id: "
                + session.getId() + ", for tenant domain" + tdomain + ", for the Adaptor:" + streamName);
    }
}

From source file:org.wso2.carbon.event.input.adapter.websocket.internal.WebsocketClient.java

@Override
public void onClose(Session session, javax.websocket.CloseReason closeReason) {
    if (log.isDebugEnabled()) {
        log.debug("Input ws-adaptor: WebsocketClient Endpoint closed: " + closeReason.toString()
                + "for request URI - " + session.getRequestURI());
    }/* ww  w. ja v a 2s.  c  om*/
    try {
        session.close();
    } catch (IOException e) {
        log.error("Error occurred during closing session. Session ID:" + session.getId()
                + ", for request URI - " + session.getRequestURI() + ", Reason: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.event.input.adapter.websocket.internal.WebsocketClient.java

@Override
public void onError(Session session, Throwable thr) {
    log.error("Error occurred during session ID:" + session.getId() + ", for request URI - "
            + session.getRequestURI() + ", Reason: " + thr, thr);
    try {// w w  w .  j a  v  a2  s  . c om
        session.close();
    } catch (IOException e) {
        log.error("Error occurred during closing session. Session ID:" + session.getId()
                + ", for request URI - " + session.getRequestURI() + ", Reason: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.event.input.adaptor.websocket.internal.WebsocketClient.java

@Override
public void onError(javax.websocket.Session session, java.lang.Throwable thr) {
    log.error("Error occured during session ID:" + session.getId() + ", for request URI - "
            + session.getRequestURI() + ", Reason: " + thr);
}

From source file:org.wso2.carbon.event.output.adapter.websocket.internal.WebsocketClient.java

@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
    if (log.isDebugEnabled()) {
        log.debug("Websocket Output Adaptor: WebsocketClient connected, with session ID: " + session.getId()
                + ", to the remote end point URI - " + session.getRequestURI());
    }//from w  w  w.j  a va 2  s  . c  o m
}

From source file:org.wso2.carbon.identity.agent.outbound.server.SessionHandler.java

/**
 * Remove session from cache./*  ww w .jav  a  2s .co m*/
 * @param tenantDomain Tenant domain
 * @param userstoreDomain User store domain
 * @param session websocket session
 */
public void removeSession(String tenantDomain, String userstoreDomain, Session session) {

    if (sessions.get(getKey(tenantDomain, userstoreDomain)) != null) {
        Iterator<Session> iterator = sessions.get(getKey(tenantDomain, userstoreDomain)).iterator();
        while (iterator.hasNext()) {
            Session tmpSession = iterator.next();
            if (tmpSession.getId().equals(session.getId())) {
                iterator.remove();
                break;
            }
        }
    }
}

From source file:org.wso2.carbon.identity.agent.outbound.server.UserStoreServerEndpoint.java

/**
 * Handle session/*  ww  w.  j  ava2 s  . c om*/
 * @param token access token
 * @param node Client node
 * @param session web socket session
 */
private void handleSession(String token, String node, Session session) {

    LOGGER.info("Client: " + node + " trying to connect the sever.");

    if (StringUtils.isNullOrEmpty(token)) {
        try {
            String message = "Closing session from node: " + node + " due to invalid access token.";
            sendErrorMessage(session, message);
        } catch (IOException | JSONException e) {
            LOGGER.error("Error occurred while closing session with client node: " + node);
        }
        return;
    }
    TokenMgtDao tokenMgtDao = new TokenMgtDao();
    AccessToken accessToken = tokenMgtDao.getAccessToken(token);
    ConnectionHandler connectionHandler = new ConnectionHandler();
    if (accessToken == null || !UserStoreConstants.ACCESS_TOKEN_STATUS_ACTIVE.equals(accessToken.getStatus())) {
        try {
            String message = "Closing session with node: " + node + " due to invalid access token.";
            sendErrorMessage(session, message);
        } catch (IOException | JSONException e) {
            LOGGER.error("Error occurred while closing session with node: " + node, e);
        }
    } else if (connectionHandler.isNodeConnected(accessToken, node)) {
        try {
            LOGGER.info("Client: " + node + " is already connected. Checking whether the Identity Broker node "
                    + "the client connected was up and running");
            String connectedServer = connectionHandler.getConnectedServer(accessToken, node);
            HttpURLConnection conn = null;
            try {
                conn = getHttpURLConnection(connectedServer, node);

                if (conn != null && conn.getResponseCode() != 200) {
                    // Server responded with a status non other than 200. Which means server is not contactable.
                    // So accepting the connection.
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Server : " + connectedServer + " responded with a status not 200. "
                                + "Status relieved : " + conn.getResponseCode()
                                + "Accepting current connection.");
                    }
                    addConnection(node, session, accessToken, connectionHandler);
                    return;
                }
            } catch (ConnectException e) {
                // Suppressing the exception. Server cannot be contacted so connection coming in is valid.
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Cannot connect to the server : " + connectedServer + ". "
                            + "Accepting current connection.", e);
                }
                addConnection(node, session, accessToken, connectionHandler);
                return;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            isOnCloseNeededMap.put(session.getId(), false);

            String message = "Client: " + node + " already connected. This may be an inconsistency of "
                    + "the server notification of agent";
            sendErrorMessage(session, message);
        } catch (IOException | JSONException e) {
            LOGGER.error("Error occurred while closing session with node: " + node, e);
        }
    } else if (connectionHandler.isConnectionLimitExceed(accessToken.getTenant(), accessToken.getDomain())) {
        try {
            String message = "No of agent connections limit exceeded for tenant: " + accessToken.getTenant();
            sendErrorMessage(session, message);
        } catch (IOException | JSONException e) {
            LOGGER.error("Error occurred while closing session with node: " + node, e);
        }
    } else {
        addConnection(node, session, accessToken, connectionHandler);
    }
}

From source file:org.wso2.carbon.identity.agent.outbound.server.UserStoreServerEndpoint.java

@OnClose
public void onClose(@PathParam("node") String node, CloseReason closeReason, Session session) {

    Boolean isOnCloseNeeded = this.isOnCloseNeededMap.get(session.getId());
    if (isOnCloseNeeded != null && !isOnCloseNeeded) {
        isOnCloseNeededMap.remove(session.getId());
        return;//  w  ww  . j ava  2s.c o  m
    }

    TokenMgtDao tokenMgtDao = new TokenMgtDao();
    AccessToken accessToken = tokenMgtDao
            .getAccessToken(getAccessTokenFromUserProperties(session.getUserProperties()));

    LOGGER.info("Connection close triggered with status code : " + closeReason.getCloseCode().getCode()
            + " On reason " + closeReason.getReasonPhrase() + " from " + node + " in tenant "
            + accessToken.getTenant());
    if (accessToken != null) {
        serverHandler.removeSession(accessToken.getTenant(), accessToken.getDomain(), session);
        AgentMgtDao agentMgtDao = new AgentMgtDao();
        agentMgtDao.updateConnection(accessToken.getId(), node, serverNode,
                UserStoreConstants.CLIENT_CONNECTION_STATUS_CONNECTION_FAILED);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Connection close for tenant: " + accessToken.getTenant());
        }
        String msg = "Client : " + node + " from " + accessToken.getTenant()
                + " disconnected from server node: " + serverNode;
        LOGGER.info(msg);
    }
}