/**
  * Remove a single domain ID from all session domain ID caches
  *
  * @param domainId
  */
 private void removeDomainFromIDCache(String domainId) {
   try {
     Set<?> cachedObjects = cacheManager.getAllKeysFromRegionCache(CACHE_REGION);
     if (cachedObjects != null) {
       for (Object k : cachedObjects) {
         if (k instanceof String) {
           String key = (String) k;
           if (key != null && key.startsWith(DOMAIN_CACHE_KEY_PREDICATE)) {
             Set<String> domainIds =
                 (Set<String>) cacheManager.getFromRegionCache(CACHE_REGION, key);
             domainIds.remove(domainId);
             cacheManager.putInRegionCache(CACHE_REGION, key, domainIds);
           }
         }
       }
     }
   } catch (Throwable e) {
     // due to a known issue in hibernate cache
     // the getAll* methods of ICacheManager throw a NullPointerException if
     // cache values are null (this can happen due to cache object timeouts)
     // please see: http://opensource.atlassian.com/projects/hibernate/browse/HHH-3248
     if (logger.isDebugEnabled()) {
       logger.debug("", e); // $NON-NLS-1$
     }
   }
 }
  public AbstractJcrBackedRoleBindingDao() {

    cacheManager = PentahoSystem.getCacheManager(null);

    if (!cacheManager.cacheEnabled(LOGICAL_ROLE_BINDINGS_REGION)) {
      cacheManager.addCacheRegion(LOGICAL_ROLE_BINDINGS_REGION);
    }
  }
 /** Clears all caches for all locales. */
 protected void resetCache(IPentahoSession session) {
   final Lock writeLock = cacheLock.writeLock();
   try {
     writeLock.lock();
     final ICacheManager cacheMgr = PentahoSystem.getCacheManager(session);
     cacheMgr.clearRegionCache(CATALOG_CACHE_REGION);
   } finally {
     writeLock.unlock();
   }
 }
  public void shutdown() {

    ICacheManager cacheManager = PentahoSystem.getCacheManager(null);

    Logger.debug(this, "DatasourceSystemListener: Called for shutdown ..."); // $NON-NLS-1$

    cacheManager.removeRegionCache(IDBDatasourceService.JDBC_DATASOURCE);

    Logger.debug(this, "DatasourceSystemListener: Completed shutdown."); // $NON-NLS-1$
  }
  protected ICacheManager addCacheRegions() {
    ICacheManager cacheManager = PentahoSystem.getCacheManager(null);

    Logger.debug(this, "Adding caching regions ..."); // $NON-NLS-1$

    if (!cacheManager.cacheEnabled(IDBDatasourceService.JDBC_DATASOURCE)) {
      cacheManager.addCacheRegion(IDBDatasourceService.JDBC_DATASOURCE);
    }

    return cacheManager;
  }
  @Override
  public Set<String> getDomainIds() {
    final IPentahoSession session = PentahoSessionHolder.getSession();

    final String domainKey = generateDomainIdCacheKeyForSession(session);
    Set<String> domainIds = (Set<String>) cacheManager.getFromRegionCache(CACHE_REGION, domainKey);
    if (domainIds != null) {
      // We've previously cached domainIds available for this session
      return domainIds;
    }
    // Domains are accessible by anyone. What they contain may be different so rely on the lookup to
    // be
    // session-specific.
    domainIds = delegate.getDomainIds();
    cacheManager.putInRegionCache(CACHE_REGION, domainKey, new HashSet<String>(domainIds));
    return domainIds;
  }
 @Override
 public Boolean call(final ICacheManager cacheManager, final CacheKey key) {
   if (logger.isDebugEnabled()) {
     logger.debug("Removing domain from cache: " + key); // $NON-NLS-1$
   }
   cacheManager.removeFromRegionCache(CACHE_REGION, key);
   return true; // continue
 }
  public void setRoleBindings(
      Session session, ITenant tenant, String runtimeRoleName, List<String> logicalRoleNames)
      throws NamespaceException, RepositoryException {
    if (tenant == null) {
      tenant = JcrTenantUtils.getTenant(runtimeRoleName, false);
      runtimeRoleName = getPrincipalName(runtimeRoleName);
    }

    if (!TenantUtils.isAccessibleTenant(tenant)) {
      throw new NotFoundException("Tenant " + tenant.getId() + " not found");
    }

    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    final String phoNsPrefix =
        session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
    final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
    Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
    NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
    int i = 0;
    while (runtimeRoleNodes.hasNext()) {
      runtimeRoleNodes.nextNode();
      i++;
    }
    if (i == 0) {
      // no bindings setup yet; install bootstrap bindings; bootstrapRoleBindings will now no longer
      // be
      // consulted
      for (Map.Entry<String, List<String>> entry : bootstrapRoleBindings.entrySet()) {
        JcrRoleAuthorizationPolicyUtils.internalSetBindings(
            pentahoJcrConstants,
            runtimeRolesFolderNode,
            entry.getKey(),
            entry.getValue(),
            phoNsPrefix);
      }
    }
    if (!isImmutable(runtimeRoleName)) {
      JcrRoleAuthorizationPolicyUtils.internalSetBindings(
          pentahoJcrConstants,
          runtimeRolesFolderNode,
          runtimeRoleName,
          logicalRoleNames,
          phoNsPrefix);
    } else {
      throw new RuntimeException(
          Messages.getInstance()
              .getString(
                  "JcrRoleAuthorizationPolicyRoleBindingDao.ERROR_0001_ATTEMPT_MOD_IMMUTABLE",
                  runtimeRoleName)); //$NON-NLS-1$
    }
    session.save();
    Assert.isTrue(NodeHelper.hasNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName));

    // update cache
    String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
    cacheManager.putInRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId, logicalRoleNames);
  }
  /**
   * Returns a list of catalogs for the current session.
   *
   * <p>The cache is stored in the platform's caches in the region {@link #CATALOG_CACHE_REGION}. It
   * is also segmented by locale, but we only return the correct sub-region according to the session
   * passed as a parameter.
   */
  @SuppressWarnings("unchecked")
  protected synchronized List<IOlapService.Catalog> getCache(IPentahoSession session) {
    // Create the cache region if necessary.
    final ICacheManager cacheMgr = PentahoSystem.getCacheManager(session);
    final Object cacheKey = makeCacheSubRegionKey(getLocale());

    final Lock writeLock = cacheLock.writeLock();
    try {

      writeLock.lock();

      if (!cacheMgr.cacheEnabled(CATALOG_CACHE_REGION)) {
        // Create the region. This requires write access.
        cacheMgr.addCacheRegion(CATALOG_CACHE_REGION);
      }

      if (cacheMgr.getFromRegionCache(CATALOG_CACHE_REGION, cacheKey) == null) {
        // Create the sub-region. This requires write access.
        cacheMgr.putInRegionCache(
            CATALOG_CACHE_REGION, cacheKey, new ArrayList<IOlapService.Catalog>());
      }

      return (List<IOlapService.Catalog>)
          cacheMgr.getFromRegionCache(CATALOG_CACHE_REGION, cacheKey);

    } finally {
      writeLock.unlock();
    }
  }
 @Override
 public Domain getDomain(final String id) {
   final IPentahoSession session = PentahoSessionHolder.getSession();
   final CacheKey key = new CacheKey(session.getId(), id);
   Domain domain = (Domain) cacheManager.getFromRegionCache(CACHE_REGION, key);
   if (domain != null) {
     if (logger.isDebugEnabled()) {
       logger.debug("Found domain in cache: " + key); // $NON-NLS-1$
     }
     return domain;
   }
   domain = delegate.getDomain(id);
   if (domain != null) {
     SecurityHelper helper = new SecurityHelper();
     domain = helper.createSecureDomain(this, domain);
     // cache domain with the key we used to look it up, not whatever new id it might have now
     if (logger.isDebugEnabled()) {
       logger.debug("Caching domain by session: " + key); // $NON-NLS-1$
     }
     cacheManager.putInRegionCache(CACHE_REGION, key, domain);
   }
   return domain;
 }
 /** Wraps the provided domain repository to provide session-based caching of domains. */
 public SessionCachingMetadataDomainRepository(final IMetadataDomainRepository delegate) {
   if (delegate == null) {
     throw new NullPointerException();
   }
   this.delegate = delegate;
   cacheManager = PentahoSystem.getCacheManager(null); // cache manager gets loaded just once...
   if (cacheManager != null) {
     if (!cacheManager.cacheEnabled(CACHE_REGION)) {
       if (!cacheManager.addCacheRegion(CACHE_REGION)) {
         cacheManager = null;
       }
     }
   }
   if (cacheManager == null) {
     throw new IllegalStateException(
         getClass().getSimpleName()
             + " ("
             + CACHE_REGION
             + ") cannot be initialized"); //$NON-NLS-1$ //$NON-NLS-2$
   }
   PentahoSystem.addLogoutListener(
       this); // So you can remove a users' region when their session disappears
 }
 /**
  * Calls the callback for every key in the cache region
  *
  * @param callback {@see CacheCallback}
  */
 protected void forAllKeys(final CacheIteratorCallback callback) {
   try {
     Set<?> cachedObjects = cacheManager.getAllKeysFromRegionCache(CACHE_REGION);
     if (cachedObjects != null) {
       for (Object k : cachedObjects) {
         if (k instanceof CacheKey) {
           CacheKey key = (CacheKey) k;
           if (Boolean.FALSE.equals(callback.call(cacheManager, key))) {
             break;
           }
         }
       }
     }
   } catch (Throwable e) {
     // due to a known issue in hibernate cache
     // the getAll* methods of ICacheManager throw a NullPointerException if
     // cache values are null (this can happen due to cache object timeouts)
     // please see: http://opensource.atlassian.com/projects/hibernate/browse/HHH-3248
     if (logger.isDebugEnabled()) {
       logger.debug("", e); // $NON-NLS-1$
     }
   }
 }
  public boolean startup(final IPentahoSession session) {
    try {

      Logger.debug(this, "DatasourceSystemListener: called for startup ..."); // $NON-NLS-1$

      ICacheManager cacheManager = addCacheRegions();

      List<IDatabaseConnection> databaseConnections = getListOfDatabaseConnections(session);

      String dsName = "";
      DataSource ds = null;

      for (IDatabaseConnection databaseConnection : databaseConnections) {

        if (databaseConnection != null) {

          Logger.debug(this, "  Setting up datasource - " + databaseConnection); // $NON-NLS-1$

          // isPortUsedByServer should NOT be called on a JNDI data source
          // http://jira.pentaho.com/browse/BISERVER-12244
          if (!databaseConnection.getAccessType().equals(DatabaseAccessType.JNDI)) {
            // if connection's port used by server there is no sense to get DataSource for this
            ds =
                isPortUsedByServer(databaseConnection)
                    ? null
                    : setupDataSourceForConnection(databaseConnection);
          } else {
            Logger.debug(
                this,
                "(Datasource \""
                    + IDBDatasourceService.JDBC_DATASOURCE // $NON-NLS-1$
                    + dsName
                    + "\" not cached)"); //$NON-NLS-1$
            continue;
          }

          dsName = databaseConnection.getName();

          cacheManager.putInRegionCache(IDBDatasourceService.JDBC_DATASOURCE, dsName, ds);

          Logger.debug(
              this,
              "(Storing datasource under key \""
                  + IDBDatasourceService.JDBC_DATASOURCE // $NON-NLS-1$
                  + dsName
                  + "\")"); //$NON-NLS-1$
        }
      }

      Logger.debug(this, "DatasourceSystemListener: Completed startup."); // $NON-NLS-1$

      return true;

    } catch (ObjectFactoryException objface) {

      Logger.error(
          this,
          Messages.getInstance()
              .getErrorString("DatasourceSystemListener.ERROR_0001_UNABLE_TO_INSTANTIATE_OBJECT"),
          objface); //$NON-NLS-1$

      return false;

    } catch (DatasourceMgmtServiceException dmse) {

      Logger.error(
          this,
          Messages.getInstance()
              .getErrorString("DatasourceSystemListener.ERROR_0002_UNABLE_TO_GET_DATASOURCE"),
          dmse); //$NON-NLS-1$

      return false;
    }
  }
  @Override
  public List<String> getBoundLogicalRoleNames(
      Session session, ITenant tenant, List<String> runtimeRoleNames)
      throws NamespaceException, RepositoryException {
    if ((tenant == null) || (tenant.getId() == null)) {
      return getBoundLogicalRoleNames(session, runtimeRoleNames);
    }

    if (!TenantUtils.isAccessibleTenant(tenant)) {
      return new ArrayList<String>();
    }

    final List<String> uncachedRuntimeRoleNames = new ArrayList<String>();
    final Set<String> cachedBoundLogicalRoleNames = new HashSet<String>();
    for (String runtimeRoleName : runtimeRoleNames) {
      String roleName = tenantedRoleNameUtils.getPrincipleName(runtimeRoleName);
      String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
      Object fromRegionCache =
          cacheManager.getFromRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId);
      if (fromRegionCache != null) {
        cachedBoundLogicalRoleNames.addAll((Collection<String>) fromRegionCache);
      } else {
        uncachedRuntimeRoleNames.add(roleName);
      }
    }
    if (uncachedRuntimeRoleNames.isEmpty()) {
      // no need to hit the repo
      return new ArrayList<String>(cachedBoundLogicalRoleNames);
    }

    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    final String phoNsPrefix =
        session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
    final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
    HashMultimap<String, String> boundLogicalRoleNames = HashMultimap.create();
    Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
    NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
    if (!runtimeRoleNodes.hasNext()) {
      // no bindings setup yet; fall back on bootstrap bindings
      for (String runtimeRoleName : uncachedRuntimeRoleNames) {
        String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
        if (bootstrapRoleBindings.containsKey(runtimeRoleName)) {
          boundLogicalRoleNames.putAll(roleId, bootstrapRoleBindings.get(runtimeRoleName));
        }
      }
    } else {
      for (String runtimeRoleName : uncachedRuntimeRoleNames) {
        if (NodeHelper.hasNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName)) {
          Node runtimeRoleFolderNode =
              NodeHelper.getNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName);
          if (runtimeRoleFolderNode.hasProperty(pentahoJcrConstants.getPHO_BOUNDROLES())) {
            Value[] values =
                runtimeRoleFolderNode
                    .getProperty(pentahoJcrConstants.getPHO_BOUNDROLES())
                    .getValues();
            String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
            for (Value value : values) {
              boundLogicalRoleNames.put(roleId, value.getString());
            }
          }
        }
      }
    }
    // now add in immutable bound logical role names
    for (String runtimeRoleName : uncachedRuntimeRoleNames) {
      if (immutableRoleBindings.containsKey(runtimeRoleName)) {
        String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
        boundLogicalRoleNames.putAll(roleId, immutableRoleBindingNames.get(runtimeRoleName));
      }
    }

    // update cache
    Map<String, Collection<String>> stringCollectionMap = boundLogicalRoleNames.asMap();
    for (Entry<String, Collection<String>> stringCollectionEntry : stringCollectionMap.entrySet()) {
      cacheManager.putInRegionCache(
          LOGICAL_ROLE_BINDINGS_REGION,
          stringCollectionEntry.getKey(),
          stringCollectionEntry.getValue());
    }

    // now add in those runtime roles that have no bindings to the cache
    for (String runtimeRoleName : uncachedRuntimeRoleNames) {
      String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);

      if (cacheManager.getFromRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId) == null) {
        cacheManager.putInRegionCache(
            LOGICAL_ROLE_BINDINGS_REGION, roleId, Collections.emptyList());
      }
    }

    // combine cached findings plus ones from repo
    Set<String> res = new HashSet<String>();
    res.addAll(cachedBoundLogicalRoleNames);
    res.addAll(boundLogicalRoleNames.values());
    return new ArrayList<String>(res);
  }
 /**
  * Remove domain ID cache for a given session
  *
  * @param session
  */
 protected void clearDomainIdsFromCache(IPentahoSession session) {
   final String key = generateDomainIdCacheKeyForSession(session);
   if (cacheManager.getFromRegionCache(CACHE_REGION, key) != null) {
     cacheManager.removeFromRegionCache(CACHE_REGION, key);
   }
 }