+
+ private static WorkbenchSelectionElement getPossibleWorkbenchSelectionElement(Object selection) {
+ return getPossibleObject(selection, WorkbenchSelectionElement.class);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> T getPossibleObject(Object selection, Class<T> clazz) {
+ return clazz.isInstance(selection)
+ ? (T) selection
+ : ISelectionUtils.filterSingleSelection(selection, clazz);
+ }
+
+ private static class PossibleVariableType extends VariableRead<Resource> {
+
+ public PossibleVariableType(Variable var) {
+ super(var);
+ }
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return variable.getPossibleType(graph);
+ }
+
+ }
+
+ private static String toJSONObjectString(String... keyValuePairs) {
+ int len = keyValuePairs.length;
+ assert (len & 1) == 0;
+ StringBuilder sb = new StringBuilder(128);
+ sb.append("{ ");
+ int entryCount = 0;
+ for (int i = 0; i < len; i += 2) {
+ String value = keyValuePairs[i+1];
+ if (value != null && !value.isEmpty()) {
+ if (entryCount > 0)
+ sb.append(", ");
+ sb.append("\"").append(keyValuePairs[i]).append("\": ").append(value);
+ ++entryCount;
+ }
+ }
+ sb.append(" }");
+ return sb.toString();
+ }
+
+ private static String escapeQuotes(String s) {
+ return s.indexOf('"') >= 0 ? s.replaceAll("\"", "\\\\\"") : s;
+ }
+
+ private static String safeQuotedString(String s) {
+ return s != null && !s.isEmpty() ? "\"" + escapeQuotes(s) + "\"" : "";
+ }
+
+ private static String toJSONStringArray(List<String> strings) throws DatabaseException {
+ // Sort the type strings to produce stable results
+ if (strings.isEmpty())
+ return "";
+ return strings.stream()
+ .map(WorkbenchSelectionUtils::escapeQuotes)
+ .sorted()
+ .collect(Collectors.joining("\", \"", "[\"", "\"]"));
+ }
+
+ private static String getTypeResourceString(RequestProcessor processor, Resource r, Variable v) throws DatabaseException {
+ return toJSONStringArray(
+ toPossibleURIs(processor,
+ getTypes(processor, r, v)));
+ }
+
+ private static Set<Resource> getTypes(RequestProcessor processor, Resource r, Variable v) throws DatabaseException {
+ if (r == null && v != null)
+ r = processor.syncRequest(new PossibleVariableRepresents(v));
+ if (r != null)
+ return processor.syncRequest(new Types(r));
+ r = v != null ? processor.syncRequest(new PossibleVariableType(v)) : null;
+ return r != null ? processor.syncRequest(new Supertypes(r)) : Collections.emptySet();
+ }
+
+ private static List<String> toPossibleURIs(RequestProcessor processor, Collection<Resource> resources) throws DatabaseException {
+ if (resources.isEmpty())
+ return Collections.emptyList();
+ List<String> result = new ArrayList<>(resources.size());
+ for (Resource r : resources) {
+ String uri = processor.syncRequest(new PossibleURI(r));
+ if (uri != null)
+ result.add(uri);
+ }
+ return result;
+ }
+