public Object getContentObjectFromCache(
      String contentObjectId, CacheRegion cacheRegion, String cacheKey) throws Exception {
    if (!enabled) {
      logger.debug("Query Cache is not Enabled");
      return null;
    }

    try {
      if (StringUtils.isBlank(contentObjectId)) {
        logger.debug(
            "Provided contentObject id is empty or null. Query cache will not be searched.");
        return null;
      }

      if (CacheRegion.NONE == cacheRegion) {
        logger.debug("Provided cache region is NONE. Query cache will not be searched.");
        return null;
      }

      if (cacheKey == null) {
        cacheKey = contentObjectId;
      }

      Fqn<String> contentObjectIdFQN = constructJcrQueryFQN(contentObjectId, cacheRegion);

      Node rootNode = cmsRepositoryCache.getCache().getRoot();

      if (!rootNode.hasChild(contentObjectIdFQN)) {
        logger.debug(
            "The following cache node for content object id does not exist in Query Cache and no results can be retrieved through cache: {}",
            contentObjectIdFQN);
        return null;
      }

      Object cachedItem = rootNode.getChild(contentObjectIdFQN).get(cacheKey);

      if (logger.isDebugEnabled()) {
        if (cachedItem == null) {
          logger.debug(
              "The following cache node for content onbject id does not exist in Query Cache {} under the key {} ",
              contentObjectIdFQN,
              cacheKey);
        } else {
          logger.debug(
              "The following cache node for content onbject id exists in Query Cache {} under the key {} and will be returned",
              contentObjectIdFQN,
              cacheKey);
        }
      }

      return cachedItem;
    } catch (Exception e) {
      if (propagateExceptions) throw e;
      else {
        logger.error("Exception in cache ", e);
        return null;
      }
    }
  }
  /**
   * Tests proper handling of region initialization and destruction.
   *
   * @throws Exception
   */
  public void testActivationDeactivation() throws Exception {

    // Set up a cache to monitor affects of starting the region
    Cache remoteCache =
        DefaultCacheFactory.getInstance()
            .createCache(SharedCacheInstanceManager.DEFAULT_CACHE_RESOURCE, false);

    // This test assumes replication; verify that's correct
    assertEquals(
        "Cache is REPL_SYNC", "REPL_SYNC", remoteCache.getConfiguration().getCacheModeString());

    JChannelFactory channelFactory = new JChannelFactory();
    channelFactory.setMultiplexerConfig(SharedCacheInstanceManager.DEF_JGROUPS_RESOURCE);
    remoteCache.getConfiguration().getRuntimeConfig().setMuxChannelFactory(channelFactory);
    remoteCache.start();

    // Make sure we stop the remoteCache
    registerCache(remoteCache);

    Fqn regionFqn = getRegionFqn("test/test", "test");

    assertNull("No region node", remoteCache.getRoot().getChild(regionFqn));

    Configuration cfg =
        CacheTestUtil.buildConfiguration("test", SharedJBossCacheRegionFactory.class, true, true);
    JBossCacheRegionFactory regionFactory =
        CacheTestUtil.startRegionFactory(cfg, getCacheTestSupport());

    Region region =
        createRegion(regionFactory, "test/test", cfg.getProperties(), getCacheDataDescription());

    Cache localCache = getJBossCache(regionFactory);

    // This test assumes replication; verify that's correct
    assertEquals(
        "Cache is REPL_SYNC", "REPL_SYNC", localCache.getConfiguration().getCacheModeString());

    // Region creation should not have affected remoteCache

    assertNull("No region node", remoteCache.getRoot().getChild(regionFqn));
    Node regionRoot = localCache.getRoot().getChild(regionFqn);
    assertTrue("Has a node at " + regionFqn, regionRoot != null);
    assertTrue(regionFqn + " is resident", regionRoot.isResident());

    // Confirm region destroy does not affect remote cache

    Option option = new Option();
    option.setCacheModeLocal(true);
    remoteCache.getInvocationContext().setOptionOverrides(option);
    remoteCache.put(regionFqn, "test", "test");

    assertEquals("Put succeeded", "test", remoteCache.get(regionFqn, "test"));
    assertNull("Put was local", localCache.get(regionFqn, "test"));

    region.destroy();

    assertEquals("Remote cache unchanged", "test", remoteCache.get(regionFqn, "test"));
    assertNull("No region node", localCache.getRoot().getChild(regionFqn));
  }
Esempio n. 3
0
  public static void putPocessTiming(
      String projectId, String userId, String domainId, ParamType paramType) {
    // get cache
    try {
      Cache cache = CacheUtil.getCache();
      Node rootNode = cache.getRoot();
      String roleTree = domainId + "/" + projectId + "/" + userId + "/" + PM_ENABLE_PROCESS_TIMING;
      rootNode.put(roleTree, paramType.getValue());

    } catch (MalformedObjectNameException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      e.printStackTrace();
    }
  }
 /**
  * Retrieves a set containing sbb entity ids in the factory cache data
  *
  * @return
  */
 public Set<SbbEntityID> getSbbEntities() {
   final Node node = getNode();
   if (node == null) {
     return Collections.emptySet();
   }
   HashSet<SbbEntityID> result = new HashSet<SbbEntityID>();
   ServiceID serviceID = null;
   for (Object obj : node.getChildrenNames()) {
     serviceID = (ServiceID) obj;
     for (SbbEntityID sbbEntityID : getRootSbbEntityIDs(serviceID)) {
       result.add(sbbEntityID);
       collectSbbEntities(sbbEntityID, result);
     }
   }
   return result;
 }
Esempio n. 5
0
  public static String clearPocessTiming(String projectId, String userId, String domainId) {
    String processTimingPMFlag = "NONE";
    // get cache
    try {

      Node rootNode = CacheUtil.getCache().getRoot();
      processTimingPMFlag =
          (String)
              rootNode.put(
                  domainId + "/" + projectId + "/" + userId + "/" + PM_ENABLE_PROCESS_TIMING, null);
    } catch (MalformedObjectNameException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      e.printStackTrace();
    }
    return processTimingPMFlag;
  }
 public Set<SbbEntityID> getRootSbbEntityIDs(ServiceID serviceID) {
   final Node node = getNode();
   if (node == null) {
     return Collections.emptySet();
   }
   final Node serviceNode = node.getChild(serviceID);
   if (serviceNode == null) {
     return Collections.emptySet();
   }
   HashSet<SbbEntityID> result = new HashSet<SbbEntityID>();
   RootSbbEntityID rootSbbEntityID = null;
   for (Object obj : serviceNode.getChildrenNames()) {
     rootSbbEntityID = new RootSbbEntityID(serviceID, (String) obj);
     result.add(rootSbbEntityID);
   }
   return result;
 }
  public void removeCacheEntriesForAuthenticationToken(String authenticationToken)
      throws Exception {
    if (enabled) {
      try {

        if (StringUtils.isNotBlank(authenticationToken)) {
          logger.debug(
              "All query results for authentication token {} will be removed", authenticationToken);

          Cache cache = cmsRepositoryCache.getCache();

          Node rootNode = cache.getRoot();

          if (rootNode.hasChild(JCR_QUERY_NODE_FQN)) {

            // Get all regions under this node. For each region search
            // for node named after authentication token and remove it
            Set<Node> cacheRegions = rootNode.getChild(JCR_QUERY_NODE_FQN).getChildren();

            if (CollectionUtils.isNotEmpty(cacheRegions)) {

              for (Iterator<Node> iter = cacheRegions.iterator(); iter.hasNext(); ) {
                Node cacheRegion = iter.next();

                if (cacheRegion.hasChild(authenticationToken)) {

                  if (logger.isDebugEnabled()) {
                    logger.debug(
                        "Removing results cached under node {}",
                        cacheRegion.getChild(authenticationToken).getFqn());
                  }

                  cacheRegion.removeChild(authenticationToken);
                }
              }
            }
          }
        } else {
          logger.debug("Authentication token is null or empty. Nothing will be removed from cache");
        }
      } catch (Exception e) {
        if (propagateExceptions) throw e;
        else {
          logger.error("Exception in cache ", e);
        }
      }
    }
  }
  /** @see edu.harvard.i2b2.crc.delegate.RequestHandlerDelegate#handleRequest(java.lang.String) */
  public String handleRequest(String requestXml, RequestHandler requestHandler)
      throws I2B2Exception {
    String response = null;
    JAXBUtil jaxbUtil = CRCLoaderJAXBUtil.getJAXBUtil();

    try {
      JAXBElement jaxbElement = jaxbUtil.unMashallFromString(requestXml);
      RequestMessageType requestMessageType = (RequestMessageType) jaxbElement.getValue();
      BodyType bodyType = requestMessageType.getMessageBody();

      if (bodyType == null) {
        log.error("null value in body type");
        throw new I2B2Exception("null value in body type");
      }

      // Call PM cell to validate user
      StatusType procStatus = null;
      ProjectType projectType = null;
      String projectId = null;
      SecurityType securityType = null;
      try {

        if (requestMessageType.getMessageHeader() != null) {
          if (requestMessageType.getMessageHeader().getSecurity() != null) {
            securityType = requestMessageType.getMessageHeader().getSecurity();
          }
          projectId = requestMessageType.getMessageHeader().getProjectId();
        }
        if (securityType == null) {
          procStatus = new StatusType();
          procStatus.setType("ERROR");
          procStatus.setValue("Request message missing user/password");
          response =
              I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
          return response;
        }

        PMServiceDriver pmServiceDriver = new PMServiceDriver();
        projectType = pmServiceDriver.checkValidUser(securityType, projectId);
        if (projectType == null) {
          procStatus = new StatusType();
          procStatus.setType("ERROR");
          procStatus.setValue("Invalid user/password for the given domain");
          response =
              I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
          return response;
        }

        log.debug("project name from PM " + projectType.getName());
        log.debug("project id from PM " + projectType.getId());
        if (projectType.getRole().get(0) != null) {
          log.debug("Project role from PM " + projectType.getRole().get(0));
          this.putRoles(
              projectId,
              securityType.getUsername(),
              securityType.getDomain(),
              projectType.getRole());

          Node rootNode = CacheUtil.getCache().getRoot();
          List<String> roles =
              (List<String>)
                  rootNode.get(
                      securityType.getDomain()
                          + "/"
                          + projectId
                          + "/"
                          + securityType.getUsername());
          if (roles != null) {
            System.out.println("roles size !!1 " + roles.size());
          }

        } else {
          log.warn("project role not set for user [" + securityType.getUsername() + "]");
        }

      } catch (AxisFault e) {
        procStatus = new StatusType();
        procStatus.setType("ERROR");
        procStatus.setValue("Could not connect to server");
        response =
            I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
        return response;
      } catch (I2B2Exception e) {
        procStatus = new StatusType();
        procStatus.setType("ERROR");
        procStatus.setValue("Message error connecting Project Management cell");
        response =
            I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
        return response;
      } catch (JAXBUtilException e) {
        procStatus = new StatusType();
        procStatus.setType("ERROR");
        procStatus.setValue("Message error from Project Management cell");
        response =
            I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, bodyType);
        return response;
      }

      JAXBUnWrapHelper unWrapHelper = new JAXBUnWrapHelper();

      BodyType responseBodyType = null;
      if (requestHandler instanceof PublishDataRequestHandler) {

        String irodsStorageResource = null;
        for (ParamType paramType : projectType.getParam()) {

          if (paramType.getName().equalsIgnoreCase("SRBDefaultStorageResource")) {
            irodsStorageResource = paramType.getValue();
            log.debug("param value for SRBDefaultStorageResource" + paramType.getValue());
          }
        }
        ((PublishDataRequestHandler) requestHandler)
            .setIrodsDefaultStorageResource(irodsStorageResource);
      }

      responseBodyType = requestHandler.execute();

      procStatus = new StatusType();
      procStatus.setType("DONE");
      procStatus.setValue("DONE");

      response =
          I2B2MessageResponseFactory.buildResponseMessage(
              requestXml, procStatus, responseBodyType, true);

    } catch (JAXBUtilException e) {
      log.error("JAXBUtil exception", e);
      StatusType procStatus = new StatusType();
      procStatus.setType("ERROR");
      procStatus.setValue(requestXml + "\n\n" + StackTraceUtil.getStackTrace(e));
      try {
        response = I2B2MessageResponseFactory.buildResponseMessage(null, procStatus, null);
      } catch (JAXBUtilException e1) {
        e1.printStackTrace();
      }
    } catch (I2B2Exception e) {
      log.error("I2B2Exception", e);
      StatusType procStatus = new StatusType();
      procStatus.setType("ERROR");
      procStatus.setValue(StackTraceUtil.getStackTrace(e));
      try {
        response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null);
      } catch (JAXBUtilException e1) {
        e1.printStackTrace();
      }
    } catch (Throwable e) {
      log.error("Throwable", e);
      StatusType procStatus = new StatusType();
      procStatus.setType("ERROR");
      procStatus.setValue(StackTraceUtil.getStackTrace(e));
      try {
        response = I2B2MessageResponseFactory.buildResponseMessage(requestXml, procStatus, null);
      } catch (JAXBUtilException e1) {
        e1.printStackTrace();
      }
    }
    return response;
  }
  public Object getJcrQueryResults(CmsCriteria cmsCriteria, String cacheKeyPrefix)
      throws Exception {

    if (!enabled) {
      logger.debug("Query Cache is not Enabled");
      return null;
    }

    try {
      if (cmsCriteria == null || StringUtils.isBlank(cmsCriteria.getXPathQuery())) {
        logger.debug("Provided JCR Query is empty or null. Query cache will not be searched.");
        return null;
      }

      if (!cmsCriteria.isCacheable()) {
        logger.debug(
            "Jcr query {} is not cacheable. Query cache will not be searched",
            cmsCriteria.getXPathQuery());
        return null;
      }

      String jcrQuery = cmsCriteria.getXPathQuery();

      String cacheKey =
          constructCacheKey(
              cacheKeyPrefix,
              cmsCriteria.getOffset(),
              cmsCriteria.getLimit(),
              cmsCriteria.getRenderProperties());

      Fqn jcrQueryFQN = constructJcrQueryFQN(jcrQuery, cmsCriteria.getCacheRegion());

      Node rootNode = cmsRepositoryCache.getCache().getRoot();

      if (!rootNode.hasChild(jcrQueryFQN)) {
        logger.debug(
            "The following jcr query node does not exist in Query Cache and no results can be retrieved through cache: {}",
            jcrQueryFQN);
        return null;
      }

      Object cachedItem = rootNode.getChild(jcrQueryFQN).get(cacheKey);

      if (cachedItem == null) {
        logger.debug(
            "The following jcr query node exists in Query Cache but no results for the given row range and render properties exist in cache. JcrQueryNode = {} ,Cache Key = {}",
            jcrQueryFQN,
            cacheKey);
      } else {
        logger.debug(
            "The following jcr query node exists in Query Cache and results for the given row range and render properties also exist in cache and will be returned. JcrQueryNode = {} ,Cache Key = {}",
            jcrQueryFQN,
            cacheKey);
      }

      return cachedItem;
    } catch (Exception e) {
      if (propagateExceptions) throw e;
      else {
        logger.error("Exception in cache ", e);
        return null;
      }
    }
  }
  public void cacheContentObject(
      String contentObjectId, Object contentObject, CacheRegion cacheRegion, String cacheKey)
      throws Exception {
    try {

      if (enabled
          && StringUtils.isNotBlank(contentObjectId)
          && contentObject != null
          && CacheRegion.NONE != cacheRegion) {

        Cache cache = cmsRepositoryCache.getCache();

        Node rootNode = cache.getRoot();

        if (cacheKey == null) {
          cacheKey = contentObjectId;
        }

        Fqn<String> contentObjectIdFQN = constructJcrQueryFQN(contentObjectId, cacheRegion);

        if (!rootNode.hasChild(contentObjectIdFQN)) {

          logger.debug(
              "The following content object cache node does not exist and will be added in Query Cache. The content object cache node to be cached is {} under key {}",
              contentObjectIdFQN,
              cacheKey);

          // Put query results to cache
          cache.put(contentObjectIdFQN, cacheKey, contentObject);

        } else {
          // Content Object already exists
          Node contentOjectCacheNode = rootNode.getChild(contentObjectIdFQN);

          // Write results only if there is no matching rowRangeAndRenderProperties query
          if (contentOjectCacheNode.get(cacheKey) == null) {

            if (contentObject != null) {
              logger.debug(
                  "The following content object cache node exists in Query Cache. The existing Jcr Query node is {} . The key is {} and content object is not null. So a map entry with this key and the content object will be created",
                  contentObjectIdFQN,
                  cacheKey);

              contentOjectCacheNode.put(cacheKey, contentObject);
            } else {
              // Remove Content Object Cache Node
              // cache.remove(jcrQueryFQN);
              logger.debug(
                  "The following content object cache node exists in Query Cache. The existing Jcr Query node is {}.The key is {}.The content objec IS NULL. So NO map entry with this key and the content object will be created",
                  contentObjectIdFQN,
                  cacheKey);
            }
          } else {
            logger.debug(
                "The following content object cache node exists in Query Cache. The existing Jcr Query node is {}. The key is {}. So NO map entry with this key and the content object need to be created",
                contentObjectIdFQN,
                cacheKey);
          }
        }
      }
    } catch (Exception e) {
      if (propagateExceptions) throw e;
      else logger.error("Exception in cache ", e);
    }
  }
  public void cacheJcrQueryResults(
      CmsCriteria cmsCriteria,
      Object outcome,
      RenderProperties renderProperties,
      String cacheKeyPrefix)
      throws Exception {
    // Cache only if a query is provided and outcome is not null
    try {
      String jcrQuery = cmsCriteria.getXPathQuery();

      if (enabled && !StringUtils.isBlank(jcrQuery)) {

        if (!cmsCriteria.isCacheable()) {
          logger.debug("Jcr query {} is not cacheable. Query will not be cached.", jcrQuery);
          return;
        }

        Cache cache = cmsRepositoryCache.getCache();

        Node rootNode = cache.getRoot();

        String cacheKey =
            constructCacheKey(
                cacheKeyPrefix, cmsCriteria.getOffset(), cmsCriteria.getLimit(), renderProperties);

        Fqn<String> jcrQueryFQN = constructJcrQueryFQN(jcrQuery, cmsCriteria.getCacheRegion());

        if (!rootNode.hasChild(jcrQueryFQN)) {
          if (outcome != null) {
            logger.debug(
                "The following jcr query node does not exist and will be added in Query Cache along with the row range and render properties key (not null query results). The Jcr Query node to be cached is {} and the cache key is ",
                jcrQueryFQN,
                cacheKey);

            // Put query results to cache
            cache.put(jcrQueryFQN, cacheKey, outcome);

          } else {
            logger.debug(
                "The following jcr query node does not exist in Query Cache but WILL NOT CACHED because query result is null. The Jcr Query node is {} and the cache key is {}",
                jcrQueryFQN,
                cacheKey);
          }
        } else {
          // JcrQuery already exists
          Node jcrQueryNode = rootNode.getChild(jcrQueryFQN);

          // Write results only if there is no matching rowRangeAndRenderProperties query
          if (jcrQueryNode.get(cacheKey) == null) {

            if (outcome != null) {
              logger.debug(
                  "The following jcr query node exists in Query Cache. The existing Jcr Query node is {}. The row range and properties key does not exist in cache. The key is {}. The query outcome is not null. So a map entry with this key and the query results will be created",
                  jcrQueryFQN,
                  cacheKey);
              jcrQueryNode.put(cacheKey, outcome);
            } else {
              // Remove jcrQueryFqn
              // cache.remove(jcrQueryFQN);
              logger.debug(
                  "The following jcr query node exists in Query Cache. The existing Jcr Query node is {}. The row range and properties key does not exist in cache. The key is {} . The query outcome IS NULL. So NO map entry with this key and the query results will be created",
                  jcrQueryFQN,
                  cacheKey);
            }
          } else {
            logger.debug(
                "The following jcr query node exists in Query Cache. The existing Jcr Query node is {}. The cache key {} does also exist in cache. So NO map entry with this key and the query results need to be created",
                jcrQueryFQN,
                cacheKey);
          }
        }
      }
    } catch (Exception e) {
      if (propagateExceptions) throw e;
      else logger.error("Exception in cache ", e);
    }
  }