<commit_before>/*
 * //******************************************************************
 * //
 * // Copyright 2016 Samsung Electronics All Rights Reserved.
 * //
 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 * //
 * // Licensed 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.iotivity.cloud.accountserver.resources.account;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;

import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.db.TokenTable;
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.accountserver.oauth.OAuthProviderFactory;
import org.iotivity.cloud.accountserver.resources.acl.group.GroupResource;
import org.iotivity.cloud.accountserver.util.TypeCastingManager;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.base.exception.ServerException.NotFoundException;
import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
import org.iotivity.cloud.util.Log;

/**
 *
 * This class provides a set of APIs to handle requests about account
 * information of authorized user.
 *
 */
public class AccountManager {

    private OAuthProviderFactory           mFactory                  = null;
    private TypeCastingManager<UserTable>  mUserTableCastingManager  = new TypeCastingManager<>();
    private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();

    public HashMap<String, Object> signUp(String did, String authCode,
            String authProvider, Object options) {

        boolean res = false;
        authProvider = checkAuthProviderName(authProvider);
        res = loadAuthProviderLibrary(authProvider);

        if (!res) {
            throw new InternalServerErrorException(
                    authProvider + " library is not loaded");
        }
        String userUuid = null;
        // set token data
        TokenTable tokenInfo = requestAccessToken(authCode, options);
        tokenInfo.setDid(did);
        tokenInfo.setProvider(authProvider);
        Date currentTime = new Date();
        DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
        tokenInfo.setIssuedtime(transFormat.format(currentTime));

        // set user data
        UserTable userInfo = requestUserInfo(tokenInfo.getAccesstoken(),
                options);
        userInfo.setProvider(authProvider);

        // check uuid
        userUuid = findUuid(userInfo.getUserid(), authProvider);

        storeUserTokenInfo(userUuid, userInfo, tokenInfo, did);

        // make response
        HashMap<String, Object> response = makeSignUpResponse(tokenInfo);

        return response;
    }

    private void storeUserTokenInfo(String userUuid, UserTable userInfo,
            TokenTable tokenInfo, String did) {
        // store db
        if (userUuid == null) {
            userUuid = generateUuid();
            userInfo.setUuid(userUuid);

            AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
                    castUserTableToMap(userInfo));

            // make my private group
            GroupResource.getInstance().createGroup(userInfo.getUuid(),
                    Constants.REQ_GTYPE_PRIVATE);

            // add my device to private group
            GroupResource.getInstance().getGroup(userInfo.getUuid())
                    .addDevice(new HashSet<String>(Arrays.asList(did)));
        }
        tokenInfo.setUuid(userUuid);
        AccountDBManager.getInstance().insertAndReplaceRecord(
                Constants.TOKEN_TABLE, castTokenTableToMap(tokenInfo));
    }

    private String checkAuthProviderName(String authProvider) {

        String authProviderName = null;

        if (authProvider.equalsIgnoreCase(Constants.GITHUB)) {
            authProviderName = Constants.GITHUB;
        } else if (authProvider.equalsIgnoreCase(Constants.SAMSUNG)) {
            authProviderName = Constants.SAMSUNG;
        }
<commit_msg>AccountManager bug fixed (private group creation)<commit_after>/*
 * //******************************************************************
 * //
 * // Copyright 2016 Samsung Electronics All Rights Reserved.
 * //
 * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 * //
 * // Licensed 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.iotivity.cloud.accountserver.resources.account;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;

import org.iotivity.cloud.accountserver.Constants;
import org.iotivity.cloud.accountserver.db.AccountDBManager;
import org.iotivity.cloud.accountserver.db.TokenTable;
import org.iotivity.cloud.accountserver.db.UserTable;
import org.iotivity.cloud.accountserver.oauth.OAuthProviderFactory;
import org.iotivity.cloud.accountserver.resources.acl.group.GroupResource;
import org.iotivity.cloud.accountserver.util.TypeCastingManager;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
import org.iotivity.cloud.base.exception.ServerException.NotFoundException;
import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
import org.iotivity.cloud.util.Log;

/**
 *
 * This class provides a set of APIs to handle requests about account
 * information of authorized user.
 *
 */
public class AccountManager {

    private OAuthProviderFactory           mFactory                  = null;
    private TypeCastingManager<UserTable>  mUserTableCastingManager  = new TypeCastingManager<>();
    private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();

    public HashMap<String, Object> signUp(String did, String authCode,
            String authProvider, Object options) {

        boolean res = false;
        authProvider = checkAuthProviderName(authProvider);
        res = loadAuthProviderLibrary(authProvider);

        if (!res) {
            throw new InternalServerErrorException(
                    authProvider + " library is not loaded");
        }
        String userUuid = null;
        // set token data
        TokenTable tokenInfo = requestAccessToken(authCode, options);
        tokenInfo.setDid(did);
        tokenInfo.setProvider(authProvider);
        Date currentTime = new Date();
        DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
        tokenInfo.setIssuedtime(transFormat.format(currentTime));

        // set user data
        UserTable userInfo = requestUserInfo(tokenInfo.getAccesstoken(),
                options);
        userInfo.setProvider(authProvider);

        // check uuid
        userUuid = findUuid(userInfo.getUserid(), authProvider);

        storeUserTokenInfo(userUuid, userInfo, tokenInfo, did);

        // make response
        HashMap<String, Object> response = makeSignUpResponse(tokenInfo);

        return response;
    }

    private void storeUserTokenInfo(String userUuid, UserTable userInfo,
            TokenTable tokenInfo, String did) {
        // store db
        if (userUuid == null) {
            userUuid = generateUuid();
            userInfo.setUuid(userUuid);

            AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
                    castUserTableToMap(userInfo));

            // make my private group
            GroupResource.getInstance().createGroup(userInfo.getUuid(),
                    Constants.REQ_GTYPE_PRIVATE);
        }
        // add my device to private group
        GroupResource.getInstance().getGroup(userInfo.getUuid())
                .addDevice(new HashSet<String>(Arrays.asList(did)));
        tokenInfo.setUuid(userUuid);
        AccountDBManager.getInstance().insertAndReplaceRecord(
                Constants.TOKEN_TABLE, castTokenTableToMap(tokenInfo));
    }

    private String checkAuthProviderName(String authProvider) {

        String authProviderName = null;

        if (authProvider.equalsIgnoreCase(Constants.GITHUB)) {
            authProviderName = Constants.GITHUB;
        } else if (authProvider.equalsIgnoreCase(Constants.SAMSUNG)) {
            authProviderName = Constants.SAMSUNG;
        }

{'fraction_non_alphanumeric': 0.12872748745202245, 'fraction_numerical': 0.0015746481645507332, 'mean_word_length': 3.0373460468812077, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2503044', 'n_tokens_mistral': 2742, 'n_tokens_neox': 2617, 'n_words': 605}