public Query build(final QueryNode queryNode)
throws QueryNodeException {
final TwigQueryNode tqn = (TwigQueryNode) queryNode;
final QueryNode root = tqn.getRoot();
final QueryNode child = tqn.getChild();
final TwigQuery twigQuery;
final int rootLevel = tqn.getRootLevel();
if (root == null && child == null) {
throw new QueryNodeException(new MessageImpl(QueryParserMessages.EMPTY_MESSAGE));
}
if (tqn.getChildren().size() != 2) {
throw new IllegalArgumentException("A TwigQueryNode cannot have more " +
"than 2 children:\n" + tqn.getChildren().toString());
}
if (child instanceof WildcardNodeQueryNode &&
root instanceof WildcardNodeQueryNode) {
throw new QueryNodeException(new MessageImpl("Twig with both root and " +
"child empty is not allowed."));
}
// Build the root operand
if (root instanceof WildcardNodeQueryNode) { // Empty root query
twigQuery = new TwigQuery(rootLevel);
} else {
final Object attQuery = root.getTag(QueryTreeBuilder.QUERY_TREE_BUILDER_TAGID);
if (attQuery != null) {
twigQuery = new TwigQuery(rootLevel);
twigQuery.addRoot((NodeQuery) attQuery);
} else {
throw new QueryNodeException(new MessageImpl(QueryParserMessages.INVALID_SYNTAX,
"Unable to get the root of the Twig query"));
}
}
if (!(child instanceof WildcardNodeQueryNode)) {
// Build the child operand
final Object v = child.getTag(QueryTreeBuilder.QUERY_TREE_BUILDER_TAGID);
if (v instanceof ArrayQuery) { // array of children nodes
final ArrayQueryNode aqn = (ArrayQueryNode) child;
final List<Query> children = ((ArrayQuery) v).getElements();
for (int i = 0; i < children.size(); i++) {
twigQuery.addChild((NodeQuery) children.get(i),
NodeQueryBuilderUtil.getModifierValue(aqn.getChildren().get(i), NodeBooleanClause.Occur.MUST));
}
} else if (v instanceof Query) {
final NodeQuery valQuery = (NodeQuery) v;
twigQuery.addChild(valQuery, Occur.MUST);
} else {
throw new QueryNodeException(new MessageImpl(QueryParserMessages.INVALID_SYNTAX,
"Unexpected class of a Twig Query clause: " + v == null ? "null" : v.getClass().getName()));
}
}