writeln("Evaluating query...");
long startTime = System.nanoTime();
Collection<Namespace> namespaces = con.getNamespaces().addTo(new ArrayList<Namespace>());
TupleResult tupleQueryResult = con.prepareTupleQuery(ql, queryString).evaluate();
try {
int resultCount = 0;
List<String> bindingNames = tupleQueryResult.getBindingNames();
if (bindingNames.isEmpty()) {
while (tupleQueryResult.hasNext()) {
tupleQueryResult.next();
resultCount++;
}
}
else {
int columnWidth = (consoleWidth - 1) / bindingNames.size() - 3;
// Build table header
StringBuilder sb = new StringBuilder(consoleWidth);
for (String bindingName : bindingNames) {
sb.append("| ").append(bindingName);
StringUtil.appendN(' ', columnWidth - bindingName.length(), sb);
}
sb.append("|");
String header = sb.toString();
// Build separator line
sb.setLength(0);
for (int i = bindingNames.size(); i > 0; i--) {
sb.append('+');
StringUtil.appendN('-', columnWidth + 1, sb);
}
sb.append('+');
String separatorLine = sb.toString();
// Write table header
writeln(separatorLine);
writeln(header);
writeln(separatorLine);
// Write table rows
while (tupleQueryResult.hasNext()) {
BindingSet bindingSet = tupleQueryResult.next();
resultCount++;
sb.setLength(0);
for (String bindingName : bindingNames) {
Value value = bindingSet.getValue(bindingName);
String valueStr = getStringRepForValue(value, namespaces);
sb.append("| ").append(valueStr);
StringUtil.appendN(' ', columnWidth - valueStr.length(), sb);
}
sb.append("|");
writeln(sb.toString());
}
writeln(separatorLine);
}
long endTime = System.nanoTime();
writeln(resultCount + " result(s) (" + (endTime - startTime) / 1000000 + " ms)");
}
finally {
tupleQueryResult.close();
}
}
finally {
con.close();
}