public RegistryCacheInvalidationClient() throws APIManagementException {
   APIManagerConfiguration config =
       ServiceReferenceHolder.getInstance()
           .getAPIManagerConfigurationService()
           .getAPIManagerConfiguration();
   environments = config.getApiGatewayEnvironments();
 }
 private ThrottlePolicyDeploymentManager() {
   APIManagerConfiguration config =
       ServiceReferenceHolder.getInstance()
           .getAPIManagerConfigurationService()
           .getAPIManagerConfiguration();
   environments = config.getApiGatewayEnvironments();
 }
  public String getGroupingIdentifiers(String loginResponse) {

    JSONObject obj;
    String username = null;
    Boolean isSuperTenant;
    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    String claim = "http://wso2.org/claims/organization";
    String organization = null;
    try {
      obj = new JSONObject(loginResponse);
      username = (String) obj.get("user");
      isSuperTenant = (Boolean) obj.get("isSuperTenant");

      RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();

      // if the user is not in the super tenant domain then find the domain name and tenant id.
      if (!isSuperTenant) {
        tenantDomain = MultitenantUtils.getTenantDomain(username);
        tenantId =
            ServiceReferenceHolder.getInstance()
                .getRealmService()
                .getTenantManager()
                .getTenantId(tenantDomain);
      }

      UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
      UserStoreManager manager = realm.getUserStoreManager();
      organization =
          manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null);
      if (organization != null) {
        organization = tenantDomain + "/" + organization.trim();
      }
    } catch (JSONException e) {
      log.error("Exception occured while trying to get group Identifier from login response");
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
      log.error("Error while checking user existence for " + username);
    }

    return organization;
  }
public class GlobalThrottleEngineClient {
  private AuthenticationAdminStub authenticationAdminStub = null;
  private static final Logger log = Logger.getLogger(GlobalThrottleEngineClient.class);
  ThrottleProperties.PolicyDeployer policyDeployerConfiguration =
      ServiceReferenceHolder.getInstance()
          .getAPIManagerConfigurationService()
          .getAPIManagerConfiguration()
          .getThrottleProperties()
          .getPolicyDeployer();

  private String login()
      throws RemoteException, LoginAuthenticationExceptionException, MalformedURLException {
    authenticationAdminStub =
        new AuthenticationAdminStub(
            policyDeployerConfiguration.getServiceUrl() + "AuthenticationAdmin");
    String sessionCookie = null;

    if (authenticationAdminStub.login(
        policyDeployerConfiguration.getUsername(),
        policyDeployerConfiguration.getPassword(),
        new URL(policyDeployerConfiguration.getServiceUrl()).getHost())) {
      ServiceContext serviceContext =
          authenticationAdminStub._getServiceClient().getLastOperationContext().getServiceContext();
      sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
    }
    return sessionCookie;
  }

  /**
   * Checks the validity of a execution plan
   *
   * @param executionPlan
   * @return boolean
   */
  public boolean validateExecutionPlan(String executionPlan) {

    ServiceClient serviceClient;
    Options options;
    String result = null;
    try {
      String sessionCookie = login();
      EventProcessorAdminServiceStub eventProcessorAdminServiceStub =
          new EventProcessorAdminServiceStub(
              policyDeployerConfiguration.getServiceUrl() + "EventProcessorAdminService");

      serviceClient = eventProcessorAdminServiceStub._getServiceClient();
      options = serviceClient.getOptions();
      options.setManageSession(true);
      options.setProperty(HTTPConstants.COOKIE_STRING, sessionCookie);

      result = eventProcessorAdminServiceStub.validateExecutionPlan(executionPlan);

    } catch (RemoteException e) {
      return false;
    } catch (MalformedURLException e) {
      return false;
    } catch (LoginAuthenticationExceptionException e) {
      return false;
    }

    if ("success".equalsIgnoreCase(result)) {
      return true;
    }
    return false;
  }

  /**
   * 1. Check validity of execution plan 2. If execution plan exist with same name edit it 3. Else
   * deploy new execution plan
   *
   * @param name Name of execution plan
   * @param executionPlan execution query plan
   * @param sessionCookie session cookie to use established connection
   * @throws RemoteException
   */
  private void deploy(String name, String executionPlan, String sessionCookie)
      throws RemoteException {
    ServiceClient serviceClient;
    Options options;

    EventProcessorAdminServiceStub eventProcessorAdminServiceStub =
        new EventProcessorAdminServiceStub(
            policyDeployerConfiguration.getServiceUrl() + "EventProcessorAdminService");
    serviceClient = eventProcessorAdminServiceStub._getServiceClient();
    options = serviceClient.getOptions();
    options.setManageSession(true);
    options.setProperty(HTTPConstants.COOKIE_STRING, sessionCookie);

    eventProcessorAdminServiceStub.validateExecutionPlan(executionPlan);
    ExecutionPlanConfigurationDto[] executionPlanConfigurationDtos =
        eventProcessorAdminServiceStub.getAllActiveExecutionPlanConfigurations();
    boolean isUpdateRequest = false;
    if (executionPlanConfigurationDtos != null) {
      for (ExecutionPlanConfigurationDto executionPlanConfigurationDto :
          executionPlanConfigurationDtos) {
        if (executionPlanConfigurationDto.getName().trim().equals(name)) {
          eventProcessorAdminServiceStub.editActiveExecutionPlan(executionPlan, name);
          isUpdateRequest = true;
          break;
        }
      }
    }
    if (!isUpdateRequest) {
      eventProcessorAdminServiceStub.deployExecutionPlan(executionPlan);
    }
  }

  private void logout() throws RemoteException, LogoutAuthenticationExceptionException {
    authenticationAdminStub.logout();
  }

  public void deployExecutionPlan(String name, String executionPlan) throws Exception {
    try {
      String sessionID = login();
      deploy(name, executionPlan, sessionID);
    } finally {
      try {
        logout();
      } catch (RemoteException e) {
        log.error("Error when logging out from global throttling engine. " + e.getMessage(), e);
      } catch (LogoutAuthenticationExceptionException e) {
        log.error("Error when logging out from global throttling engine. " + e.getMessage(), e);
      }
    }
  }

  /**
   * This method will be used to delete single execution plan.
   *
   * @param name execution plan name to be deleted.
   */
  public void deleteExecutionPlan(String name) {
    ServiceClient serviceClient;
    Options options;
    String sessionID = null;
    try {
      sessionID = login();
    } catch (RemoteException e) {
      log.error(
          "Error while connecting to login central policy management server" + e.getMessage());
    } catch (LoginAuthenticationExceptionException e) {
      log.error(
          "Error while connecting to login central policy management server, "
              + "Check user name and password"
              + e.getMessage());
    } catch (MalformedURLException e) {
      log.error(
          "Error while connecting to login central policy management server, check URL"
              + e.getMessage());
    }
    EventProcessorAdminServiceStub eventProcessorAdminServiceStub = null;
    try {
      eventProcessorAdminServiceStub =
          new EventProcessorAdminServiceStub(
              policyDeployerConfiguration.getServiceUrl() + "EventProcessorAdminService");
      serviceClient = eventProcessorAdminServiceStub._getServiceClient();
      options = serviceClient.getOptions();
      options.setManageSession(true);
      options.setProperty(HTTPConstants.COOKIE_STRING, sessionID);
      eventProcessorAdminServiceStub.undeployActiveExecutionPlan(name);
    } catch (AxisFault axisFault) {
      log.error(
          "Error while connecting to login central policy management server to delete "
              + "execution plan."
              + axisFault);
    } catch (RemoteException e) {
      log.error(
          "Error while connecting to login central policy management server to delete "
              + "execution plan."
              + e.getMessage());
    }
  }
}