<commit_before>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.wso2.carbon.device.mgt.extensions.remote.session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.AuthenticationInfo;
import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.OAuthAuthenticator;
import org.wso2.carbon.device.mgt.extensions.remote.session.constants.RemoteSessionConstants;
import org.wso2.carbon.device.mgt.extensions.remote.session.dto.RemoteSession;
import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException;
import org.wso2.carbon.device.mgt.extensions.remote.session.internal.RemoteSessionManagementDataHolder;

import javax.websocket.CloseReason;
import javax.websocket.Session;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.Map;

/**
 * Class @{@link RemoteSessionManagementServiceImpl} is the implementation of @{@link RemoteSessionManagementService}
 * which is used manage initial connection, sending messages to peer session, manage and close the session.
 */
public class RemoteSessionManagementServiceImpl implements RemoteSessionManagementService {

    private static final Log log = LogFactory.getLog(RemoteSessionManagementServiceImpl.class);

    @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.");
        }

        // 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);

        // if session initiated using operation id means request came from device.
        if (operationId == null) {
            // 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());

                            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");
            }

        } else {
            // set common settings for session
            session.setMaxBinaryMessageBufferSize(RemoteSessionManagementDataHolder.getInstance()
                    .getMaxMessageBufferSize());
            session.setMaxTextMessageBufferSize(RemoteSessionManagementDataHolder.getInstance()
                    .getMaxMessageBufferSize());
            session.setMaxIdleTimeout(RemoteSessionManagementDataHolder.getInstance().getMaxIdleTimeout());
            String uuid = session.getQueryString();

            if (uuid != null && uuid.isEmpty()) {
                log.error("Could not find a UUID related to the remote session");
            } else {
                String tenantDomain = RemoteSessionManagementDataHolder.getInstance().getUuidToTenantMap().remove(uuid);
                if (tenantDomain == null || tenantDomain.isEmpty()) {
                    log.error("Invalid UUID, could not create the remote session");
                } else {
                    // create new device session
                    initializeDeviceSession(session, tenantDomain, deviceType, deviceId, operationId, uuid);
                }
            }
        }
    }<commit_msg>Fix an issue with handling the new uuid<commit_after>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.wso2.carbon.device.mgt.extensions.remote.session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.AuthenticationInfo;
import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.OAuthAuthenticator;
import org.wso2.carbon.device.mgt.extensions.remote.session.constants.RemoteSessionConstants;
import org.wso2.carbon.device.mgt.extensions.remote.session.dto.RemoteSession;
import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException;
import org.wso2.carbon.device.mgt.extensions.remote.session.internal.RemoteSessionManagementDataHolder;

import javax.websocket.CloseReason;
import javax.websocket.Session;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Class @{@link RemoteSessionManagementServiceImpl} is the implementation of @{@link RemoteSessionManagementService}
 * which is used manage initial connection, sending messages to peer session, manage and close the session.
 */
public class RemoteSessionManagementServiceImpl implements RemoteSessionManagementService {

    private static final Log log = LogFactory.getLog(RemoteSessionManagementServiceImpl.class);

    @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.");
        }

        // 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);

        // if session initiated using operation id means request came from device.
        if (operationId == null) {
            // 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());

                            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");
            }

        } else {
            // set common settings for session
            session.setMaxBinaryMessageBufferSize(RemoteSessionManagementDataHolder.getInstance()
                    .getMaxMessageBufferSize());
            session.setMaxTextMessageBufferSize(RemoteSessionManagementDataHolder.getInstance()
                    .getMaxMessageBufferSize());
            session.setMaxIdleTimeout(RemoteSessionManagementDataHolder.getInstance().getMaxIdleTimeout());
            String uuid = null;
            String queryParam = session.getQueryString();
            String[] rawUUID = queryParam.split("=");
            if (rawUUID.length != 2) {
                log.warn("Invalid query string [" + Arrays.toString(rawUUID) + "] passed in.");
            }

            if (rawUUID[0].equals("websocketToken")) {
                uuid = rawUUID[1];
            }

            if (uuid != null && uuid.isEmpty()) {
                log.error("Could not find a UUID related to the remote session");
            } else {
                String tenantDomain = RemoteSessionManagementDataHolder.getInstance().getUuidToTenantMap().remove(uuid);
                if (tenantDomain == null || tenantDomain.isEmpty()) {
                    log.error("Invalid UUID, could not create the remote session");
                } else {
                    // create new device session
                    initializeDeviceSession(session, tenantDomain, deviceType, deviceId, operationId, uuid);
                }
            }
        }
    }
{'fraction_non_alphanumeric': 0.08240110713873833, 'fraction_numerical': 0.00328681812939684, 'mean_word_length': 2.542279411764706, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5050106', 'n_tokens_mistral': 4030, 'n_tokens_neox': 3889, 'n_words': 912}