@Monitor(
      server = EMAIL_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_XML_WEBSERVICE,
      serviceUrlKeys = "EMAILSERVICE")
  private DetectResult monitorEmailServer() {
    DetectResult result = new DetectResult();
    try {
      UserProfile userProfile = BackendServerMonitorUtil.createUserProfile();
      TnContext tc = BackendServerMonitorUtil.createTnContext();
      EmailConfirmationRequest request = new EmailConfirmationRequest();
      request.setContextString(tc.toContextString());
      request.setEmail("*****@*****.**");
      request.setEmailType(UserTypeDef.COMMON_EMAIL);
      request.setUserId(userProfile.getUserId());
      EmailConfirmationResponse response =
          TelepersonalizeProxy.getInstance().sendEmail(request, tc);
      if (response.isSuccess()) {
        result.isSuccess = true;
      } else {
        result.isSuccess = false;
        result.msg = response.getErrorMessage();
      }

    } catch (Exception ex) {
      logger.fatal("#monitorEmailServer", ex);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when sendMail()"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(ex);
    }
    return result;
  }
  @Monitor(
      server = POICATEGORY_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_XML_WEBSERVICE,
      serviceUrlKeys = "POICATEGORY")
  private DetectResult monitorPoiCategoryServer() {
    DetectResult result = new DetectResult();

    try {
      TnContext tc = BackendServerMonitorUtil.createTnContext();
      PoiCategoryRequest request = new PoiCategoryRequest();
      request.setStrContext(tc.toContextString());
      request.setCategoryId(0);
      request.setPoiHierarchyId(1);
      request.setVersion("YP50");
      PoiCategoryResponse response =
          PoiCategoryServiceProxy.getInstance().fetchPoiCategories(request, tc);
      if (response.getCategories() != null && response.getCategories().length > 0) {
        result.isSuccess = true;
      } else {
        result.isSuccess = false;
        result.msg =
            "statusCode = " + response.getStatusCode() + ", statusMsg = " + response.getStatusMsg();
      }
    } catch (Exception e) {
      logger.fatal("fetch poi category tree", e);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when get poi category tree"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(e);
    }

    return result;
  }
  private void hardCodeTnContext(ExecutorContext execContext, UserProfile userProfile) {
    String loginName = userProfile.getMin();
    String carrier = userProfile.getCarrier();
    String device = userProfile.getDevice();
    String product = userProfile.getPlatform();
    String version = userProfile.getVersion();
    String userID = userProfile.getUserId();
    String applicationName = userProfile.getProduct();
    // String mapDpi = userProfile.getMapDpi();
    String locale = userProfile.getLocale();
    // String programCode = userProfile.getProgramCode();

    TnContext tc = new TnContext();
    tc.addProperty(TnContext.PROP_LOGIN_NAME, loginName);
    tc.addProperty(TnContext.PROP_CARRIER, carrier);
    tc.addProperty(TnContext.PROP_DEVICE, device);
    tc.addProperty(TnContext.PROP_PRODUCT, product);
    tc.addProperty(TnContext.PROP_VERSION, version);
    //      tc.addProperty("user_family",
    // Long.toString(ResourceLoader.getInstance().getUserFamily(userProfile)));
    tc.addProperty("application", applicationName); // "application" should defined in TnContext
    tc.addProperty("c-server class", Constants.CSERVER_CLASS);
    tc.addProperty("c-server url", execContext.getServerUrl());
    // tc.addProperty("map_dpi", mapDpi);
    tc.addProperty("locale", locale);
    // tc.addProperty("program_code", programCode);

    tc.addProperty(TnContext.PROP_REQUESTOR, TnContext.TT_REQUESTOR_TNCLIENT);
  }
  @Monitor(
      server = POIDETAIL_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_PROPERTIES,
      filePath = "config/web_services.properties",
      serviceUrlKeys = "URL_POI_DETAIL")
  private DetectResult monitorPoiDetailServer() {
    DetectResult result = new DetectResult();

    ContentInfoServiceStub stub = null;
    try {
      TnContext tc = BackendServerMonitorUtil.createTnContext();

      GetPoiDetailsRequest getPoiDetailRequest = new GetPoiDetailsRequest();
      getPoiDetailRequest.setClientName(HtmlConstants.clientName);
      getPoiDetailRequest.setClientVersion(HtmlConstants.clientVersion);
      getPoiDetailRequest.setContextString(tc.toContextString());
      getPoiDetailRequest.setTransactionId(System.currentTimeMillis() + "");
      getPoiDetailRequest.setPoiId(getSamplePoiId());

      stub = new ContentInfoServiceStub(WebServiceConfigurator.getUrlOfPoiDetail());
      GetPoiDetailsResponse getPoiDetailResponse = stub.getPoiDetails(getPoiDetailRequest);
      com.telenav.datatypes.services.v20.ResponseStatus status =
          getPoiDetailResponse.getResponseStatus();

      // poi detail can't be found is ok. only 20%-30% has detail information from zhangpan.
      if ("OK".equals(status.getStatusCode())
          || "DB_DATA_NOT_FOUND".equals(status.getStatusCode())) {
        result.isSuccess = true;
      } else {
        result.isSuccess = false;
        result.msg =
            "responseCode = "
                + status.getStatusCode()
                + ", responseMessage = "
                + status.getStatusMessage();
        logger.debug(result.msg);
      }

    } catch (Exception ex) {
      logger.fatal("#monitorLogoImageServer", ex);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when get logo image"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(ex);
    } finally {
      if (stub != null) {
        try {
          WebServiceUtils.cleanupStub(stub);
        } catch (Exception ex) {
        }
      }
    }
    return result;
  }
  /**
   * If DSM server failed, then no choice to use the default one
   *
   * @return
   */
  private TnContext getDefaultTnContext(TnContext tc) {
    if (tc == null) {
      tc = new TnContext();
    }
    tc.addProperty(TnContext.PROP_MAP_DATASET, DEFAULT_MAP_DATA);
    tc.addProperty(TnContext.PROP_POI_DATASET, DEFAULT_POI_DATASET);
    // Add this property to indicate this is a default dsm config
    tc.addProperty(PROP_DSM_SERVER_STATUS, DSM_SERVER_DOWN);

    logger.debug("getDefaultTnContext>>" + tc.getProperty(TnContext.PROP_MAP_DATASET));
    return tc;
  }
  /**
   * TODO add a new record about nickname
   *
   * @param nickNameRequest
   * @param nickNameResponse
   * @param tnContext
   * @return
   */
  public HtmlNickNameResponse addNickName(
      HtmlNickNameRequest nickNameRequest,
      HtmlNickNameResponse nickNameResponse,
      TnContext tnContext) {

    CliTransaction cli = new CliTransaction(CliConstants.TYPE_MODULE);
    cli.setFunctionName("addNickName");
    nickNameResponse.setStatus(ExecutorResponse.STATUS_OK);
    long userId = nickNameRequest.getUserId();
    String userName = nickNameRequest.getNickName();
    nickNameResponse.setNickName(userName);
    UserManagementServiceStub stub = null;
    try {

      logger.debug("addNickName userId:" + userId + ",userName" + userName);
      // set conditions
      GetUserRequestDTO getUserRequest = new GetUserRequestDTO();
      getUserRequest.setParam(Long.toString(userId));
      getUserRequest.setParamType(UserQueryBy.USER_ID);
      getUserRequest.setClientName(HtmlConstants.clientName);
      getUserRequest.setClientVersion(HtmlConstants.clientVersion);
      getUserRequest.setContextString(tnContext.toContextString());
      getUserRequest.setTransactionId(HtmlPoiUtil.getTrxId());

      // get user
      stub = getServer();
      GetUserResponseDTO responseDto = stub.getUser(getUserRequest);
      User user = responseDto.getUser();
      user.setUserName(userName);

      // update user
      UpdateUserRequestDTO updateRequest = new UpdateUserRequestDTO();
      updateRequest.setUser(user);
      updateRequest.setClientName(HtmlConstants.clientName);
      updateRequest.setClientVersion(HtmlConstants.clientVersion);
      updateRequest.setContextString(tnContext.toContextString());
      updateRequest.setTransactionId(HtmlPoiUtil.getTrxId());

      UserManagementResponseDTO updateResponse = stub.updateUser(updateRequest);

    } catch (Exception e) {
      logger.error(e);
      e.printStackTrace();
      cli.setStatus(e);
      cli.setState(CliConstants.STATUS_FAIL);
    } finally {
      cli.complete();
      WebServiceUtils.cleanupStub(stub);
    }

    return nickNameResponse;
  }
  @Monitor(
      server = ORGANICADVERTISE_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_PROPERTIES,
      filePath = "config/web_services.properties",
      serviceUrlKeys = "URL_ORGANIC_ADS_SEARCH")
  private DetectResult monitorOrganicAdvertiseServer() {
    DetectResult result = new DetectResult();

    com.telenav.services.content.ads.v10.AdServiceStub stub = null;
    try {
      TnContext tc = BackendServerMonitorUtil.createTnContext();

      AdServiceOrganicAdsRequestDTO requestDTO = new AdServiceOrganicAdsRequestDTO();
      requestDTO.setClientName(HtmlConstants.clientName);
      requestDTO.setClientVersion(HtmlConstants.clientVersion);
      requestDTO.setContextString(tc.toContextString());
      requestDTO.setTransactionId(HtmlPoiUtil.getTrxId());
      long[] poiIds = new long[1];
      poiIds[0] = getSamplePoiId();
      requestDTO.setPoiIds(poiIds);

      stub =
          new com.telenav.services.content.ads.v10.AdServiceStub(
              WebServiceConfigurator.getUrlOfOrganicAdsSearch());
      AdServiceResponseDTO response = stub.getOrganicAds(requestDTO);

      if (response != null) {
        result.isSuccess = true;

      } else {
        result.isSuccess = false;
        result.msg = "response is null";
      }
    } catch (Exception ex) {
      logger.fatal("#monitorOrganicAdvertiseServer", ex);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when get logo get organic advertise"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(ex);
    } finally {
      if (stub != null) {
        try {
          WebServiceUtils.cleanupStub(stub);
        } catch (Exception ex) {
        }
      }
    }
    return result;
  }
  @Monitor(
      server = USER_MANAGEMENT_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_PROPERTIES,
      filePath = "config/web_services.properties",
      serviceUrlKeys = "URL_POI_REVIEW_WRITE")
  private DetectResult monitorUserManagementServer() {

    DetectResult result = new DetectResult();

    UserManagementServiceStub stub = null;
    try {
      UserProfile userProfile = BackendServerMonitorUtil.createUserProfile();
      TnContext tc = BackendServerMonitorUtil.createTnContext();

      GetUserRequestDTO getUserRequest = new GetUserRequestDTO();
      getUserRequest.setParam(userProfile.getUserId() + "");
      getUserRequest.setParamType(UserQueryBy.USER_ID);

      getUserRequest.setClientName(HtmlConstants.clientName);
      getUserRequest.setClientVersion(HtmlConstants.clientVersion);
      getUserRequest.setContextString(tc.toContextString());
      getUserRequest.setTransactionId(HtmlPoiUtil.getTrxId());
      // get userInfo
      stub = new UserManagementServiceStub(WebServiceConfigurator.getUrlOfPoiReviewWrite());
      GetUserResponseDTO response = stub.getUser(getUserRequest);
      if (response != null) {
        if (response.getUser() != null) {
          result.isSuccess = true;
        } else {
          result.isSuccess = false;
          result.msg = "GetUserResponseDTO.getUser() is null";
        }
      } else {
        result.isSuccess = false;
        result.msg = "GetUserResponseDTO is Null";
      }
    } catch (Exception ex) {
      logger.fatal("#monitorUserManagementServer", ex);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when getUserName"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(ex);
    } finally {
      if (stub != null) {
        WebServiceUtils.cleanupStub(stub);
      }
    }
    return result;
  }
  public InterceptResult intercept(
      ExecutorRequest request, ExecutorResponse response, ExecutorContext context) {
    TnContext tnContext = context.getTnContext();

    if (tnContext != null && tnContext.size() > 0) {
      if (logger.isDebugEnabled()) {
        logger.debug("Re-use tnContext:" + tnContext);
        logger.debug("Returned.");
      }
      return InterceptResult.PROCEED;
    }

    tnContext = getTnContext(request.getUserProfile(), context);
    context.setTnContext(tnContext);
    return InterceptResult.PROCEED;
  }
  /* used in ShareAddressExecutor */
  @Monitor(
      server = SHAREADDRESS_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_XML_WEBSERVICE,
      serviceUrlKeys = "ADDRESSSHARING")
  private DetectResult monitorShareAddressServer() {
    DetectResult result = new DetectResult();

    try {
      UserProfile userProfile = BackendServerMonitorUtil.createUserProfile();
      TnContext tc = BackendServerMonitorUtil.createTnContext();

      AddressSharingRequest addressSharingRequest = new AddressSharingRequest();
      addressSharingRequest.setUserId(PoiUtil.getLongFrom(userProfile.getUserId()));
      addressSharingRequest.setPtn(userProfile.getMin());
      addressSharingRequest.setContextString(tc.toContextString());
      addressSharingRequest.setAddress(BackendServerMonitorUtil.createStop());

      ContactInfo contact = new ContactInfo();
      contact.setName("test");
      contact.setPtn(userProfile.getMin());
      List<ContactInfo> contactlist = new ArrayList<ContactInfo>();
      contactlist.add(contact);
      addressSharingRequest.setContactList(contactlist);

      AddressSharingResponse addressSharingResponse =
          AddressSharingServiceProxy.getInstance().shareAddress(addressSharingRequest, tc);
      String statusCode = addressSharingResponse.getStatusCode();
      String statusMessage = addressSharingResponse.getStatusMessage();

      if ("OK".equalsIgnoreCase(statusCode)) {
        result.isSuccess = true;
      } else {
        result.isSuccess = false;
        result.msg = "statusCode = " + statusCode + ", statusMessage = " + statusMessage;
      }
    } catch (Exception ex) {
      logger.fatal("#monitorShareAddressServer", ex);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when share address"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(ex);
    }

    return result;
  }
Exemplo n.º 11
0
  public void setUp() {
    tst = new TnSurveyTag();
    tnContext = new TnContext();
    tnContext.addProperty(TnContext.PROP_CARRIER, "ATT");
    tnContext.addProperty(TnContext.PROP_DEVICE, "genericTest");
    tnContext.addProperty(TnContext.PROP_PRODUCT, "ANDROID");
    tnContext.addProperty(TnContext.PROP_VERSION, "6.2.01");
    tnContext.addProperty("application", "ATT_NAV");
    tnContext.addProperty("login", "3817799999");
    tnContext.addProperty("userid", "3707312");

    HttpServletRequest request = new MockHttpServletRequest();
    handler = new DataHandler(request);

    Hashtable clientInfo = new Hashtable();
    clientInfo.put(DataHandler.KEY_CARRIER, "ATT");
    clientInfo.put(DataHandler.KEY_PLATFORM, "ANDROID");
    clientInfo.put(DataHandler.KEY_VERSION, "6.2.01");
    clientInfo.put(DataHandler.KEY_PRODUCTTYPE, "ATT_NAV");
    clientInfo.put(DataHandler.KEY_DEVICEMODEL, "genericTest");

    clientInfo.put(DataHandler.KEY_WIDTH, "480");
    clientInfo.put(DataHandler.KEY_HEIGHT, "800");
    clientInfo.put(DataHandler.KEY_LOCALE, "en_US");
    clientInfo.put(DataHandler.KEY_CLIENT_SUPPORT_SCREEN_WIDTH, "480-800");
    clientInfo.put(DataHandler.KEY_CLIENT_SUPPORT_SCREEN_HEIGHT, "800-480");
    handler.setClientInfo(clientInfo);
  }
 private void setDsmRuleToTnContext(
     UserProfile userProfile, TnContext tc, boolean isAddAllDsmRule) {
   DsmRuleHolder dsmHolder = ResourceHolderManager.getResourceHolder(HolderType.DSM_TYPE);
   if (dsmHolder != null) {
     Map map = dsmHolder.getDsmResponses(userProfile, tc);
     if (map != null) {
       Iterator it = map.keySet().iterator();
       while (it.hasNext()) {
         String key = (String) it.next();
         if (isAddAllDsmRule) {
           tc.addProperty(key, (String) map.get(key));
         } else {
           if (isDsmRuleNeedRegister(key)) {
             tc.addProperty(key, (String) map.get(key));
           }
         }
       }
     }
   }
 }
  /**
   * @TODO query nickname
   *
   * @param nickNameRequest
   * @param nickNameResponse
   * @param tnContext
   * @return
   */
  public HtmlNickNameResponse queryNickName(
      HtmlNickNameRequest nickNameRequest,
      HtmlNickNameResponse nickNameResponse,
      TnContext tnContext) {

    CliTransaction cli = new CliTransaction(CliConstants.TYPE_MODULE);
    cli.setFunctionName("queryNickName");
    long userId = nickNameRequest.getUserId();
    nickNameResponse.setStatus(ExecutorResponse.STATUS_OK);
    nickNameResponse.setUserId(userId);
    nickNameResponse.setNickName("");
    UserManagementServiceStub stub = null;
    try {
      // set query conditions
      GetUserRequestDTO getUserRequest = new GetUserRequestDTO();
      getUserRequest.setParam(Long.toString(userId));
      getUserRequest.setParamType(UserQueryBy.USER_ID);

      getUserRequest.setClientName(HtmlConstants.clientName);
      getUserRequest.setClientVersion(HtmlConstants.clientVersion);
      getUserRequest.setContextString(tnContext.toContextString());
      getUserRequest.setTransactionId(HtmlPoiUtil.getTrxId());
      // get userInfo
      stub = getServer();
      GetUserResponseDTO responseDto = stub.getUser(getUserRequest);
      if (responseDto != null) {
        User user = responseDto.getUser();
        if (user != null) // set response param
        {
          logger.debug("queryNickName userId:" + userId + ",user name:" + user.getUserName());
          // set query result
          nickNameResponse.setNickName(user.getUserName());
        }
        cli.addData("Response", "Status Code:" + responseDto.getResponseStatus());
      }
      // nickNameResponse.setMessage("Status Code =" + statusCode + " Message=" + statusMsg);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      logger.error(e);
      e.printStackTrace();
      cli.setStatus(e);
      cli.setState(CliConstants.STATUS_FAIL);
    } finally {
      cli.complete();
      WebServiceUtils.cleanupStub(stub);
    }

    return nickNameResponse;
  }
  /**
   * @TODO check nickname if exist
   *
   * @param nickNameRequest
   * @param nickNameResponse
   * @param tnContext
   * @return
   */
  public HtmlNickNameResponse checkNickName(
      HtmlNickNameRequest nickNameRequest,
      HtmlNickNameResponse nickNameResponse,
      TnContext tnContext) {

    CliTransaction cli = new CliTransaction(CliConstants.TYPE_MODULE);
    cli.setFunctionName("checkNickName");
    String nickNameStr = nickNameRequest.getNickName();
    nickNameResponse.setIsUniqueNickName(HtmlConstants.OPERATE_UNIQUE_NICKNAME);
    nickNameResponse.setStatus(ExecutorResponse.STATUS_OK);
    UserManagementServiceStub stub = null;
    try {

      // set conditions
      IsUniqueUsernameRequestDTO isUniqueRequest = new IsUniqueUsernameRequestDTO();
      isUniqueRequest.setUserName(nickNameStr);
      isUniqueRequest.setClientName(HtmlConstants.clientName);
      isUniqueRequest.setClientVersion(HtmlConstants.clientVersion);
      isUniqueRequest.setContextString(tnContext.toContextString());
      isUniqueRequest.setTransactionId(HtmlPoiUtil.getTrxId());

      // check NickName
      stub = getServer();
      IsUniqueUsernameResponseDTO isUniqueResponse = stub.isUniqueUsername(isUniqueRequest);
      nickNameResponse.setNickName(nickNameStr);
      if (isUniqueResponse != null) {
        boolean isUnique = isUniqueResponse.getUnique();
        logger.debug("checkNickName userName:"******",isUnique" + isUnique);
        cli.addData("data", "checkNickName userName:"******",isUnique" + isUnique);
        if (isUnique) { // the nick name is unique
          nickNameResponse.setIsUniqueNickName(HtmlConstants.OPERATE_UNIQUE_NICKNAME);
        } else { // the nick name has exist
          nickNameResponse.setIsUniqueNickName(HtmlConstants.OPERATE_NOT_UNIQUE_NICKNAME);
        }
      }

    } catch (Exception e) {
      // TODO Auto-generated catch block
      logger.error(e);
      e.printStackTrace();
      cli.setStatus(e);
      cli.setState(CliConstants.STATUS_FAIL);
    } finally {
      cli.complete();
      WebServiceUtils.cleanupStub(stub);
    }

    return nickNameResponse;
  }
  @Monitor(
      server = ONEBOXSEARCH_SERVER,
      parserClass = ServiceUrlParserFactory.CLASS_PROPERTIES,
      filePath = "config/web_services.properties",
      serviceUrlKeys = "URL_ONE_BOX_SEARCH")
  private DetectResult monitorOneBoxSearchServer() {
    DetectResult result = new DetectResult();

    OneboxSearchServiceStub stub = null;
    try {
      UserProfile userProfile = BackendServerMonitorUtil.createUserProfile();
      TnContext tc = BackendServerMonitorUtil.createTnContext();

      OneboxSearchRequest obReq = new OneboxSearchRequest();

      // set user
      UserInformation user = new UserInformation();
      UserProfile usrProfile = userProfile;
      user.setUserId(usrProfile.getUserId());
      user.setPtn(usrProfile.getMin());
      obReq.setUserInfo(user);

      // set client info
      Date today = new Date();
      // using date only
      String trxnId = String.valueOf(today.getTime());
      obReq.setClientName(ClientNameEnum._MOBILE);
      obReq.setClientVersion("1");
      obReq.setTransactionId(trxnId);

      // set POI data set() and MAP data set
      obReq.setContextString(tc.toContextString());

      // set anchor
      com.telenav.ws.datatypes.address.GeoCode latLon =
          new com.telenav.ws.datatypes.address.GeoCode();
      latLon.setLatitude(37.37453);
      latLon.setLongitude(-121.99983);
      obReq.setAnchor(latLon);

      // set query
      obReq.setQuery("coffee");
      obReq.setStartIndex(0);
      obReq.setResultCount(10);
      // TODO: check sponsor number
      obReq.setSponsorStartIndex(0);
      obReq.setSponsorResultCount(1);
      obReq.setLocale(CommonUtil.getTnLocal(userProfile.getLocale()));
      obReq.setSponsorResultCount(100);
      obReq.setTransactionId(System.currentTimeMillis() + "");

      stub = new OneboxSearchServiceStub(WebServiceConfigurator.getUrlOfOneBox());
      OneboxSearchResponse response = stub.oneboxSearch(obReq);

      if (response != null && "RESULT_FOUND".equals(response.getResponseStatus().getStatusCode())) {
        result.isSuccess = true;
      } else {
        result.isSuccess = false;
        result.msg =
            response == null
                ? "Response is null."
                : "StatusCode = "
                    + response.getResponseStatus().getStatusCode()
                    + ", StatusMessage = "
                    + response.getResponseStatus().getStatusMessage();
      }

    } catch (Exception e) {
      logger.fatal("#monitorOneBoxSearchServer", e);
      result.isSuccess = false;
      result.msg =
          "Exception occurs when one box search"
              + ". Exception msg->"
              + ExceptionUtil.collectExceptionMsg(e);
    } finally {
      if (stub != null) {
        WebServiceUtils.cleanupStub(stub);
      }
    }
    return result;
  }
  public TnContext getTnContext(UserProfile userProfile, ExecutorContext context) {

    String userID = userProfile.getUserId();

    long lUserID = -1;
    if (userID != null && userID.length() > 0) {
      lUserID = Long.parseLong(userID);
    }

    ContextMgrService cms = new ContextMgrService();
    ContextMgrStatus myStatus = null;

    if (logger.isDebugEnabled()) {
      logger.debug("needRegister:" + needRegister);
    }

    TnContext tc = new TnContext();
    try {
      if (needRegister) {
        // get the tncontext from DSM db
        // tc = getTnContextFromDsmDB(userProfile.getMin());
        // set user profile into tncontext
        setUserProfileToTnContext(tc, userProfile, context);
        // set the need register dsm rule into tncontext
        setNeedRegisterDsmRuleToTnContext(userProfile, tc);
        if (logger.isDebugEnabled()) {
          logger.debug("tc -->" + tc);
          logger.debug("tc.length = " + tc.toContextString().length());
        }
        myStatus = cms.registerContext(lUserID, Constants.CALLER_CSERVER, tc);

      } else {
        // set user profile into tncontext
        setUserProfileToTnContext(tc, userProfile, context);
        myStatus = cms.updateContext(tc);
      }
    } catch (Exception e) {
      logger.fatal(e, e);
    }

    // set all the dsm rules in to tncontext
    setAllDsmRuleToTnContext(userProfile, tc);

    DevicePropertiesHolder deviceHolder =
        (DevicePropertiesHolder) ResourceHolderManager.getResourceHolder(HolderType.DEVICE_TYPE);
    if (deviceHolder != null) {
      DeviceProperties deviceProperties = deviceHolder.getDeviceProperties(userProfile, tc);
      if (deviceProperties != null) {
        tc.addProperty(
            GENERATE_LANE_INFO,
            String.valueOf(deviceProperties.getBooleanDefFalse(NAV_ENABLE_LANE_ASSIST)));
      }
    }

    if (myStatus == null || myStatus.getStatusCode() != Error.NO_ERROR) {
      CliTransaction cli =
          com.telenav.cserver.framework.cli.CliTransactionFactory.getInstance(
              CliConstants.TYPE_MODULE);
      cli.setFunctionName("getTnContext");
      cli.addData(
          "cms_status(has issue)", myStatus != null ? myStatus.getStatusCode() + "" : "null");

      tc = getDefaultTnContext(tc);
      if (logger.isDebugEnabled()) {
        logger.debug("tnContext has issue.");
      }

      cli.complete();
    }
    logger.debug("final tc:>>" + tc);
    return tc;
  }
  /**
   * TODO add a new record about nickname
   *
   * @param nickNameRequest
   * @param nickNameResponse
   * @param tnContext
   * @return
   */
  public HtmlNickNameResponse checkAndaddNickName(
      HtmlNickNameRequest nickNameRequest,
      HtmlNickNameResponse nickNameResponse,
      TnContext tnContext) {

    CliTransaction cli = new CliTransaction(CliConstants.TYPE_MODULE);
    cli.setFunctionName("checkAndaddNickName");
    nickNameResponse.setStatus(ExecutorResponse.STATUS_OK);
    UserManagementServiceStub stub = null;
    try {

      String userName = nickNameRequest.getNickName();
      // set conditions
      IsUniqueUsernameRequestDTO isUniqueRequest = new IsUniqueUsernameRequestDTO();
      isUniqueRequest.setUserName(userName);
      isUniqueRequest.setClientName(HtmlConstants.clientName);
      isUniqueRequest.setClientVersion(HtmlConstants.clientVersion);
      isUniqueRequest.setContextString(tnContext.toContextString());
      isUniqueRequest.setTransactionId(HtmlPoiUtil.getTrxId());

      // check NickName
      stub = getServer();
      IsUniqueUsernameResponseDTO isUniqueResponse = stub.isUniqueUsername(isUniqueRequest);
      nickNameResponse.setNickName(userName);

      if (isUniqueResponse != null) {
        boolean isUnique = isUniqueResponse.getUnique();

        logger.debug("checkNickName userName:"******",isUnique" + isUnique);
        cli.addData("data", "checkNickName userName:"******",isUnique" + isUnique);
        if (isUnique) { // the nick name is unique
          nickNameResponse.setIsUniqueNickName(HtmlConstants.OPERATE_UNIQUE_NICKNAME);

          long userId = nickNameRequest.getUserId();

          logger.debug("addNickName userId:" + userId + ",userName" + userName);
          // set conditions
          GetUserRequestDTO getUserRequest = new GetUserRequestDTO();
          getUserRequest.setParam(Long.toString(userId));
          getUserRequest.setParamType(UserQueryBy.USER_ID);
          getUserRequest.setClientName(HtmlConstants.clientName);
          getUserRequest.setClientVersion(HtmlConstants.clientVersion);
          getUserRequest.setContextString(tnContext.toContextString());
          getUserRequest.setTransactionId(HtmlPoiUtil.getTrxId());

          // get user
          GetUserResponseDTO responseDto = stub.getUser(getUserRequest);
          User user = responseDto.getUser();
          if (user != null) {
            user.setUserName(userName);
            // update user
            UpdateUserRequestDTO updateRequest = new UpdateUserRequestDTO();
            updateRequest.setUser(user);
            updateRequest.setClientName(HtmlConstants.clientName);
            updateRequest.setClientVersion(HtmlConstants.clientVersion);
            updateRequest.setContextString(tnContext.toContextString());
            updateRequest.setTransactionId(HtmlPoiUtil.getTrxId());

            UserManagementResponseDTO updateResponse = stub.updateUser(updateRequest);
          }
        } else { // the nick name has exist
          nickNameResponse.setIsUniqueNickName(HtmlConstants.OPERATE_NOT_UNIQUE_NICKNAME);
        }
      } else {
        nickNameResponse.setIsUniqueNickName(HtmlConstants.OPERATE_UNIQUE_NICKNAME);
      }
    } catch (Exception e) {
      logger.error(e);
      e.printStackTrace();
      cli.setStatus(e);
      cli.setState(CliConstants.STATUS_FAIL);
    } finally {
      cli.complete();
      WebServiceUtils.cleanupStub(stub);
    }

    return nickNameResponse;
  }