protected long getUpperSampleLimit(SPARQLEndpoint endpoint, Triple triplePattern)
      throws SADIException, IOException {
    String uri = endpoint.getURI();

    log.trace("determining number of triples matching " + triplePattern + " in " + uri);

    ServiceStatus status = ServiceStatus.OK;
    if (getRegistry() != null) {
      status = getRegistry().getServiceStatus(endpoint.getURI());
    }

    // check for a cached value first
    if (upperSampleLimitCache.contains(endpoint, triplePattern)) {
      log.trace("using previously cached value for upper sample limit");
      return upperSampleLimitCache.get(endpoint, triplePattern);
    }

    ElementGroup whereClause = getWhereClauseWithBlankNodeFilter(triplePattern);

    /*
    Node s = triplePattern.getSubject();
    Node o = triplePattern.getObject();

    // Build a Jena representation of the WHERE clause

    ElementGroup whereClause = new ElementGroup();
    whereClause.addTriplePattern(triplePattern);
    if(s.isVariable()) {
    	whereClause.addElementFilter(new ElementFilter(new E_LogicalNot(new E_IsBlank(new ExprVar(s)))));
    }
    if(o.isVariable()) {
    	whereClause.addElementFilter(new ElementFilter(new E_LogicalNot(new E_IsBlank(new ExprVar(o)))));
    }
    */

    if (status != ServiceStatus.SLOW) {
      try {
        // issue a SELECT COUNT(*) query
        Query countStarQuery = new Query();
        countStarQuery.setQuerySelectType();
        countStarQuery.setQueryPattern(whereClause);
        countStarQuery.addResultVar(countStarQuery.allocAggregate(AggCount.get()));

        List<Map<String, String>> results = endpoint.selectQuery(countStarQuery.serialize());

        Map<String, String> firstRow = results.iterator().next();
        String firstColumn = firstRow.keySet().iterator().next();
        long limit = Long.parseLong(firstRow.get(firstColumn));

        upperSampleLimitCache.put(endpoint, triplePattern, limit);
        log.trace(String.format("successful upper limit query: %s", countStarQuery.serialize()));
        log.trace(String.format("upper limit: %d", limit));
        return limit;
      } catch (IOException e) {
        log.warn(
            "failed to COUNT number of triples matching "
                + triplePattern
                + " in "
                + uri
                + ", trying for a lower bound instead.");
      }
    }

    Query selectStarQuery = new Query();
    selectStarQuery.setQuerySelectType();
    selectStarQuery.setQueryPattern(whereClause);
    selectStarQuery.setQueryResultStar(true);

    long limit = endpoint.getResultsCountLowerBound(selectStarQuery.serialize(), 50000);
    upperSampleLimitCache.put(endpoint, triplePattern, limit);

    log.trace(String.format("successful upper limit query: %s", selectStarQuery.serialize()));
    log.trace(String.format("upper limit: %d", limit));

    return limit;
  }