org.apache.jena.shared.PrefixMapping Java Examples

The following examples show how to use org.apache.jena.shared.PrefixMapping. 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: SPARQLExtCli.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static void execGenerateStream(RootPlan plan, ContextUtils.Builder builder, CliRequest request) {
	final PrefixMapping pm = plan.getQuery().getPrefixMapping();
	final ConsoleStreamRDF consoleStreamRDF;
	if (request.output == null) {
		consoleStreamRDF = new ConsoleStreamRDF(System.out, pm);
	} else {
		try {
			consoleStreamRDF = new ConsoleStreamRDF(
					new PrintStream(new FileOutputStream(request.output, request.outputAppend)), pm);
		} catch (IOException ex) {
			LOG.error("Error while opening the output file.", ex);
			return;
		}
	}
	Context context = builder.setGenerateOutput(consoleStreamRDF).build();
	plan.execGenerateStream(context);
}
 
Example #2
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a parsable SPARQL string based on a fragment and prefix declarations.
 * Depending on the setting of the flag useGraphPrefixes, this either uses the
 * prefixes from the Jena graph of the given executable, or strictly uses sh:prefixes.
 * @param str  the query fragment (e.g. starting with SELECT)
 * @param executable  the sh:SPARQLExecutable potentially holding the sh:prefixes
 * @return the parsable SPARQL string
 */
public static String withPrefixes(String str, Resource executable) {
	if(useGraphPrefixes) {
		return ARQFactory.get().createPrefixDeclarations(executable.getModel()) + str;
	}
	else {
		StringBuffer sb = new StringBuffer();
		PrefixMapping pm = new PrefixMappingImpl();
		Set<Resource> reached = new HashSet<Resource>();
		for(Resource ontology : JenaUtil.getResourceProperties(executable, SH.prefixes)) {
			String duplicate = collectPrefixes(ontology, pm, reached);
			if(duplicate != null) {
				throw new SHACLException("Duplicate prefix declaration for prefix " + duplicate);
			}
		}
		for(String prefix : pm.getNsPrefixMap().keySet()) {
			sb.append("PREFIX ");
			sb.append(prefix);
			sb.append(": <");
			sb.append(pm.getNsPrefixURI(prefix));
			sb.append(">\n");
		}
		sb.append(str);
		return sb.toString();
	}
}
 
Example #3
Source File: ARQFactory.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new Query from a partial query (possibly lacking
 * PREFIX declarations), using the ARQ syntax specified by <code>getSyntax</code>.
 * @param model  the Model to operate on
 * @param partialQuery  the (partial) query string
 * @return the Query
 */
public Query createQuery(Model model, String partialQuery) {
	PrefixMapping pm = new PrefixMappingImpl();
    String defaultNamespace = JenaUtil.getNsPrefixURI(model, "");
    if(defaultNamespace != null) {
        pm.setNsPrefix("", defaultNamespace);
    }
    Map<String,String> extraPrefixes = ExtraPrefixes.getExtraPrefixes();
    for(String prefix : extraPrefixes.keySet()) {
    	String ns = extraPrefixes.get(prefix);
    	if(ns != null && pm.getNsPrefixURI(prefix) == null) {
    		pm.setNsPrefix(prefix, ns);
    	}
    }

    // Get all the prefixes from the model at once.
    Map<String, String> map = model.getNsPrefixMap();
    map.remove("");
    pm.setNsPrefixes(map);
    
	return doCreateQuery(partialQuery, pm);
}
 
Example #4
Source File: Qald7CreationTool.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean checkIsOnlydbo(final String sparqlQuery) throws QueryParseException {
	if (sparqlQuery == null) {
		return false;
	}
	Query q = QueryFactory.create(sparqlQuery);
	PrefixMapping prefixMap = q.getPrefixMapping();
	Map<String, String> map = new HashMap<>(prefixMap.getNsPrefixMap());

	Set<Entry<String, String>> remove = new HashSet<>();
	for (Entry<String, String> it : map.entrySet()) {
		if (it.getKey().equals("rdf") || it.getKey().equals("rdfs") || it.getValue().equals(DBO_URI) || it.getValue().equals(RES_URI)) {
			remove.add(it);
		}
	}
	map.entrySet().removeAll(remove);
	return map.isEmpty();
}
 
Example #5
Source File: SPARQLPrefixResolver.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String expandPrefix(final String prefixed) {
	String s = super.getLocalPrefixMapping().expandPrefix(prefixed);
	PrefixMapping pmapGlobal = super.getGlobalPrefixMapping();
	if (pmapGlobal == null) {
		return s;
	}

	if (s == null || s.equals(prefixed)) {
		if (pmapGlobal != null) {
			s = pmapGlobal.expandPrefix(prefixed);
		}
		if (s != null) {
			int colon = prefixed.indexOf(':');
			String prefix = prefixed.substring(0, colon);
			String uri = pmapGlobal.getNsPrefixURI(prefix);
			super.getLocalPrefixMapping().setNsPrefix(prefix, uri);
		}
	}
	return s;
}
 
Example #6
Source File: SPARQLPrefixResolver.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String getNsURIPrefix(final String uri) {
	String s = super.getLocalPrefixMapping().getNsURIPrefix(uri);
	if (s != null) {
		return s;
	}
	PrefixMapping pmapGlobal = super.getGlobalPrefixMapping();
	if (pmapGlobal == null) {
		return null;
	}
	if (pmapGlobal != null) {
		s = pmapGlobal.getNsURIPrefix(uri);
	}
	super.getLocalPrefixMapping().setNsPrefix(s, uri);
	return null;
}
 
Example #7
Source File: SPARQLPrefixResolver.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String getNsPrefixURI(final String prefix) {
	String s = super.getLocalPrefixMapping().getNsPrefixURI(prefix);
	if (s != null) {
		return s;
	}

	PrefixMapping pmapGlobal = super.getGlobalPrefixMapping();
	s = pmapGlobal.getNsPrefixURI(prefix);
	if (s != null) {
		super.getLocalPrefixMapping().setNsPrefix(prefix, s);
		return s;
	}
	return null;

}
 
Example #8
Source File: StreamingRDFWriter.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void writeTurtle(String baseIRI, PrefixMapping prefixes, boolean writeBase) {
	// Auto-register RDF prefix so that rdf:type is displayed well
	// All other prefixes come from the query and should be as author intended
	prefixes = ensureRDFPrefix(prefixes);

	if (writeBase) {
		// Jena's streaming Turtle writers don't output base even if it is provided,
		// so we write it directly.
		IndentedWriter w = new IndentedWriter(out);
		RiotLib.writeBase(w, baseIRI);
		w.flush();
	}
	
	StreamRDF writer = new WriterStreamRDFBlocks(out);
	if (dedupWindowSize > 0) {
		writer = new StreamRDFDedup(writer, dedupWindowSize);
	}
	writer.start();
	writer.base(baseIRI);
	for (Entry<String, String> e : prefixes.getNsPrefixMap().entrySet()) {
		writer.prefix(e.getKey(), e.getValue());
	}
	StreamOps.sendTriplesToStream(triples, writer);
	writer.finish();
}
 
Example #9
Source File: ExpandPrefixFunction.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public NodeValue exec(NodeValue prefix, Context context) {
	if (prefix == null) {
		return null;
	}
	if (!prefix.isString()) {
		throw new ExprEvalException(NAME + ": not a string: " + prefix);
	}
	PrefixMapping prefixes = context.get(PREFIX_MAPPING);
	if (prefixes == null) {
		throw new ExprEvalException(NAME + ": no prefix mapping registered");
	}
	String iri = prefixes.getNsPrefixURI(prefix.asString());
	if (iri == null) {
		throw new ExprEvalException(NAME + ": prefix not defined: " + prefix);
	}
	return NodeValue.makeString(iri);
}
 
Example #10
Source File: DiffGraph.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public PrefixMapping getPrefixMapping() {
	if (pm == null) {
		// copy delegate's prefix mapping.
		pm = new PrefixMappingImpl().setNsPrefixes(base.getPrefixMapping());
	}
	return pm;
}
 
Example #11
Source File: ContextUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private Builder() {
	this.context = new Context(ARQ.getContext());
	this.commons = new Commons();

	// update functionregistry
	FunctionRegistry registry = (FunctionRegistry) context.get(ARQConstants.registryFunctions);
	SPARQLExtFunctionRegistry newRegistry = new SPARQLExtFunctionRegistry(registry, context);
	context.set(ARQConstants.registryFunctions, newRegistry);

	// update iteratorregistry
	IteratorFunctionRegistry iteratorRegistry = (IteratorFunctionRegistry) context
			.get(SPARQLExt.REGISTRY_ITERATORS);
	IteratorFunctionRegistry newIteratorRegistry = new IteratorFunctionRegistry(iteratorRegistry, context);
	context.set(SPARQLExt.REGISTRY_ITERATORS, newIteratorRegistry);

	// default streammanager
	context.set(SysRIOT.sysStreamManager, SPARQLExtStreamManager.makeStreamManager());

	// set variable parts
	context.set(DATASET, DatasetFactory.create());

	// default prefix manager
	context.set(PREFIX_MANAGER, PrefixMapping.Standard);

	// default number of results and blank nodes
	context.set(SIZE, 0);
	// context.set(LIST_NODES, new HashMap<>());

	context.set(COMMONS, commons);
}
 
Example #12
Source File: ContextUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param ctx
 *            the context to fork
 */
private Forker(Context ctx, boolean isRoot) {
	context = new Context(ctx);
	context.set(SysRIOT.sysStreamManager,
			context.get(SysRIOT.sysStreamManager, SPARQLExtStreamManager.makeStreamManager()));
	context.set(BASE, context.get(BASE));
	context.set(PREFIX_MANAGER, context.get(PREFIX_MANAGER, PrefixMapping.Standard));
	context.set(SIZE, 0);
	if(!isRoot) {
		context.set(PARENT_CONTEXT, ctx);
	}
}
 
Example #13
Source File: SPARQLExtParserBase.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
/**
 * Starts parsing a sub GENERATE query.
 */
protected final void startSubQueryExt() {
    String base = getQuery().getBaseURI();
    PrefixMapping pm = getQuery().getPrefixMapping();
    pushQuery();
    query = new SPARQLExtQuery();
    query.setBaseURI(base);
    query.setPrefixMapping(pm);
}
 
Example #14
Source File: PrefixUtils.java    From shacl with Apache License 2.0 5 votes vote down vote up
/** 
 * Copy prefix mappings into {@code dstGraph} from {@code srcGraph},
 * checking whether the prefix mapping is already set.
 * @param dstGraph  the destination graph
 * @param srcGraph  the source graph
 * @return false if no changes where made.
 */
public static boolean copyPrefixMap(Graph dstGraph, Graph srcGraph) {
    boolean changeMade = false;
    PrefixMapping dstPM = dstGraph.getPrefixMapping();
    PrefixMapping srcPM = srcGraph.getPrefixMapping();
    // Copy different prefix mappings.
    for (Map.Entry<String, String> e : srcPM.getNsPrefixMap().entrySet()) {
        if (!e.getValue().equals(dstPM.getNsPrefixURI(e.getKey()))) {
            dstPM.setNsPrefix(e.getKey(), e.getValue());
            changeMade = true;
        }
    }
    return changeMade;
}
 
Example #15
Source File: PrefixUtils.java    From shacl with Apache License 2.0 5 votes vote down vote up
/** 
 * Remove prefix mappings from {@code dstGraph} that do not exist in {@code srcGraph}.
 * @param dstGraph  the destination graph
 * @param srcGraph  the source graph
 * @return false if no changes where made.
 */
public static boolean removeMissingPrefixes(Graph dstGraph, Graph srcGraph) {
    boolean changeMade = false;
    PrefixMapping dstPM = dstGraph.getPrefixMapping();
    PrefixMapping srcPM = srcGraph.getPrefixMapping();
    // Delete those from dstPM that are not in srcPM
    for(String prefix : dstPM.getNsPrefixMap().keySet()) {
        if(srcPM.getNsPrefixURI(prefix) == null) {
            dstPM.removeNsPrefix(prefix);
            changeMade = true;
        }
    }
    return changeMade;
}
 
Example #16
Source File: PrefixMappingMonitor.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Override
public PrefixMapping withDefaultMappings(PrefixMapping map) {
    // fake
    map.getNsPrefixMap().forEach((p,u) -> set(p,u));
    get().withDefaultMappings(map);
    return this;
}
 
Example #17
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the usual default namespaces for rdf, rdfs, owl and xsd.
 * @param prefixMapping  the Model to modify
 */
public static void initNamespaces(PrefixMapping prefixMapping) {
    ensurePrefix(prefixMapping, "rdf",  RDF.getURI());
    ensurePrefix(prefixMapping, "rdfs", RDFS.getURI());
    ensurePrefix(prefixMapping, "owl",  OWL.getURI());
    ensurePrefix(prefixMapping, "xsd",  XSD.getURI());
}
 
Example #18
Source File: JenaInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private String replaceURIs(String tsv, PrefixMapping prefixMapping) {
  Map<String, String> pmap = prefixMapping.getNsPrefixMap();
  for (Map.Entry<String, String> entry : pmap.entrySet()) {
    tsv = tsv.replaceAll(entry.getValue(), entry.getKey() + ":");
  }
  return tsv;
}
 
Example #19
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 5 votes vote down vote up
private static String collectPrefixes(Resource ontology, PrefixMapping pm, Set<Resource> reached) {
	
	reached.add(ontology);
	
	for(Resource decl : JenaUtil.getResourceProperties(ontology, SH.declare)) {
		String prefix = JenaUtil.getStringProperty(decl, SH.prefix);
		String ns = JenaUtil.getStringProperty(decl, SH.namespace);
		if(prefix != null && ns != null) {
			String oldNS = pm.getNsPrefixURI(prefix);
			if(oldNS != null && !oldNS.equals(ns)) {
				return prefix;
			}
			pm.setNsPrefix(prefix, ns);
		}
	}
	
	for(Resource imp : JenaUtil.getResourceProperties(ontology, OWL.imports)) {
		if(!reached.contains(imp)) {
			String duplicate = collectPrefixes(imp, pm, reached);
			if(duplicate != null) {
				return duplicate;
			}
		}
	}
	
	return null;
}
 
Example #20
Source File: SPARQLPrefixResolver.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
/** @see org.apache.jena.shared.PrefixMapping#qnameFor(java.lang.String) */
@Override
public String qnameFor(final String uri) {
	PrefixMapping pmapLocal = super.getLocalPrefixMapping();
	PrefixMapping pmapGlobal = super.getGlobalPrefixMapping();
	String s = pmapLocal.qnameFor(uri);

	if (s != null) {
		return s;
	}

	if (pmapGlobal != null) {
		s = pmapGlobal.qnameFor(uri);
		if (s != null) {
			boolean b = false;
			try {
				b = (boolean) checkValidPrefixMethod.invoke(null, s);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (b) {
				String prefix = s.substring(0, s.indexOf(":"));
				pmapLocal.setNsPrefix(prefix, pmapGlobal.getNsPrefixURI(prefix));
			}
		}
	}
	return s;
}
 
Example #21
Source File: SPARQLPrefixResolver.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
/** @see org.apache.jena.shared.PrefixMapping#shortForm(java.lang.String) */
@Override
public String shortForm(final String uri) {

	PrefixMapping pmapLocal = super.getLocalPrefixMapping();
	PrefixMapping pmapGlobal = super.getGlobalPrefixMapping();
	String s = pmapLocal.shortForm(uri);
	if (pmapGlobal == null) {
		return s;
	}

	if (s == null || s.equals(uri)) {
		s = pmapGlobal.shortForm(uri);
		if (s != null && !s.equals(uri)) {
			boolean b = false;
			try {
				b = (boolean) checkValidPrefixMethod.invoke(null, s);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (b) {
				String prefix = s.substring(0, s.indexOf(":"));
				pmapLocal.setNsPrefix(prefix, pmapGlobal.getNsPrefixURI(prefix));
			}
		}
	}

	return s;
}
 
Example #22
Source File: StreamingRDFWriter.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private PrefixMapping ensureRDFPrefix(PrefixMapping prefixes) {
	// Some prefix already registered for the RDF namespace -- good enough
	if (prefixes.getNsURIPrefix(RDF.getURI()) != null) return prefixes;
	// rdf: is registered to something else -- give up
	if (prefixes.getNsPrefixURI("rdf") != null) return prefixes;
	// Register rdf:
	PrefixMapping newPrefixes = new PrefixMappingImpl();
	newPrefixes.setNsPrefixes(prefixes);
	newPrefixes.setNsPrefix("rdf", RDF.getURI());
	return newPrefixes;
}
 
Example #23
Source File: ExpandPrefixedNameFunction.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public NodeValue exec(NodeValue name, Context context) {
	if (name == null) return null;
	if (!name.isString()) throw new ExprEvalException("Not a string: " + name);
	PrefixMapping prefixes = context.get(ExpandPrefixFunction.PREFIX_MAPPING);
	if (prefixes == null) throw new ExprEvalException("No prefix mapping registered");
	String pname = name.asString();
	int idx = pname.indexOf(':');
	if (idx == -1) throw new ExprEvalException("Not a prefixed name: " + name);
	String prefix = pname.substring(0, idx);
	String iri = prefixes.getNsPrefixURI(prefix);
	if (iri == null) throw new ExprEvalException("Prefix not defined: " + prefix);
	return NodeValue.makeNode(NodeFactory.createURI(iri + pname.substring(idx + 1)));
}
 
Example #24
Source File: JenaUtil.java    From shacl with Apache License 2.0 4 votes vote down vote up
private static void ensurePrefix(PrefixMapping prefixMapping, String prefix, String uristr) {
    // set if not present, or if different
    if (!uristr.equals(prefixMapping.getNsPrefixURI(prefix))) {
        prefixMapping.setNsPrefix(prefix, uristr);
    }
}
 
Example #25
Source File: LargeInputTest.java    From tarql with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Before
public void setUp() {
	PrefixMapping prefixes = new PrefixMappingImpl();
	prefixes.setNsPrefix("ex", EX + "#");
}
 
Example #26
Source File: JenaUtil.java    From shacl with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the usual default namespaces for rdf, rdfs, owl and xsd.
 * @param graph  the Graph to modify
 */
public static void initNamespaces(Graph graph) {
	PrefixMapping prefixMapping = graph.getPrefixMapping();
	initNamespaces(prefixMapping);
}
 
Example #27
Source File: DescribeClass.java    From xcurator with Apache License 2.0 4 votes vote down vote up
protected void renderURI( PrintStream out, PrefixMapping prefixes, String uri ) {
    out.print( prefixes.shortForm( uri ) );
}
 
Example #28
Source File: DescribeClass.java    From xcurator with Apache License 2.0 4 votes vote down vote up
protected PrefixMapping prefixesFor( Resource n ) {
    return n.getModel().getGraph().getPrefixMapping();
}
 
Example #29
Source File: ClassHierarchy.java    From xcurator with Apache License 2.0 4 votes vote down vote up
/** Render a URI */
protected void renderURI( PrintStream out, PrefixMapping prefixes, String uri ) {
    out.print( prefixes.shortForm( uri ) );
}
 
Example #30
Source File: ShapePathImplTest.java    From RDFUnit with Apache License 2.0 4 votes vote down vote up
private ShapePath fromString(String propertyPathString) {
    return new ShapePathImpl(ResourceFactory.createResource("http://example.com/"),
            PathParser.parse(propertyPathString, PrefixMapping.Standard));
}