org.apache.jena.graph.NodeFactory Java Examples

The following examples show how to use org.apache.jena.graph.NodeFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PubchemMeshSynonyms.java    From act with GNU General Public License v3.0 7 votes vote down vote up
public String fetchCIDFromInchi(String inchi) {
  // The clone method has its own implementation in the SelectBuilder. Thus safe to use!
  SelectBuilder sb = CID_QUERY_TMPL.clone();
  // The inchi litteral needs to be create with a language tag, otherwise it will not match anything
  // See "Matching Litteral with Language Tags" (https://www.w3.org/TR/rdf-sparql-query/#matchLangTags)
  // for more information
  sb.setVar(Var.alloc("inchi_string"), NodeFactory.createLiteral(inchi, ENGLISH_LANG_TAG));
  Query query = sb.build();

  String result;
  LOGGER.debug("Executing SPARQL query: %s", query.toString());
  try (QueryExecution qexec = QueryExecutionFactory.sparqlService(sparqlService, query)) {
    ResultSet results = qexec.execSelect();
    // TODO: we assume here that there is at most one CID per InChI and return the first CID
    // Improve that behavior so we can stitch together many CID's synonyms.
    if (!results.hasNext()) {
      LOGGER.info("Could not find Pubchem Compound Id for input InChI %s", inchi);
      return null;
    }
    result = results.nextSolution().getResource("inchi_iri").getLocalName();
  }

  String cid = extractCIDFromResourceName(result);
  LOGGER.info("Found Pubchem Compound Id %s for input InChI %s", cid, inchi);
  return cid;
}
 
Example #2
Source File: AbstractTestDeltaLink.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@Test
public void dLink_patch_events_1() {
    // Test routing to RDFChanges.
    DeltaLink dLink = getLink();
    Id dsRef = dLink.newDataSource("dLink_patch_events_1", "http://example/patchEvent1");

    Node gn = NodeFactory.createURI("http://example/g");
    // Test listener.
    RDFChangesCounter c = new RDFChangesCounter() {
        @Override
        public void add(Node g, Node s, Node p, Node o) {
            assertEquals(gn, g);
            super.add(g, s, p, o);
        }
    };
    setupEvents(dLink, dsRef, c);

    patch_send(dsRef, "patch1.rdfp");
    // Fetch patch, trigger listener.
    dLink.fetch(dsRef, Version.FIRST);

    // Assess what happened.
    PatchSummary summary = c.summary();
    assertEquals(1, summary.countAddData);
}
 
Example #3
Source File: RDFNodeFactory.java    From Processor with Apache License 2.0 6 votes vote down vote up
public static final RDFNode createTyped(String value, Resource valueType)
   {
if (value == null) throw new IllegalArgumentException("Param value cannot be null");

       // without value type, return default xsd:string value
       if (valueType == null) return ResourceFactory.createTypedLiteral(value, XSDDatatype.XSDstring);

       // if value type is from XSD namespace, value is treated as typed literal with XSD datatype
       if (valueType.getNameSpace().equals(XSD.getURI()))
       {
           RDFDatatype dataType = NodeFactory.getType(valueType.getURI());
           return ResourceFactory.createTypedLiteral(value, dataType);
       }
       // otherwise, value is treated as URI resource
       else
           return ResourceFactory.createResource(value);
   }
 
Example #4
Source File: Query.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<Node> getResultURIs() {
	List<Node> list = new ArrayList<Node>();
	if (describeQuery != null) {
		List<BinaryUnion<Variable, IRI>> binaryUnions = describeQuery
				.getResources();
		if (binaryUnions != null) {
			for (BinaryUnion<Variable, IRI> binaryUnion : binaryUnions) {
				if (binaryUnion.getSecond() != null) {
					String v = binaryUnion.getSecond().toString();
					Node e = NodeFactory.createURI(v);
					list.add(e);
				}
			}
		}
	}
	return list;
}
 
Example #5
Source File: SPDXFile.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the resource for an existing file in the model
 * @param spdxFile
 * @return resource of an SPDX file with the same name and checksum.  Null if none found
 * @throws InvalidSPDXAnalysisException 
 */
static protected Resource findFileResource(Model model, SPDXFile spdxFile) throws InvalidSPDXAnalysisException {
	// find any matching file names
	Node fileNameProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_NAME).asNode();
	Triple fileNameMatch = Triple.createMatch(null, fileNameProperty, NodeFactory.createLiteral(spdxFile.getName()));
	
	ExtendedIterator<Triple> filenameMatchIter = model.getGraph().find(fileNameMatch);	
	if (filenameMatchIter.hasNext()) {
		Triple fileMatchTriple = filenameMatchIter.next();
		Node fileNode = fileMatchTriple.getSubject();
		// check the checksum
		Node checksumProperty = model.getProperty(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_FILE_CHECKSUM).asNode();
		Triple checksumMatch = Triple.createMatch(fileNode, checksumProperty, null);
		ExtendedIterator<Triple> checksumMatchIterator = model.getGraph().find(checksumMatch);
		if (checksumMatchIterator.hasNext()) {
			Triple checksumMatchTriple = checksumMatchIterator.next();
			SPDXChecksum cksum = new SPDXChecksum(model, checksumMatchTriple.getObject());
			if (cksum.getValue().compareToIgnoreCase(spdxFile.sha1.getValue()) == 0) {
				return RdfParserHelper.convertToResource(model, fileNode);
			}
		}
	}
	// if we get to here, we did not find a match
	return null;
}
 
Example #6
Source File: localname.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private QueryIterator execFixedSubject(Node nodeURI, Node nodeLocalname, Binding binding, ExecutionContext execCxt)
{
    if ( ! nodeURI.isURI() )
        // Subject bound but not a URI
        return QueryIterNullIterator.create(execCxt) ;

    // Subject is bound and a URI - get the localname as a Node 
    Node localname = NodeFactory.createLiteral(nodeURI.getLocalName()) ;
    
    // Object - unbound variable or a value? 
    if ( ! nodeLocalname.isVariable() )
    {
        // Object bound or a query constant.  Is it the same as the calculated value?
        if ( nodeLocalname.equals(localname) )
            // Same
            return QueryIterSingleton.create(binding, execCxt) ;
        // No - different - no match.
        return QueryIterNullIterator.create(execCxt) ;
    }
    
    // Object unbound variable - assign the localname to it.
    return QueryIterSingleton.create(binding, Var.alloc(nodeLocalname), localname, execCxt) ;
}
 
Example #7
Source File: RuleSystemToQueries.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
protected static Node toNode(Expr e        ) {
	
	Node ret;
	if(e.isVariable()) {
		ret = NodeFactory.createVariable(((VariableExpr)e).getName());
	} else {
		Object v = ((ConstantExpr) e).getValue();
		if (v instanceof URI) {
			ret = NodeFactory.createURI(v.toString());
		} /*else if (predicatePosition) {
			ret = Node.createURI(v.toString());
		}*/ else
		{
			ret = NodeFactory.createLiteral(v.toString());
		}
	}
	return ret;
}
 
Example #8
Source File: OCUtils.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public static Set<ConjunctiveQuery> getMembershipQuery(OWLOntology ont) {
	Set<ConjunctiveQuery> ret = new HashSet<ConjunctiveQuery>();
	for (OWLClass owlclass: ont.getClassesInSignature(true)) {
		ElementTriplesBlock p = new ElementTriplesBlock();
		String x = "x";
		Node sub = NodeFactory.createVariable(x);
		Node pred = NodeFactory.createURI(RDFConstants.RDF_TYPE);
		Node obj = NodeFactory.createURI(owlclass.getIRI().toString());
		Triple qt = new Triple(sub, pred, obj);
		p.getPattern().add(qt);
		ConjunctiveQuery cq = new ConjunctiveQuery();
		cq.setQueryPattern(p);
		cq.addResultVar(x);
		cq.setDistinct(true);
		ret.add(cq);
	}
	return ret;
}
 
Example #9
Source File: PredicateMappingsDataSet.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
public PredicateMappingsDataSet(int numberOfHashFunctions,
		int numberOfColorFunctions) {
	this.numberOfColorFunctions = numberOfColorFunctions;
	this.numberOfHashFunctions = numberOfHashFunctions;

	Model defModel = ModelFactory.createDefaultModel();
	dataset = DatasetFactory.create(defModel);
	dataset.getDefaultModel()
			.getGraph()
			.add(new Triple(NodeFactory.createURI(Constants.ibmns
					+ Constants.NUM_COL_FUNCTION),
					NodeFactory.createURI(Constants.ibmns
							+ Constants.VALUE_PREDICATE), intToNode(numberOfColorFunctions)));

	dataset.getDefaultModel()
			.getGraph()
			.add(new Triple(NodeFactory.createURI(Constants.ibmns
					+ Constants.NUM_HASH_FUNCTION),
					NodeFactory.createURI(Constants.ibmns
							+ Constants.VALUE_PREDICATE), intToNode(numberOfHashFunctions)));
}
 
Example #10
Source File: SPARQLExtCli.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static void replaceSourcesIfRequested(CommandLine cli, SPARQLExtQuery query) {
	final Properties replacementSources = cli.getOptionProperties(ARG_SOURCE_LONG);

	List<Element> updatedSources = query.getBindingClauses().stream().map(element -> {
		if (element instanceof ElementSource) {
			ElementSource elementSource = (ElementSource) element;
			String sourceURI = elementSource.getSource().toString(query.getPrefixMapping(), false);

			if (replacementSources.containsKey(sourceURI)) {
				Node replacementSource = NodeFactory.createURI(replacementSources.getProperty(sourceURI));

				LOG.info("Replaced source <{}> with <{}>.", sourceURI, replacementSource);

				return new ElementSource(replacementSource, elementSource.getAccept(), elementSource.getVar());
			}
		}

		return element;
	}).collect(Collectors.toList());

	query.setBindingClauses(updatedSources);
}
 
Example #11
Source File: LogUtils.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static ElementData compress(List<Var> variables, List<Binding> input) {
    ElementData el = new ElementData();
    variables.forEach(el::add);
    if (input.size() < 10) {
        input.forEach((b) -> el.add(compress(variables, b)));
        return el;
    }
    for (int i = 0; i < 5; i++) {
        el.add(compress(variables, input.get(i)));
    }
    BindingMap binding = BindingFactory.create();
    Node n = NodeFactory.createLiteral("[ " + (input.size() - 10) + " more ]");
    variables.forEach((v) -> binding.add(v, n));
    el.add(binding);
    for (int i = input.size() - 5; i < input.size(); i++) {
        el.add(compress(variables, input.get(i)));
    }
    return el;
}
 
Example #12
Source File: LogUtils.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static ElementData compress(List<Binding> input) {
    ElementData el = new ElementData();

    if (input.size() < 10) {
        input.forEach((b) -> {
            addCompressedToElementData(el, b);
        });
        return el;
    }
    for (int i = 0; i < 5; i++) {
        addCompressedToElementData(el, input.get(i));
    }
    BindingMap binding = BindingFactory.create();
    Node n = NodeFactory.createLiteral("[ " + (input.size() - 10) + " more ]");
    el.getVars().forEach((v) -> binding.add(v, n));
    el.add(binding);
    for (int i = input.size() - 5; i < input.size(); i++) {
        addCompressedToElementData(el, input.get(i));
    }
    return el;
}
 
Example #13
Source File: DatasetDeclarationPlan.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private void addNamedGraph(Binding binding, Context context, DatasetGraph dsg, Expr sourceExpr) {
	String sourceURI = evalSourceURI(binding, context, sourceExpr);
	final String absURI = baseURI(sourceURI, baseURI);
	Dataset dataset = ContextUtils.getDataset(context);
	Node n = NodeFactory.createURI(absURI);
	Graph g = dsg.getGraph(n);
	if (g == null) {
		g = GraphFactory.createJenaDefaultGraph();
		dsg.addGraph(n, g);
	}
	// default: check the dataset
	if (dataset.containsNamedModel(absURI)) {
		Graph dg = dataset.getNamedModel(absURI).getGraph();
		GraphUtil.addInto(g, dg);
		return;
	}
	// fallback: load as RDF graph
	StreamRDF dest = StreamRDFLib.graph(g);
	ContextUtils.loadGraph(context, sourceURI, absURI, dest);
}
 
Example #14
Source File: ITER_GeoJSON.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public List<List<NodeValue>> exec(NodeValue json) {
    String s = getString(json);
    List<List<NodeValue>> nodeValues = new ArrayList<>();
    FeatureCollection featureCollection = GSON.fromJson(s, FeatureCollection.class);

    for (Feature feature : featureCollection.features()) {
        List<NodeValue> values = new ArrayList<>();
        NodeValue geometry = geoJSONGeom.getNodeValue(feature.geometry());
        values.add(geometry);
        Node properties = NodeFactory.createLiteral(
                GSON.toJson(feature.properties()),
                TypeMapper.getInstance().getSafeTypeByName("http://www.iana.org/assignments/media-types/application/json"));
        values.add(new NodeValueNode(properties));
        nodeValues.add(values);
    }
    return nodeValues;
}
 
Example #15
Source File: FUN_XPath.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public NodeValue nodeForNode(org.w3c.dom.Node xmlNode) throws TransformerException {
    if(xmlNode == null) {
        return null;
    }
    String nodeValue = xmlNode.getNodeValue();
    if (nodeValue != null) {
        return new NodeValueString(nodeValue);
    } else {
        DOMSource source = new DOMSource(xmlNode);
        StringWriter writer = new StringWriter();
        Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
        transformer.transform(source, new StreamResult(writer));
        Node node = NodeFactory.createLiteral(writer.toString(), DT);
        return new NodeValueNode(node);
    }
}
 
Example #16
Source File: RDFPatchReaderBinary.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
public static Node fromThrift(RDF_Term term) {
    if ( term.isSetIri() )
        return NodeFactory.createURI(term.getIri().getIri());

    if ( term.isSetBnode() )
        return NodeFactory.createBlankNode(term.getBnode().getLabel());

    if ( term.isSetLiteral() ) {
        RDF_Literal lit = term.getLiteral();
        String lex = lit.getLex();
        String dtString = null;
        if ( lit.isSetDatatype() )
            dtString = lit.getDatatype();
        RDFDatatype dt = NodeFactory.getType(dtString);

        String lang = lit.getLangtag();
        return NodeFactory.createLiteral(lex, lang, dt);
    }

    throw new PatchException("No conversion to a Node: "+term.toString());
}
 
Example #17
Source File: CSVParser.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Binding toBinding(String[] row) {
	BindingHashMap result = new BindingHashMap();
	for (int i = 0; i < row.length; i++) {
		if (isUnboundValue(row[i]))
			continue;
		result.add(getVar(i), NodeFactory.createLiteral(sanitizeString(row[i])));
	}
	// Add current row number as ?ROWNUM
	result.add(TarqlQuery.ROWNUM, NodeFactory.createLiteral(
			Integer.toString(rownum), XSDDatatype.XSDinteger));
	return result;
}
 
Example #18
Source File: DatatypeConstraintExecutor.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine engine, Collection<RDFNode> focusNodes) {
	long startTime = System.currentTimeMillis();
	RDFNode datatypeNode = constraint.getParameterValue();
	String datatypeURI = datatypeNode.asNode().getURI();
	RDFDatatype datatype = NodeFactory.getType(datatypeURI);
	String message = "Value must be a valid literal of type " + ((Resource)datatypeNode).getLocalName();
	for(RDFNode focusNode : focusNodes) {
		for(RDFNode valueNode : engine.getValueNodes(constraint, focusNode)) {
			validate(constraint, engine, message, datatypeURI, datatype, focusNode, valueNode);
		}
		engine.checkCanceled();
	}
	addStatistics(constraint, startTime);
}
 
Example #19
Source File: TermFactory.java    From shacl with Apache License 2.0 5 votes vote down vote up
public JSLiteral literal(String value, Object langOrDatatype) {
	if(langOrDatatype instanceof JSNamedNode) {
		return new JSLiteral(NodeFactory.createLiteral(value, TypeMapper.getInstance().getTypeByName(((JSNamedNode)langOrDatatype).getValue())));
	}
	else if(langOrDatatype instanceof String) {
		return new JSLiteral(NodeFactory.createLiteral(value, (String)langOrDatatype));
	}
	else {
		throw new IllegalArgumentException("Invalid type of langOrDatatype argument");
	}
}
 
Example #20
Source File: JSFactory.java    From shacl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static Node getNode(Object obj) {
	if(obj == null) {
		return null;
	}
	else if(obj instanceof JSTerm) {
		return ((JSTerm)obj).getNode();
	}
	else if(obj instanceof Map) {
		Map som = (Map) obj;
		String value = (String) som.get(VALUE);
		if(value == null) {
			throw new IllegalArgumentException("Missing value");
		}
		String termType = (String) som.get(TERM_TYPE);
		if(NAMED_NODE.equals(termType)) {
			return NodeFactory.createURI(value);
		}
		else if(BLANK_NODE.equals(termType)) {
			return NodeFactory.createBlankNode(value);
		}
		else if(LITERAL.equals(termType)) {
			String lang = (String) som.get(LANGUAGE);
			Map dt = (Map)som.get(DATATYPE);
			String dtURI = (String)dt.get(VALUE);
			RDFDatatype datatype = TypeMapper.getInstance().getSafeTypeByName(dtURI);
			return NodeFactory.createLiteral(value, lang, datatype);
		}
		else {
			throw new IllegalArgumentException("Unsupported term type " + termType);
		}
	}
	else {
		return null;
	}
}
 
Example #21
Source File: AbstractSPARQLExpression.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getFunctionalSyntaxArguments() {
	List<String> results = new LinkedList<>();
	results.add(FmtUtils.stringForNode(NodeFactory.createLiteral(queryString)));
	NodeExpression input = getInput();
	if(input != null) {
		results.add(input.getFunctionalSyntax());
	}
	return results;
}
 
Example #22
Source File: AnnotationTools.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
private String getLiteral(Child<?> workflowBean, String propertyUri) {
	Dataset annotations = annotationDatasetFor(workflowBean);
	URI beanUri = uritools.uriForBean(workflowBean);
	Node subject = NodeFactory.createURI(beanUri.toString());
	Node property = NodeFactory.createURI(propertyUri);

	Iterator<Quad> found = annotations.asDatasetGraph().find(null, subject,
			property, null);
	if (!found.hasNext()) {
		return null;
	}
	return found.next().getObject().toString(false);
}
 
Example #23
Source File: SPDXDocument.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @param id
 * @return true if the license ID is already in the model as an extracted license info
 * @throws InvalidSPDXAnalysisException 
 */
protected boolean extractedLicenseExists(String id) throws InvalidSPDXAnalysisException {
	Node p = model.getProperty(SPDX_NAMESPACE, PROP_LICENSE_ID).asNode();
	Node o = NodeFactory.createLiteral(id);
	Triple m = Triple.createMatch(null, p, o);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	return tripleIter.hasNext();
}
 
Example #24
Source File: uppercase.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Override
public Node calc(Node node)
{
    if ( ! node.isLiteral() ) 
        return null ;
    String str = node.getLiteralLexicalForm().toUpperCase() ;
    return NodeFactory.createLiteral(str) ;
}
 
Example #25
Source File: FUN_CSSPath.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private NodeValue selectElement(Element element, String selectPath) {
    Elements elements = element.select(selectPath);
    Element e = elements.first();
    if (e == null) {
        throw new ExprEvalException("No evaluation of " + element + ", " + selectPath);
    }
    Node n = NodeFactory.createLiteral(e.outerHtml(), DT);
    return new NodeValueNode(n);
}
 
Example #26
Source File: ITER_CSVHeaders.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public List<List<NodeValue>> exec(NodeValue csv) {
    if (csv.getDatatypeURI() != null
            && !csv.getDatatypeURI().equals(datatypeUri)
            && !csv.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.debug("The URI of NodeValue1 MUST be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>."
        );
    }
    try {
        String sourceCSV = String.valueOf(csv.asNode().getLiteralLexicalForm());

        InputStream is = new ByteArrayInputStream(sourceCSV.getBytes("UTF-8"));
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        CsvMapReader mapReader = new CsvMapReader(br, CsvPreference.STANDARD_PREFERENCE);
        String headers_str[] = mapReader.getHeader(true);

        final List<List<NodeValue>> listNodeValues = new ArrayList<>();
        Node node;
        NodeValue nodeValue;
        for (String header : headers_str) {
            node = NodeFactory.createLiteral(header);
            nodeValue = new NodeValueNode(node);
            listNodeValues.add(Collections.singletonList(nodeValue));
        }
        return listNodeValues;
    } catch (Exception ex) {
        if(LOG.isDebugEnabled()) {
            Node compressed = LogUtils.compress(csv.asNode());
            LOG.debug("No evaluation for " + compressed, ex);
        }
        throw new ExprEvalException("No evaluation ", ex);
    }
}
 
Example #27
Source File: TestRDFChangesGraph.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private static Graph txnGraph(String graphName) {
        DatasetGraph dsg = DatasetGraphFactory.createTxnMem();
        Node gn = NodeFactory.createURI(graphName);
        Graph g = dsg.getGraph(gn);
        // Jena 3.5.0 and earlier.
//      g = new GraphWrapper(g) {
//          @Override public TransactionHandler getTransactionHandler() { return new TransactionHandlerView(dsg); }
//      };
        return g;
    }
 
Example #28
Source File: RDFPatchReaderText.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private static Node tokenToNode(Token token) {
    if ( token.isIRI() )
        // URI or <_:...>
        return RiotLib.createIRIorBNode(token.getImage());
    if ( token.isBNode() ) {
        // Blank node as _:...
        String label = token.getImage().substring(bNodeLabelStart.length());
        return NodeFactory.createBlankNode(label);
    }
    Node node = token.asNode();
    if ( node == null )
        throw exception(token, "Expect a Node, got %s",token);
    return node;
}
 
Example #29
Source File: ITER_JSONListKeys.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public List<List<NodeValue>> exec(NodeValue json) {
    if (json.getDatatypeURI() != null
            && !json.getDatatypeURI().equals(datatypeUri)
            && !json.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.debug("The URI of NodeValue1 MUST have been"
                + " <" + datatypeUri + "> or"
                + " <http://www.w3.org/2001/XMLSchema#string>."
                + " Got <" + json.getDatatypeURI() + ">"
        );
    }
    try {
        Set<String> keys = GSON.fromJson(json.asNode().getLiteralLexicalForm(), Map.class).keySet();
        List<List<NodeValue>> listNodeValues = new ArrayList<>(keys.size());
        for (String key : keys) {
            NodeValue nodeValue
                    = NodeValue.makeNode(NodeFactory.createLiteral(key));
            listNodeValues.add(Collections.singletonList(nodeValue));
        }
        LOG.trace("end JSONListKeys");
        return listNodeValues;
    } catch (Exception ex) {
        if(LOG.isDebugEnabled()) {
            Node compressed = LogUtils.compress(json.asNode());
            LOG.debug("No evaluation for " + compressed, ex);
        }
        throw new ExprEvalException("No evaluation", ex);
    }
}
 
Example #30
Source File: SourcePlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
final protected Binding exec(
        final Binding binding,
        final Context context) {

    LOG.debug("Start " + this);
    Objects.nonNull(binding);
    // generate the source URI.
    final String sourceUri = getActualSource(binding);
    final String acceptHeader = getAcceptHeader(binding);
    LOG.trace("... resolved to SOURCE <" + sourceUri + "> ACCEPT " + acceptHeader + " AS " + var);
    final LookUpRequest request = new LookUpRequest(sourceUri, acceptHeader);
    final SPARQLExtStreamManager sm = (SPARQLExtStreamManager) context.get(SysRIOT.sysStreamManager);
    Objects.requireNonNull(sm);
    final TypedInputStream stream = sm.open(request);
    if (stream == null) {
        LOG.info("Exec SOURCE <" + sourceUri + "> ACCEPT " + acceptHeader + " AS " + var + " returned nothing.");
        return BindingFactory.binding(binding);
    }
    try (InputStream in = stream.getInputStream()) {
        final String literal = IOUtils.toString(in, "UTF-8");
        final RDFDatatype dt;
        if (stream.getMediaType() != null && stream.getMediaType().getContentType() != null) {
            dt = tm.getSafeTypeByName("http://www.iana.org/assignments/media-types/" + stream.getMediaType().getContentType());
        } else {
            dt = tm.getSafeTypeByName("http://www.w3.org/2001/XMLSchema#string");
        }
        final Node n = NodeFactory.createLiteral(literal, dt);
        LOG.debug("Exec " + this + " returned. "
                + "Enable TRACE level for more.");
        if (LOG.isTraceEnabled()) {
            LOG.trace("Exec " + this + " returned\n" + LogUtils.compress(n));
        }
        return BindingFactory.binding(binding, var, n);
    } catch (IOException | DatatypeFormatException ex) {
        LOG.warn("Exception while looking up " + sourceUri + ":", ex);
        return BindingFactory.binding(binding);
    }
}