Return the most specific matching rule for the given request.

@param surt
@param captureDate
@param retrievalDate
@param who
group
@return
776064
public Rule getMatchingRule(String surt, Date captureDate,
            Date retrievalDate, String who) {

        NewSurtTokenizer tok = new NewSurtTokenizer(surt);
        
        // Best general rule (when accessGroup is blank)
        Rule ruleGeneral = null;

        for (String key: tok.getSearchList()) {
            Iterable<Rule> rules = rulemap.get(key); 
            if (rules != null) {
                for (Rule rule : rules) {
                    if (rule.matches(surt, captureDate, retrievalDate, who)) {
                    	// Return this if accessGroup (who) matches exactly
                    	if ((who != null) && who.equals(rule.getWho())) {
                    		return rule;
                    	// otherwise, store the first/best one
                    	} else if (ruleGeneral == null) {
                    		ruleGeneral = rule;
                    	}
                    }
                }
            }
        }
        
        return ruleGeneral;
    }
631828
@Programmatic
    public DocumentTemplate findByTypeAndAtPathAndDate(final DocumentType documentType, final String atPath, final LocalDate date) {
        return repositoryService.firstMatch(
                new QueryDefault<>(DocumentTemplate.class,
                        "findByTypeAndAtPathAndDate",
                        "type", documentType,
                        "atPath", atPath,
                        "date", date));
    }
993346
public Map<String, Object> retrieve(String entityName, String groupId, String entityId) throws MnoException {
		return retrieve(entityName, groupId, entityId, getAuthenticatedClient());
	}
466703
public Query queryUsersForGroup(String groupId) {
        Query q = queryEntitiesRequest(HttpMethod.GET, null, null, organizationId,
                applicationId, "groups", groupId, "users");
        return q;
    }
838650
public Group lookupGroup(String url) throws FlickrException {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("method", METHOD_LOOKUP_GROUP);

        parameters.put("url", url);

        Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);
        if (response.isError()) {
            throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
        }

        Group group = new Group();
        Element payload = response.getPayload();
        Element groupnameElement = (Element) payload.getElementsByTagName("groupname").item(0);
        group.setId(payload.getAttribute("id"));
        group.setName(((Text) groupnameElement.getFirstChild()).getData());
        return group;
    }
1195079
@Override
	public List<CommerceWishList> findByU_LtC(long userId, Date createDate) {
		return findByU_LtC(userId, createDate, QueryUtil.ALL_POS,
			QueryUtil.ALL_POS, null);
	}
1357023
public Collection<WsGetGroupsResult> getGroupsForSubjectId(final String subjectId) {
        try {
            val groupsClient = new GcGetGroups().addSubjectId(subjectId);
            val results = groupsClient.execute().getResults();
            if (results == null || results.length == 0) {
                LOGGER.warn("Subject id [{}] could not be located.", subjectId);
                return new ArrayList<>(0);
            }
            LOGGER.debug("Found [{}] groups for [{}]", results.length, subjectId);
            return CollectionUtils.wrapList(results);
        } catch (final Exception e) {
            LOGGER.warn("Grouper WS did not respond successfully. Ensure your credentials are correct "
                + ", the url endpoint for Grouper WS is correctly configured and the subject [{}] exists in Grouper.", subjectId, e);
        }
        return new ArrayList<>(0);
    }
1064572
@VisibleForTesting
  @Nullable
  static String tryExtractMostProbableDataSource(String segmentId)
  {
    Matcher dateTimeMatcher = DateTimes.COMMON_DATE_TIME_PATTERN.matcher(segmentId);
    while (true) {
      if (!dateTimeMatcher.find()) {
        return null;
      }
      int dataSourceEnd = dateTimeMatcher.start() - 1;
      if (segmentId.charAt(dataSourceEnd) != DELIMITER) {
        continue;
      }
      return segmentId.substring(0, dataSourceEnd);
    }
  }
824189
public String findTextByQueryReplyAndQueryField(QueryReply queryReply, QueryField queryField) {
    EntityManager entityManager = getEntityManager();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = criteriaBuilder.createQuery(String.class);
    Root<QueryQuestionOptionAnswer> root = criteria.from(QueryQuestionOptionAnswer.class);
    Join<QueryQuestionOptionAnswer, QueryOptionFieldOption> option = root.join(QueryQuestionOptionAnswer_.option);
    
    criteria.select(option.get(QueryOptionFieldOption_.text));
    
    criteria.where(
      criteriaBuilder.and(
        criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryField), queryField),
        criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryReply), queryReply)
      )
    );
    
    return getSingleResult(entityManager.createQuery(criteria));
  }
795937
@Override
    public Iterator findEntitiesForGroup(IEntityGroup group) throws GroupsException {

        if (isTreeRefreshRequired()) {
            refreshTree();
        }

        log.debug("Invoking findEntitiesForGroup() for group:  {}", group.getLocalKey());

        // We only deal w/ group-group relationships here...
        // return findMemberGroups(group);

        List<IEntity> rslt = new ArrayList<IEntity>();
        if (displayPersonMembers) {
            List<String> list = groupsTree.getPersonChildren().get(group.getLocalKey());
            if (list != null) {
                // should only reach this code if its a SmartLdap managed group...
                for (String s : list) {
                    rslt.add(persons.get(s));
                }
            }
        }
        return rslt.iterator();
    }
390846
public static void match(DatabaseClient client) throws IOException {
    // create a manager for document search criteria
    QueryManager queryMgr = client.newQueryManager();

    // specify the search criteria for the documents
    String criteria = "neighborhoods";
    StringQueryDefinition querydef = queryMgr.newStringDefinition();
    querydef.setCriteria(criteria);

    // create a manager for matching rules
    RuleManager ruleMgr = client.newRuleManager();

    // match the rules against the documents qualified by the criteria
    RuleDefinitionList matchedRules = ruleMgr.match(querydef, new RuleDefinitionList());

    // iterate over the matched rules
    Iterator<RuleDefinition> ruleItr = matchedRules.iterator();
    while (ruleItr.hasNext()) {
      RuleDefinition rule = ruleItr.next();
      System.out.println(
        "document criteria "+criteria+" matched rule "+
          rule.getName()+" with metadata "+rule.getMetadata()
      );
    }
  }
1238287
public PactDslRequestWithPath matchQuery(String parameter, String regex) {
        return matchQuery(parameter, regex, new Generex(regex).random());
    }
1230183
public OvhResiliationTerms serviceName_resiliationTerms_GET(String serviceName, Date resiliationDate) throws IOException {
		String qPath = "/xdsl/{serviceName}/resiliationTerms";
		StringBuilder sb = path(qPath, serviceName);
		query(sb, "resiliationDate", resiliationDate);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhResiliationTerms.class);
	}
1275825
@Override
    public SingleInspectionSpecifier observe(Class<? extends RequestObserver> what) {
        initializeSingleGroup();
        singleGroup.observe(createFilterInstance(what));
        return this;
    }
312939
public int filterObject(CaptureSearchResult o) {
		if(client != null) {
			String url = o.getOriginalUrl();
			Date capDate = o.getCaptureDate();
			try {
				Rule r = client.getRule(url, capDate, new Date(), who);
				if(r != null) {
					String publicComment = r.getPublicComment();
					o.putCustom("ANOTATION", publicComment);
				}
			} catch (RuleOracleUnavailableException e) {
				e.printStackTrace();
				// should not happen: we forcibly disable robots retrievals 
			}
		}
		return FILTER_INCLUDE;
	}
35931
@View(name = "by_surrogate", map = "function(doc) { if(doc.surrogate && doc.principal) { emit(doc.principal, doc.surrogate) } }")
    public List<String> findByPrincipal(final String surrogate) {
        val view = createQuery("by_surrogate").key(surrogate);
        return db.queryView(view, String.class);
    }
404913
public QueryRule createShouldQueryRule(String multiOntologyTermIri) {
    QueryRule shouldQueryRule = new QueryRule(new ArrayList<>());
    shouldQueryRule.setOperator(Operator.SHOULD);
    for (String ontologyTermIri : multiOntologyTermIri.split(COMMA_CHAR)) {
      OntologyTerm ontologyTerm = ontologyService.getOntologyTerm(ontologyTermIri);
      List<String> queryTerms = parseOntologyTermQueries(ontologyTerm);
      Double termFrequency = getBestInverseDocumentFrequency(queryTerms);
      shouldQueryRule
          .getNestedRules()
          .add(createBoostedDisMaxQueryRuleForTerms(queryTerms, termFrequency));
    }
    return shouldQueryRule;
  }