/**
  * Get tenants associated with a user.
  *
  * @param username
  * @return
  * @throws SiteWhereException
  */
 @RequestMapping(value = "/{username}/tenants", method = RequestMethod.GET)
 @ResponseBody
 @ApiOperation(value = "Find tenants associated with a given user")
 @Secured({SitewhereRoles.ROLE_ADMINISTER_USERS})
 public List<ITenant> getTenantsForUsername(
     @ApiParam(value = "Unique username", required = true) @PathVariable String username,
     @ApiParam(value = "Include runtime info", required = false)
         @RequestParam(required = false, defaultValue = "false")
         boolean includeRuntimeInfo)
     throws SiteWhereException {
   Tracer.start(TracerCategory.RestApiCall, "getAuthoritiesForUsername", LOGGER);
   try {
     List<ITenant> results = SiteWhere.getServer().getAuthorizedTenants(username);
     if (includeRuntimeInfo) {
       for (ITenant tenant : results) {
         ISiteWhereTenantEngine engine = SiteWhere.getServer().getTenantEngine(tenant.getId());
         if (engine != null) {
           ((Tenant) tenant).setEngineState(engine.getEngineState());
         }
       }
     }
     return results;
   } finally {
     Tracer.stop(LOGGER);
   }
 }
  @RequestMapping("/tenant/{tenantId}")
  public ModelAndView chooseTenant(
      @PathVariable("tenantId") String tenantId,
      @RequestParam(required = false) String redirect,
      HttpServletRequest servletRequest) {
    Tracer.start(TracerCategory.AdminUserInterface, "chooseTenant", LOGGER);
    try {
      if ((SecurityContextHolder.getContext() == null)
          || (SecurityContextHolder.getContext().getAuthentication() == null)) {
        return login();
      }

      // If no redirect specified, show server info page.
      if ((redirect == null) || (redirect.length() == 0)) {
        redirect = "../server.html";
      }

      // Find tenants the logged in user is able to view.
      IUser user = LoginManager.getCurrentlyLoggedInUser();
      List<ITenant> matches = SiteWhere.getServer().getAuthorizedTenants(user.getUsername());
      ITenant chosen = null;
      for (ITenant tenant : matches) {
        if (tenant.getId().equals(tenantId)) {
          chosen = tenant;
        }
      }

      // Trying to choose an invalid or unauthorized tenant.
      if (chosen == null) {
        return showError("Invalid tenant choice.");
      }

      setChosenTenant(chosen, servletRequest);
      return new ModelAndView("redirect:" + redirect);
    } catch (SiteWhereException e) {
      return showError(e);
    } finally {
      Tracer.stop(LOGGER);
    }
  }