Example usage for javax.websocket Session getQueryString

List of usage examples for javax.websocket Session getQueryString

Introduction

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

Prototype

String getQueryString();

Source Link

Usage

From source file:feedme.controller.SocketServer.java

/**
 * Called when a socket connection opened
 * *//*  w  ww.  j a  va2s . c om*/
@OnOpen
public void onOpen(Session session) {

    System.out.println(session.getId() + " has opened a connection");

    Map<String, String> queryParams = getQueryMap(session.getQueryString());

    String name = "";

    if (queryParams.containsKey("name")) {

        // Getting client name via query param
        name = queryParams.get("name");
        try {
            name = URLDecoder.decode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // Mapping client name and session id

    }
    if (!name.equals("customer")) {
        nameSessionPair.put(name, session);
        sessions.add(session);
    }

    // Adding session to session list

    try {
        // Sending session id to the client that just connected
        session.getBasicRemote().sendText(jsonUtils.getClientDetailsJson(name, "Your session details"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Sessions size " + sessions.size());
    for (Iterator<Map.Entry<String, Session>> it = nameSessionPair.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, Session> e = it.next();
        System.out.println("rest id " + e.getKey() + " rest_session_id " + e.getValue().getId().toString());
    }

}

From source file:io.apicurio.hub.editing.EditApiDesignEndpoint.java

/**
 * Called when a web socket connection is made.  The format for the web socket URL endpoint is:
 * //from www.j  a v a 2s  . c om
 *   /designs/{designId}?uuid={uuid}&user={user}&secret={secret}
 *   
 * The uuid, user, and secret query parameters must be present for a connection to be 
 * successfully made.
 * 
 * @param session
 */
@OnOpen
public void onOpenSession(Session session) {
    String designId = session.getPathParameters().get("designId");
    logger.debug("WebSocket opened: {}", session.getId());
    logger.debug("\tdesignId: {}", designId);

    String queryString = session.getQueryString();
    Map<String, String> queryParams = parseQueryString(queryString);
    String uuid = queryParams.get("uuid");
    String userId = queryParams.get("user");
    String secret = queryParams.get("secret");

    this.metrics.socketConnected(designId, userId);

    logger.debug("\tuuid: {}", uuid);
    logger.debug("\tuser: {}", userId);

    ApiDesignEditingSession editingSession = null;

    try {
        long contentVersion = editingSessionManager.validateSessionUuid(uuid, designId, userId, secret);

        // Join the editing session (or create a new one) for the API Design
        editingSession = this.editingSessionManager.getOrCreateEditingSession(designId);
        Set<Session> otherSessions = editingSession.getSessions();
        if (editingSession.isEmpty()) {
            this.metrics.editingSessionCreated(designId);
        }
        editingSession.join(session, userId);

        // Send "join" messages for each user already in the session
        for (Session otherSession : otherSessions) {
            String otherUser = editingSession.getUser(otherSession);
            editingSession.sendJoinTo(session, otherUser, otherSession.getId());
        }

        // Send any commands that have been created since the user asked to join the editing session.
        List<ApiDesignCommand> commands = this.storage.listContentCommands(userId, designId, contentVersion);
        for (ApiDesignCommand command : commands) {
            String cmdData = command.getCommand();

            StringBuilder builder = new StringBuilder();
            builder.append("{");
            builder.append("\"contentVersion\": ");
            builder.append(command.getContentVersion());
            builder.append(", ");
            builder.append("\"type\": \"command\", ");
            builder.append("\"command\": ");
            builder.append(cmdData);
            builder.append("}");

            logger.debug("Sending command to client (onOpenSession): {}", builder.toString());

            session.getBasicRemote().sendText(builder.toString());
        }

        editingSession.sendJoinToOthers(session, userId);
    } catch (ServerError | StorageException | IOException e) {
        if (editingSession != null) {
            editingSession.leave(session);
        }
        logger.error("Error validating editing session UUID for API Design ID: " + designId, e);
        try {
            session.close(new CloseReason(CloseCodes.CANNOT_ACCEPT,
                    "Error opening editing session: " + e.getMessage()));
        } catch (IOException e1) {
            logger.error(
                    "Error closing web socket session (attempted to close due to error validating editing session UUID).",
                    e1);
        }
    }
}

From source file:oauth.OAuthTokenValdiator.java

/**
 * @param session of the user./*from  w  w w  .jav  a  2s.c om*/
 * @return retreive the token from the query string
 */
private String getTokenFromSession(Session session) {
    String queryString = session.getQueryString();
    if (queryString != null) {
        String[] allQueryParamPairs = queryString.split(QUERY_STRING_SEPERATOR);

        for (String keyValuePair : allQueryParamPairs) {
            String[] queryParamPair = keyValuePair.split(QUERY_KEY_VALUE_SEPERATOR);

            if (queryParamPair.length != 2) {
                log.warn("Invalid query string [" + queryString + "] passed in.");
                break;
            }
            if (queryParamPair[0].equals(TOKEN_IDENTIFIER)) {
                return queryParamPair[1];
            }
        }
    }
    return null;
}

From source file:org.wso2.carbon.device.mgt.extensions.remote.session.RemoteSessionManagementServiceImpl.java

@Override
public void initializeSession(Session session, String deviceType, String deviceId, String operationId)
        throws RemoteSessionManagementException {

    // Check whether required configurations are enabled
    if (!RemoteSessionManagementDataHolder.getInstance().isEnabled()) {
        throw new RemoteSessionManagementException("Remote session feature is disabled.");
    } else if (RemoteSessionManagementDataHolder.getInstance().getServerUrl() == null) {
        throw new RemoteSessionManagementException("Server url has not been configured.");
    }/*from   w ww.j  a v  a2 s .  c om*/

    // Read Query Parameters for obtain the token
    Map<String, List<String>> sessionQueryParam = new HashMap();
    List<String> sessionQueryParamList = new LinkedList<>();
    sessionQueryParamList.add(session.getQueryString());
    sessionQueryParam.put(RemoteSessionConstants.QUERY_STRING, sessionQueryParamList);

    // Validate the token
    OAuthAuthenticator oAuthAuthenticator = RemoteSessionManagementDataHolder.getInstance()
            .getOauthAuthenticator();
    AuthenticationInfo authenticationInfo = oAuthAuthenticator.isAuthenticated(sessionQueryParam);

    if (authenticationInfo != null && authenticationInfo.isAuthenticated()) {
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantDomain(authenticationInfo.getTenantDomain(), true);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(authenticationInfo.getUsername());
            if (deviceId != null && !deviceId.isEmpty() && deviceType != null && !deviceType.isEmpty()) {
                DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
                deviceIdentifier.setId(deviceId);
                deviceIdentifier.setType(deviceType);

                // Check authorization of user for given device
                boolean userAuthorized = RemoteSessionManagementDataHolder.getInstance()
                        .getDeviceAccessAuthorizationService()
                        .isUserAuthorized(deviceIdentifier, authenticationInfo.getUsername());
                if (userAuthorized) {
                    // set common settings for session
                    session.setMaxBinaryMessageBufferSize(
                            RemoteSessionManagementDataHolder.getInstance().getMaxMessageBufferSize());
                    session.setMaxTextMessageBufferSize(
                            RemoteSessionManagementDataHolder.getInstance().getMaxMessageBufferSize());
                    session.setMaxIdleTimeout(
                            RemoteSessionManagementDataHolder.getInstance().getMaxIdleTimeout());

                    // if session initiated using operation id means request came from device
                    if (operationId != null) {
                        // create new device session
                        initializeDeviceSession(session, authenticationInfo.getTenantDomain(), deviceType,
                                deviceId, operationId);
                    } else {
                        // create new client session
                        initializeClientSession(session, authenticationInfo.getTenantDomain(), deviceType,
                                deviceId);
                    }
                    log.info("Current remote sessions count: "
                            + RemoteSessionManagementDataHolder.getInstance().getSessionMap().size());

                } else {
                    throw new RemoteSessionManagementException("Missing device Id or type ");
                }
            } else {
                throw new RemoteSessionManagementException("Unauthorized Access for the device Type : "
                        + deviceType + " , deviceId : " + deviceId);
            }
        } catch (OperationManagementException | InvalidDeviceException e) {
            throw new RemoteSessionManagementException("Error occurred while adding initial operation for the "
                    + "device Type : " + deviceType + " , deviceId : " + deviceId);
        } catch (DeviceAccessAuthorizationException e) {
            throw new RemoteSessionManagementException(
                    "Error occurred while device access authorization for the " + "device Type : " + deviceType
                            + " , " + "deviceId : " + deviceId);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

    } else {
        throw new RemoteSessionManagementException("Invalid token");
    }
}

From source file:org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint.SuperTenantSubscriptionEndpoint.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.
 *///ww w  . j av  a 2  s . c om
@OnOpen
public void onOpen(Session session, EndpointConfig config, @PathParam("streamname") String streamName,
        @PathParam("version") String version) {
    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()
                        .setTenantId(MultitenantConstants.SUPER_TENANT_ID);
                ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService()
                        .subscribeWebsocket(streamName, version, session);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
        } else {
            log.info("Failed to authorize the connection for the stream : " + streamName + " , version : "
                    + version);
        }
    } 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 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  w  w  .  j  av  a2 s  . c  om*/
@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);
        }
    }
}