Example #1
0
  /**
   * Creates an excerpt for the given <code>hit</code>.
   *
   * @param hit the current hit.
   * @param excerptPropNames the names of the properties to use for the excerpt.
   * @param maxLength the maximum length of the excerpt.
   * @return the excerpt.
   * @throws RepositoryException if an error occurs while reading from the repository.
   */
  public static Excerpt create(final HitImpl hit, final Set excerptPropNames, final int maxLength)
      throws RepositoryException {
    Node node = hit.getResource().adaptTo(Node.class);
    if (node == null) {
      // use repository built in mechanism
      return new Excerpt(hit.getExcerpts().get("."));
    }
    Node content =
        node.hasNode(JcrConstants.JCR_CONTENT) ? node.getNode(JcrConstants.JCR_CONTENT) : node;
    if (content.isNodeType(JcrConstants.NT_RESOURCE)) {
      // use repository built in mechanism
      return new Excerpt(hit.getExcerpts().get("."));
    }

    final List<Excerpt> excerpt = new ArrayList<Excerpt>();
    final int prefixLength = node.getPath().length() + 1;
    // build excerpt built on a given set of property names
    try {
      content.accept(
          new TraversingItemVisitor.Default(true) {
            protected void entering(Property property, int level) throws RepositoryException {

              if (!excerptPropNames.contains(property.getName())) {
                // ignore
                return;
              }
              String relPath = property.getPath().substring(prefixLength);
              Excerpt e = createExcerpt(property, relPath, hit.getRow(), maxLength);
              if (e == null) {
                return;
              }
              if (e.hasHighlights) {
                excerpt.clear();
                excerpt.add(e);
                throw new RepositoryException();
              } else if (excerpt.size() == 0) {
                excerpt.add(e);
              }
            }
          });
    } catch (RepositoryException e) {
      if (excerpt.size() == 0) {
        throw e;
      }
      // otherwise the exception was thrown to
      // terminate the traversal
    }
    if (excerpt.size() == 0) {
      // no suitable excerpt found
      return new Excerpt("");
    } else {
      return excerpt.get(0);
    }
  }