public BAMServerProfile build() {
    BAMServerProfile bamServerProfile = new BAMServerProfile();
    Registry registry;
    String location;

    if (profileLocation.startsWith(UnifiedEndpointConstants.VIRTUAL_CONF_REG)) {
      registry = CarbonContext.getCurrentContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
      location =
          profileLocation.substring(
              profileLocation.indexOf(UnifiedEndpointConstants.VIRTUAL_CONF_REG)
                  + UnifiedEndpointConstants.VIRTUAL_CONF_REG.length());
      loadBAMProfileFromRegistry(bamServerProfile, registry, location);
    } else if (profileLocation.startsWith(UnifiedEndpointConstants.VIRTUAL_GOV_REG)) {
      registry = CarbonContext.getCurrentContext().getRegistry(RegistryType.SYSTEM_GOVERNANCE);
      location =
          profileLocation.substring(
              profileLocation.indexOf(UnifiedEndpointConstants.VIRTUAL_GOV_REG)
                  + UnifiedEndpointConstants.VIRTUAL_GOV_REG.length());
      loadBAMProfileFromRegistry(bamServerProfile, registry, location);
    } else if (profileLocation.startsWith(UnifiedEndpointConstants.VIRTUAL_REG)) {
      registry = CarbonContext.getCurrentContext().getRegistry(RegistryType.LOCAL_REPOSITORY);
      location =
          profileLocation.substring(
              profileLocation.indexOf(UnifiedEndpointConstants.VIRTUAL_REG)
                  + UnifiedEndpointConstants.VIRTUAL_REG.length());
      loadBAMProfileFromRegistry(bamServerProfile, registry, location);
    } else if (profileLocation.startsWith(UnifiedEndpointConstants.VIRTUAL_FILE)) {
      // TODO
    } else {
      String errMsg = "Invalid bam profile location: " + profileLocation;
      handleError(errMsg);
    }

    return bamServerProfile;
  }
  /**
   * Checks whether received credentials for accessing API is authorized for exporting and importing
   * APIs
   *
   * @param headers HTTP headers of the received request
   * @return Response indicating whether authentication and authorization for accessing API got
   *     succeeded
   * @throws APIExportException If an error occurs while authorizing current user
   */
  public static Response authorizeUser(HttpHeaders headers) throws APIExportException {
    if (!isValidCredentials(headers)) {
      log.error("No username and password is provided for authentication");
      return Response.status(Response.Status.UNAUTHORIZED)
          .entity("No username and password is provided for authentication")
          .type(MediaType.APPLICATION_JSON)
          .build();
    }

    try {
      String tenantDomain = MultitenantUtils.getTenantDomain(username);
      PrivilegedCarbonContext.startTenantFlow();
      PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

      UserStoreManager userstoremanager =
          CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();

      String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);

      // authenticate user provided credentials
      if (userstoremanager.authenticate(tenantAwareUsername, password)) {
        log.info(username + " user authenticated successfully");
        // Get admin role name of the current domain
        String adminRoleName =
            CarbonContext.getCurrentContext()
                .getUserRealm()
                .getRealmConfiguration()
                .getAdminRoleName();

        String[] userRoles = userstoremanager.getRoleListOfUser(tenantAwareUsername);

        // user is only authorized for exporting and importing if he is an admin of his
        // domain
        if (Arrays.asList(userRoles).contains(adminRoleName)) {
          log.info(username + " is authorized to import and export APIs");
          return Response.ok().build();
        } else {
          return Response.status(Response.Status.FORBIDDEN)
              .entity("User Authorization " + "Failed")
              .type(MediaType.APPLICATION_JSON)
              .build();
        }

      } else {
        return Response.status(Response.Status.UNAUTHORIZED)
            .entity("User Authentication " + "Failed")
            .type(MediaType.APPLICATION_JSON)
            .build();
      }

    } catch (UserStoreException e) {
      log.error("Error while accessing user configuration" + e.getMessage());
      throw new APIExportException("Error while accessing user configuration", e);
    } finally {
      PrivilegedCarbonContext.endTenantFlow();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void addTopic(String topicName) throws EventBrokerException {
    if (!validateTopicName(topicName)) {
      throw new EventBrokerException(
          "Topic name "
              + topicName
              + " is not a valid topic name. "
              + "Only alphanumeric characters, hyphens (-), stars(*),"
              + " hash(#) ,dot(.),question mark(?)"
              + " and underscores (_) are allowed.");
    }

    String loggedInUser = CarbonContext.getThreadLocalCarbonContext().getUsername();

    try {
      UserRegistry userRegistry =
          this.registryService.getGovernanceSystemRegistry(
              EventBrokerHolder.getInstance().getTenantId());
      String resourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);

      // we add the topic only if it does not exits. if the topic exists then
      // we don't do any thing.
      if (!userRegistry.resourceExists(resourcePath)) {
        Collection collection = userRegistry.newCollection();
        userRegistry.put(resourcePath, collection);

        // Grant this user (owner) rights to update permission on newly created topic
        UserRealm userRealm =
            EventBrokerHolder.getInstance()
                .getRealmService()
                .getTenantUserRealm(CarbonContext.getThreadLocalCarbonContext().getTenantId());

        userRealm
            .getAuthorizationManager()
            .authorizeUser(
                loggedInUser, resourcePath, EventBrokerConstants.EB_PERMISSION_CHANGE_PERMISSION);
        userRealm
            .getAuthorizationManager()
            .authorizeUser(loggedInUser, resourcePath, EventBrokerConstants.EB_PERMISSION_PUBLISH);
        userRealm
            .getAuthorizationManager()
            .authorizeUser(
                loggedInUser, resourcePath, EventBrokerConstants.EB_PERMISSION_SUBSCRIBE);
      }
    } catch (RegistryException e) {
      throw new EventBrokerException("Cannot access the config registry", e);
    } catch (UserStoreException e) {
      throw new EventBrokerException(
          "Error while granting user "
              + loggedInUser
              + ", permission "
              + EventBrokerConstants.EB_PERMISSION_CHANGE_PERMISSION
              + ", on topic "
              + topicName,
          e);
    }
  }
 @Override
 public void terminatingConfigurationContext(ConfigurationContext configurationContext) {
   CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
   int tid = carbonContext.getTenantId();
   distroyTicketsForTenant(carbonContext.getTenantDomain());
   distroyTicketsForSuperTenant();
   try {
     hdfsInstanceCache.closeTenantUsersFS(carbonContext.getTenantDomain());
     hdfsInstanceCache.closeSuperTenantFS();
     log.info("File system instance successfully closed for tenant " + tid);
   } catch (IOException e) {
     log.error("Error occurred while closinf HDFS file system for tenant " + tid, e);
   }
 }
  /**
   * @return
   * @throws IdentityException
   */
  public String[] getClaimURIs() throws IdentityException {
    String tenatUser =
        MultitenantUtils.getTenantAwareUsername(CarbonContext.getCurrentContext().getUsername());
    String domainName = MultitenantUtils.getTenantDomain(tenatUser);
    String[] claimUris = null;
    try {
      UserRealm realm = IdentityTenantUtil.getRealm(domainName, tenatUser);
      String claimDialect =
          IdentityUtil.getProperty(IdentityConstants.ServerConfig.SSO_ATTRIB_CLAIM_DIALECT);

      if (claimDialect == null || claimDialect.equals("")) {
        // set default
        claimDialect = "http://wso2.org/claims";
      }

      ClaimMapping[] claims = realm.getClaimManager().getAllClaimMappings(claimDialect);
      claimUris = new String[claims.length];

      for (int i = 0; i < claims.length; i++) {
        Claim claim = claims[i].getClaim();
        claimUris[i] = claim.getClaimUri();
      }

    } catch (IdentityException e) {
      log.error("Error while getting realm for " + tenatUser, e);
      throw new IdentityException("Error while getting realm for " + tenatUser + e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
      log.error("Error while getting claims for " + tenatUser, e);
      throw new IdentityException("Error while getting claims for " + tenatUser + e);
    }
    return claimUris;
  }
  @Override
  public void generateApplicationSkeleton(String applicationID, String workingDirectory)
      throws AppFactoryException {

    try {
      String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
      String applicationExtenstion =
          ProjectUtils.getApplicationExtenstion(applicationID, tenantDomain);
      String uploadedFileName =
          applicationID
              + "-1.0.0."
              + applicationExtenstion
              + AppFactoryConstants.UPPLOADABLE_SUFFIX;
      copyUploadedAppToLocation(uploadedFileName, workingDirectory);

      if (log.isDebugEnabled()) {
        log.debug(
            "Application skeleton creation hanlded for Uploaded application type with application key -"
                + applicationID);
      }
    } catch (IOException e) {
      log.error(e);
      throw new AppFactoryException("Error when generating uploaded application skeleton", e);
    }
  }
 @Override
 public void generateDeployableFile(
     String rootPath, String applicationId, String version, String stage)
     throws AppFactoryException {
   String applicationExtenstion =
       ProjectUtils.getApplicationExtenstion(
           applicationId, CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
   String artifactFileName =
       applicationId
           + AppFactoryConstants.APPFACTORY_ARTIFACT_NAME_VERSION_SEPERATOR
           + version
           + AppFactoryConstants.FILENAME_EXTENSION_SEPERATOR
           + applicationExtenstion;
   String uploadedAppSrcFile =
       rootPath
           + File.separator
           + AppFactoryConstants.AF_GIT_TMP_FOLDER
           + File.separator
           + artifactFileName;
   String uploadedApptmpFolder =
       rootPath + File.separator + AppFactoryConstants.DEPLOYABLE_ARTIFACT_FOLDER;
   try {
     FileUtils.copyFileToDirectory(new File(uploadedAppSrcFile), new File(uploadedApptmpFolder));
   } catch (IOException e) {
     String errMsg = "Error when copying folder from src to artifact tmp : " + e.getMessage();
     log.error(errMsg, e);
     throw new AppFactoryException(errMsg, e);
   }
 }
 /**
  * @return
  * @throws IdentityException
  */
 private KeyStoreData[] getKeyStores() throws IdentityException {
   try {
     KeyStoreAdmin admin =
         new KeyStoreAdmin(
             CarbonContext.getThreadLocalCarbonContext().getTenantId(), getGovernanceRegistry());
     boolean isSuperAdmin =
         MultitenantConstants.SUPER_TENANT_ID
                 == CarbonContext.getThreadLocalCarbonContext().getTenantId()
             ? true
             : false;
     return admin.getKeyStores(isSuperAdmin);
   } catch (SecurityConfigException e) {
     log.error("Error when loading the key stores from registry", e);
     throw new IdentityException("Error when loading the key stores from registry", e);
   }
 }
  /** {@inheritDoc} */
  @Override
  public String[] getBackendRoles() throws EventBrokerException {
    UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
    String[] cleanedRoles = new String[0];
    try {
      String adminRole =
          EventBrokerHolder.getInstance()
              .getRealmService()
              .getBootstrapRealmConfiguration()
              .getAdminRoleName();
      String[] allRoles = userRealm.getUserStoreManager().getRoleNames();
      // check if there is only admin role exists.
      if (allRoles != null && allRoles.length > 1) {
        // check if more roles available than admin role and anonymous role
        List<String> allRolesArrayList = new ArrayList<>();
        Collections.addAll(allRolesArrayList, allRoles);

        Iterator<String> it = allRolesArrayList.iterator();
        while (it.hasNext()) {
          String nextRole = it.next();
          if (nextRole.equals(adminRole)
              || nextRole.equals(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME)) {
            it.remove();
          }
        }

        cleanedRoles = allRolesArrayList.toArray(new String[allRolesArrayList.size()]);
      }

    } catch (UserStoreException e) {
      throw new EventBrokerException("Unable to get Roles from user store", e);
    }

    return cleanedRoles;
  }
  /**
   * Configures the swagger resource path form its content and returns the swagger document path.
   *
   * @param rootLocation root location of the swagger files.
   * @param content swagger content.
   * @return Common resource path.
   */
  private String getSwaggerDocumentPath(String rootLocation, JsonObject content)
      throws RegistryException {

    String swaggerDocPath = requestContext.getResourcePath().getPath();
    String swaggerDocName =
        swaggerDocPath.substring(swaggerDocPath.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
    JsonElement infoElement = content.get(SwaggerConstants.INFO);
    JsonObject infoObject = (infoElement != null) ? infoElement.getAsJsonObject() : null;

    if (infoObject == null || infoElement.isJsonNull()) {
      throw new RegistryException("Invalid swagger document.");
    }
    String serviceName = infoObject.get(SwaggerConstants.TITLE).getAsString().replaceAll("\\s", "");
    String serviceProvider = CarbonContext.getThreadLocalCarbonContext().getUsername();

    swaggerResourcesPath =
        rootLocation
            + serviceProvider
            + RegistryConstants.PATH_SEPARATOR
            + serviceName
            + RegistryConstants.PATH_SEPARATOR
            + documentVersion;

    String pathExpression = getSwaggerRegistryPath(swaggerDocName, serviceProvider);

    return RegistryUtils.getAbsolutePath(registry.getRegistryContext(), pathExpression);
  }
 @Override
 public List<Application> getApplicationListForDevice(DeviceIdentifier deviceId)
     throws ApplicationManagementException {
   Device device;
   try {
     int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
     DeviceManagementDAOFactory.openConnection();
     device = deviceDAO.getDevice(deviceId, tenantId);
     if (device == null) {
       if (log.isDebugEnabled()) {
         log.debug(
             "No device is found upon the device identifier '"
                 + deviceId.getId()
                 + "' and type '"
                 + deviceId.getType()
                 + "'. Therefore returning null");
       }
       return null;
     }
     return applicationDAO.getInstalledApplications(device.getId());
   } catch (DeviceManagementDAOException e) {
     throw new ApplicationManagementException(
         "Error occurred while fetching the Application List of '"
             + deviceId.getType()
             + "' device carrying the identifier'"
             + deviceId.getId(),
         e);
   } catch (SQLException e) {
     throw new ApplicationManagementException(
         "Error occurred while opening a connection to the data source", e);
   } finally {
     DeviceManagementDAOFactory.closeConnection();
   }
 }
 @Override
 public List<File> getPreVersionDeleteableFiles(
     String applicationID, String targetVersion, String currentVersion, String workingDir)
     throws AppFactoryException {
   String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
   String applicationExtension;
   applicationExtension = ProjectUtils.getApplicationExtenstion(applicationID, tenantDomain);
   List<File> deletableFiles = new ArrayList<File>();
   deletableFiles.add(
       new File(
           CarbonUtils.getTmpDir()
               + File.separator
               + AppFactoryConstants.REPOSITORY_BRANCH
               + File.separator
               + applicationID
               + File.separator
               + targetVersion
               + File.separator
               + applicationID
               + AppFactoryConstants.MINUS
               + AppFactoryConstants.INITIAL_UPLOADED_APP_VERSION
               + AppFactoryConstants.DOT_SEPERATOR
               + applicationExtension));
   return deletableFiles;
 }
 @Override
 public void generateApplicationSkeleton(String applicationId, String workingDirectory)
     throws AppFactoryException {
   boolean isSuccess =
       ProjectUtils.generateProjectArchetype(
           applicationId,
           workingDirectory,
           ProjectUtils.getArchetypeRequest(applicationId, getProperty(MAVEN_ARCHETYPE_REQUEST)));
   if (isSuccess) {
     String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
     File archetypeDir =
         new File(
             CarbonUtils.getTmpDir()
                 + File.separator
                 + tenantDomain
                 + File.separator
                 + applicationId
                 + File.separator
                 + AppFactoryConstants.MAVEN_ARCHETYPE_DIR);
     initialDeployArtifactGeneration(applicationId, workingDirectory, archetypeDir);
     ProjectUtils.configureFinalName(archetypeDir.getAbsolutePath());
     ProjectUtils.copyArchetypeToTrunk(archetypeDir.getAbsolutePath(), workingDirectory);
     boolean deleteResult = FileUtils.deleteQuietly(archetypeDir);
     if (!deleteResult) {
       log.warn("Error while deleting the archetype directory");
     }
   }
 }
 /**
  * Deletes an Identity Provider from the logged-in tenant
  *
  * @param idPName Name of the IdP to be deleted
  * @throws IdentityProviderManagementException Error when deleting Identity Provider
  */
 public void deleteIdP(String idPName) throws IdentityProviderManagementException {
   try {
     String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
     IdentityProviderManager.getInstance().deleteIdP(idPName, tenantDomain);
   } catch (IdentityProviderManagementException idpException) {
     log.error("Error while deleting IdP with name " + idPName, idpException);
     throw idpException;
   }
 }
 public String getUploadedApplicationTmpPath() {
   String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
   return CarbonUtils.getCarbonRepository()
       + File.separator
       + "jaggeryapps/appmgt/"
       + AppFactoryConstants.UPLOADED_APPLICATION_TMP_FOLDER_NAME
       + File.separator
       + tenantDomain;
 }
  @Override
  public void initialize(List<Parameter> parameterList) throws WorkflowImplException {

    if (!validateParams(parameterList)) {
      throw new WorkflowRuntimeException(
          "Workflow initialization failed, required parameter is missing");
    }

    Parameter wfNameParameter =
        WorkflowManagementUtil.getParameter(
            parameterList,
            WFConstant.ParameterName.WORKFLOW_NAME,
            WFConstant.ParameterHolder.WORKFLOW_IMPL);

    if (wfNameParameter != null) {
      processName = StringUtils.deleteWhitespace(wfNameParameter.getParamValue());
      role =
          WorkflowManagementUtil.createWorkflowRoleName(
              StringUtils.deleteWhitespace(wfNameParameter.getParamValue()));
    }

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
      tenantContext = "t/" + tenantDomain + "/";
    }

    Parameter bpsProfileParameter =
        WorkflowManagementUtil.getParameter(
            parameterList,
            WFImplConstant.ParameterName.BPS_PROFILE,
            WFConstant.ParameterHolder.WORKFLOW_IMPL);
    if (bpsProfileParameter != null) {
      String bpsProfileName = bpsProfileParameter.getParamValue();
      bpsProfile =
          WorkflowImplServiceDataHolder.getInstance()
              .getWorkflowImplService()
              .getBPSProfile(bpsProfileName, tenantId);
    }
    htName = processName + BPELDeployer.Constants.HT_SUFFIX;

    generateAndDeployArtifacts();
  }
示例#17
0
 public StatusHolder(String type, String key, String version, String target, String targetAction) {
   this.type = type;
   this.key = key;
   this.version = version;
   this.target = target;
   this.targetAction = targetAction;
   this.user = CarbonContext.getCurrentContext().getUsername();
   this.success = true;
   this.timeInstance = Long.toString(System.currentTimeMillis());
 }
  /** Do invalidate all policy cache */
  public void invalidateCache() {

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (log.isDebugEnabled()) {
      log.debug("Trigger invalidateCache to tenant :  " + tenantId + " and all policy ");
    }

    IdentityCacheKey cacheKey = new IdentityCacheKey(tenantId, "");
    addToCache(cacheKey, new PolicyStatus());
  }
  /**
   * Check whether the user exist.
   *
   * @param username Username of the user.
   * @return True if exist.
   * @throws Exception
   */
  public boolean isUserExist(String username) throws Exception {

    try {
      return CarbonContext.getThreadLocalCarbonContext()
          .getUserRealm()
          .getUserStoreManager()
          .isExistingUser(username);
    } catch (UserStoreException e) {
      throw new Exception("User registration exception", e);
    }
  }
 /**
  * Updated resident Identity provider for the logged-in tenant
  *
  * @param identityProvider <code>IdentityProvider</code>
  * @throws IdentityProviderManagementException Error when getting Resident Identity Provider
  */
 public void updateResidentIdP(IdentityProvider identityProvider)
     throws IdentityProviderManagementException {
   String tenantDomain = "";
   try {
     tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
     IdentityProviderManager.getInstance().updateResidentIdP(identityProvider, tenantDomain);
   } catch (IdentityProviderManagementException idpException) {
     log.error("Error while updating ResidentIdP in tenantDomain : " + tenantDomain, idpException);
     throw idpException;
   }
 }
  private boolean authorize(SecurityContext securityContext, Method targetMethod) throws Exception {
    // first we try to see whether this is a super.tenant only operation
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    if (superTenantServiceSet.contains(targetMethod.getName())
        && !isCurrentUserSuperTenant(tenantDomain, tenantId)) {
      return false;
    }
    // authorize using permissionString given as annotation in the service class
    String userName = securityContext.getUserPrincipal().getName();
    String permissionString = authorizationActionMap.get(targetMethod.getName());

    // get the authorization manager for this tenant..
    UserRealm userRealm = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

    boolean isAuthorized =
        isAuthorized(authorizationManager, userName, permissionString, ACTION_ON_RESOURCE);
    return isAuthorized;
  }
  /**
   * Check if an operation is engaged with a workflow or not.
   *
   * @param eventType
   * @return
   * @throws InternalWorkflowException
   */
  @Override
  public boolean eventEngagedWithWorkflows(String eventType) throws InternalWorkflowException {

    List<WorkflowAssociation> associations =
        workflowDAO.getWorkflowAssociationsForRequest(
            eventType, CarbonContext.getThreadLocalCarbonContext().getTenantId());
    if (associations.size() > 0) {
      return true;
    } else {
      return false;
    }
  }
 /**
  * Retrieves resident Identity provider for the logged-in tenant
  *
  * @return <code>IdentityProvider</code>
  * @throws IdentityProviderManagementException Error when getting Resident Identity Provider
  */
 public IdentityProvider getResidentIdP() throws IdentityProviderManagementException {
   String tenantDomain = "";
   try {
     tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
     IdentityProvider residentIdP =
         IdentityProviderManager.getInstance().getResidentIdP(tenantDomain);
     return residentIdP;
   } catch (IdentityProviderManagementException idpException) {
     log.error("Error while getting ResidentIdP in tenantDomain :" + tenantDomain, idpException);
     throw idpException;
   }
 }
  /**
   * Returns the fully qualified username of a particular database user. For an ordinary tenant, the
   * tenant domain will be appended to the username together with an underscore and the given
   * username will be returned as it is in the case of super tenant.
   *
   * @param username Username of the database user.
   * @return Fully qualified username of the database user.
   */
  public static String getFullyQualifiedUsername(String username) {
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {

      /* The maximum number of characters allowed for the username in mysql system tables is
       * 16. Thus, to adhere the aforementioned constraint as well as to give the username
       * an unique identification based on the tenant domain, we append a hash value that is
       * created based on the tenant domain */
      return username + "_" + RSSManagerHelper.getDatabaseUserPostfix();
    }
    return username;
  }
  private static LoadBalancingDataPublisher getDataPublisher()
      throws AgentException, MalformedURLException, AuthenticationException, TransportException {

    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();

    // Get LoadBalancingDataPublisher which has been registered for the tenant.
    LoadBalancingDataPublisher loadBalancingDataPublisher =
        UsageComponent.getDataPublisher(tenantDomain);

    // If a LoadBalancingDataPublisher had not been registered for the tenant.
    if (loadBalancingDataPublisher == null) {

      List<String> receiverGroups =
          org.wso2.carbon.databridge.agent.thrift.util.DataPublisherUtil.getReceiverGroups(
              DataPublisherUtil.getApiManagerAnalyticsConfiguration().getBamServerUrlGroups());

      String serverUser =
          DataPublisherUtil.getApiManagerAnalyticsConfiguration().getBamServerUser();
      String serverPassword =
          DataPublisherUtil.getApiManagerAnalyticsConfiguration().getBamServerPassword();
      List<ReceiverGroup> allReceiverGroups = new ArrayList<ReceiverGroup>();

      for (String receiverGroupString : receiverGroups) {
        String[] serverURLs = receiverGroupString.split(",");
        List<DataPublisherHolder> dataPublisherHolders = new ArrayList<DataPublisherHolder>();

        for (int i = 0; i < serverURLs.length; i++) {
          String serverURL = serverURLs[i];
          DataPublisherHolder dataPublisherHolder =
              new DataPublisherHolder(null, serverURL, serverUser, serverPassword);
          dataPublisherHolders.add(dataPublisherHolder);
        }

        ReceiverGroup receiverGroup = new ReceiverGroup((ArrayList) dataPublisherHolders);
        allReceiverGroups.add(receiverGroup);
      }

      // Create new LoadBalancingDataPublisher for the tenant.
      loadBalancingDataPublisher = new LoadBalancingDataPublisher((ArrayList) allReceiverGroups);
      try {
        // Add created LoadBalancingDataPublisher.
        UsageComponent.addDataPublisher(tenantDomain, loadBalancingDataPublisher);
      } catch (DataPublisherAlreadyExistsException e) {
        log.warn(
            "Attempting to register a data publisher for the tenant "
                + tenantDomain
                + " when one already exists. Returning existing data publisher");
        return UsageComponent.getDataPublisher(tenantDomain);
      }
    }

    return loadBalancingDataPublisher;
  }
  /**
   * update BPS profile for given data
   *
   * @param bpsProfileDTO
   * @throws WorkflowImplException
   */
  public void updateBPSProfile(BPSProfile bpsProfileDTO) throws WorkflowImplException {

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
      WorkflowImplServiceDataHolder.getInstance()
          .getWorkflowImplService()
          .updateBPSProfile(bpsProfileDTO, tenantId);
    } catch (WorkflowImplException e) {
      log.error("Server error when updating the BPS profile", e);
      throw new WorkflowImplException("Server error occurred when updating the BPS profile");
    }
  }
 /**
  * @param keyStoreName
  * @return
  * @throws IdentityException
  */
 private String[] getStoreEntries(String keyStoreName) throws IdentityException {
   KeyStoreAdmin admin;
   try {
     admin =
         new KeyStoreAdmin(
             CarbonContext.getCurrentContext().getTenantId(), getGovernanceRegistry());
     return admin.getStoreEntries(keyStoreName);
   } catch (SecurityConfigException e) {
     log.error("Error reading entries from the key store : " + keyStoreName);
     throw new IdentityException("Error reading entries from the keystore" + e);
   }
 }
 private TaskInfo createDataPurgingTask(String table, String cronString, int retentionPeriod) {
   String taskName = getDataPurgingTaskName(table);
   TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(cronString);
   Map<String, String> taskProperties = new HashMap<>(4);
   taskProperties.put(Constants.RETENTION_PERIOD, String.valueOf(retentionPeriod));
   taskProperties.put(Constants.TABLE, table);
   taskProperties.put(
       Constants.TENANT_ID,
       String.valueOf(CarbonContext.getThreadLocalCarbonContext().getTenantId()));
   taskProperties.put(Constants.CRON_STRING, cronString);
   return new TaskInfo(
       taskName, AnalyticsDataPurgingTask.class.getName(), taskProperties, triggerInfo);
 }
 /**
  * Updates a given Identity Provider's information in the logged-in tenant
  *
  * @param oldIdPName existing Identity Provider name
  * @param identityProvider <code>IdentityProvider</code> new Identity Provider information
  * @throws IdentityProviderManagementException Error when updating Identity Provider
  */
 public void updateIdP(String oldIdPName, IdentityProvider identityProvider)
     throws IdentityProviderManagementException {
   try {
     String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
     // todo:need to properly implement removeOriginalPasswords method to uncomment
     // removeRandomPasswords
     // removeRandomPasswords(identityProvider);
     IdentityProviderManager.getInstance().updateIdP(oldIdPName, identityProvider, tenantDomain);
   } catch (IdentityProviderManagementException idpException) {
     log.error("Error while updating IdP with name " + oldIdPName, idpException);
     throw idpException;
   }
 }
  /** @param timeout */
  public PolicyCache(int timeout) {
    super(PDPConstants.ENTITLEMENT_POLICY_INVALIDATION_CACHE, timeout);
    PolicyCacheUpdateListener policyCacheUpdateListener = new PolicyCacheUpdateListener();
    PolicyCacheCreatedListener policyCacheCreatedListener = new PolicyCacheCreatedListener();
    setCacheEntryUpdatedListener(policyCacheUpdateListener);
    setCacheEntryCreatedListener(policyCacheCreatedListener);
    initCacheBuilder();

    if (log.isDebugEnabled()) {
      int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
      log.debug("PolicyCache initializing for tenant " + tenantId);
    }
  }