Java Code Examples for org.eclipse.rdf4j.model.IRI#equals()
The following examples show how to use
org.eclipse.rdf4j.model.IRI#equals() .
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: ExploreServlet.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Gets whether this is the first time the result quad has been seen. * * @param patternPredicate the predicate asked for, or null if another quad element was asked for * @param patternObject the object asked for, or null if another quad element was asked for * @param result the result statement to determine if we've already seen * @param patternContext the context asked for, or null if another quad element was asked for * @return true, if this is the first time the quad has been seen, false otherwise */ private boolean isFirstTimeSeen(Statement result, IRI patternPredicate, Value patternObject, Resource... patternContext) { Resource resultSubject = result.getSubject(); IRI resultPredicate = result.getPredicate(); Value resultObject = result.getObject(); boolean firstTimeSeen; if (1 == patternContext.length) { // I.e., when context matches explore value. Resource ctx = patternContext[0]; firstTimeSeen = !(ctx.equals(resultSubject) || ctx.equals(resultPredicate) || ctx.equals(resultObject)); } else if (null != patternObject) { // I.e., when object matches explore value. firstTimeSeen = !(resultObject.equals(resultSubject) || resultObject.equals(resultPredicate)); } else if (null != patternPredicate) { // I.e., when predicate matches explore value. firstTimeSeen = !(resultPredicate.equals(resultSubject)); } else { // I.e., when subject matches explore value. firstTimeSeen = true; } return firstTimeSeen; }
Example 2
Source File: GeoTemporalMongoDBStorageStrategy.java From rya with Apache License 2.0 | 6 votes |
@Override public Document serialize(final RyaStatement ryaStatement) { final Document doc = new Document("_id", ryaStatement.getSubject().hashCode()); final IRI obj = ryaStatement.getObject().getDataType(); if(obj.equals(GeoConstants.GEO_AS_WKT) || obj.equals(GeoConstants.GEO_AS_GML) || obj.equals(GeoConstants.XMLSCHEMA_OGC_GML) || obj.equals(GeoConstants.XMLSCHEMA_OGC_WKT)) { try { final Statement statement = RyaToRdfConversions.convertStatement(ryaStatement); final Geometry geo = GeoParseUtils.getGeometry(statement, new GmlParser()); if (geo.getNumPoints() > 1) { doc.append(GEO_KEY, geoStrategy.getCorrespondingPoints(geo)); } else { doc.append(GEO_KEY, geoStrategy.getDBPoint(geo)); } } catch (final ParseException e) { LOG.error("Could not create geometry for statement " + ryaStatement, e); return null; } } else { doc.append(TIME_KEY, temporalStrategy.getTimeValue(ryaStatement.getObject().getData())); } return doc; }
Example 3
Source File: NTriplesUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Appends the N-Triples representation of the given {@link Literal} to the given {@link Appendable}, optionally * ignoring the xsd:string datatype as it is implied for RDF-1.1. * * @param lit The literal to write. * @param appendable The object to append to. * @param xsdStringToPlainLiteral True to omit serializing the xsd:string datatype and false to always serialize the * datatype for literals. * @param escapeUnicode True to escape non-ascii/non-printable characters using Unicode escapes * (<tt>\uxxxx</tt> and <tt>\Uxxxxxxxx</tt>), false to print without * escaping. * @throws IOException */ public static void append(Literal lit, Appendable appendable, boolean xsdStringToPlainLiteral, boolean escapeUnicode) throws IOException { // Do some character escaping on the label: appendable.append("\""); escapeString(lit.getLabel(), appendable, escapeUnicode); appendable.append("\""); if (Literals.isLanguageLiteral(lit)) { // Append the literal's language appendable.append("@"); appendable.append(lit.getLanguage().get()); } else { // SES-1917 : In RDF-1.1, all literals have a type, and if they are not // language literals we display the type for backwards compatibility // Append the literal's datatype IRI datatype = lit.getDatatype(); boolean ignoreDatatype = datatype.equals(XMLSchema.STRING) && xsdStringToPlainLiteral; if (!ignoreDatatype) { appendable.append("^^"); append(lit.getDatatype(), appendable); } } }
Example 4
Source File: ConformanceTest.java From rya with Apache License 2.0 | 6 votes |
/** * Determine that a statement is trivially true for purposes of entailment * tests, such as an implicit "[bnode] type Ontology" triple or a * "[class] type Class" triple as long as the class exists. */ boolean triviallyTrue(final Statement triple, final Schema schema) { final Resource s = triple.getSubject(); final IRI p = triple.getPredicate(); final Value o = triple.getObject(); if (p.equals(RDF.TYPE)) { if (o.equals(OWL.ONTOLOGY)) { return true; } else if (o.equals(OWL.CLASS)) { return schema.hasClass(s); } else if ((o.equals(OWL.OBJECTPROPERTY) || o.equals(OWL.DATATYPEPROPERTY)) && s instanceof IRI) { // Distinction not maintained, irrelevant to RL rules return schema.hasProperty((IRI) s); } } return false; }
Example 5
Source File: BindingSetStringConverter.java From rya with Apache License 2.0 | 6 votes |
/** * Creates a {@link Value} from a String representation of it. * * @param valueString - The String representation of the value. (not null) * @return The {@link Value} representation of the String. */ protected static Value toValue(final String valueString) { requireNonNull(valueString); // Split the String that was stored in Fluo into its Value and Type parts. final String[] valueAndType = valueString.split(TYPE_DELIM); if(valueAndType.length != 2) { throw new IllegalArgumentException("Array must contain data and type info!"); } final String dataString = valueAndType[0]; final String typeString = valueAndType[1]; // Convert the String Type into a IRI that describes the type. final IRI typeIRI = VF.createIRI(typeString); // Convert the String Value into a Value. final Value value = typeIRI.equals(XMLSchema.ANYURI) ? VF.createIRI(dataString) : VF.createLiteral(dataString, VF.createIRI(typeString)); return value; }
Example 6
Source File: GeoIndexerSfTest.java From rya with Apache License 2.0 | 5 votes |
private static Statement genericStatement(final Geometry geo, final IRI schema, final IRI encodingMethod) { if (schema.equals(GeoConstants.XMLSCHEMA_OGC_WKT)) { return genericStatementWkt(geo); } else if (schema.equals(GeoConstants.XMLSCHEMA_OGC_GML)) { return genericStatementGml(geo, encodingMethod); } throw new Error("schema unsupported: "+schema); }
Example 7
Source File: AbstractSPARQLJSONWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void writeValue(Value value) throws IOException, QueryResultHandlerException { jg.writeStartObject(); if (value instanceof IRI) { jg.writeStringField("type", "uri"); jg.writeStringField("value", ((IRI) value).toString()); } else if (value instanceof BNode) { jg.writeStringField("type", "bnode"); jg.writeStringField("value", ((BNode) value).getID()); } else if (value instanceof Literal) { Literal lit = (Literal) value; if (Literals.isLanguageLiteral(lit)) { jg.writeObjectField("xml:lang", lit.getLanguage().orElse(null)); } else { IRI datatype = lit.getDatatype(); boolean ignoreDatatype = datatype.equals(XMLSchema.STRING) && xsdStringToPlainLiteral(); if (!ignoreDatatype) { jg.writeObjectField("datatype", lit.getDatatype().stringValue()); } } jg.writeObjectField("type", "literal"); jg.writeObjectField("value", lit.getLabel()); } else { throw new TupleQueryResultHandlerException("Unknown Value object type: " + value.getClass()); } jg.writeEndObject(); }
Example 8
Source File: SpinSailConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void initRuleProperties() throws RDF4JException { if (rulePropertyMap != null) { return; } rulePropertyMap = parser.parseRuleProperties(tripleSource); // order rules Set<IRI> remainingRules = new HashSet<>(rulePropertyMap.keySet()); List<IRI> reverseOrder = new ArrayList<>(remainingRules.size()); while (!remainingRules.isEmpty()) { for (Iterator<IRI> ruleIter = remainingRules.iterator(); ruleIter.hasNext();) { IRI rule = ruleIter.next(); boolean isTerminal = true; RuleProperty ruleProperty = rulePropertyMap.get(rule); if (ruleProperty != null) { List<IRI> nextRules = ruleProperty.getNextRules(); for (IRI nextRule : nextRules) { if (!nextRule.equals(rule) && remainingRules.contains(nextRule)) { isTerminal = false; break; } } } if (isTerminal) { reverseOrder.add(rule); ruleIter.remove(); } } } orderedRuleProperties = Lists.reverse(reverseOrder); }
Example 9
Source File: Fact.java From rya with Apache License 2.0 | 5 votes |
/** * Recursively generate a String to show this fact's derivation. */ String explain(final boolean multiline, final String prefix, final Schema schema) { final StringBuilder sb = new StringBuilder(); String sep = " "; if (multiline) { sep = "\n" + prefix; } if (triple == null) { sb.append("(empty)").append(sep); } else { final Resource s = getSubject(); final IRI p = getPredicate(); final Value o = getObject(); sb.append("<").append(s.toString()).append(">").append(sep); sb.append("<").append(p.toString()).append(">").append(sep); sb.append("<").append(o.toString()).append(">"); // Restrictions warrant further explanation if (schema != null && p.equals(RDF.TYPE)) { final Resource objClass = (Resource) o; if (schema.hasRestriction(objClass)) { sb.append(" { "); sb.append(schema.explainRestriction(objClass)); sb.append(" }"); } } sb.append(sep); } if (isInference()) { sb.append(derivation.explain(multiline, prefix, schema)); } else { sb.append("[input]"); } return sb.toString(); }
Example 10
Source File: XMLDatatypeUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Checks whether the supplied datatype is a primitive XML Schema datatype. * * @param datatype * @return true if the datatype is a primitive type */ public static boolean isPrimitiveDatatype(IRI datatype) { return datatype.equals(XMLSchema.DURATION) || datatype.equals(XMLSchema.DATETIME) || datatype.equals(XMLSchema.TIME) || datatype.equals(XMLSchema.DATE) || datatype.equals(XMLSchema.GYEARMONTH) || datatype.equals(XMLSchema.GYEAR) || datatype.equals(XMLSchema.GMONTHDAY) || datatype.equals(XMLSchema.GDAY) || datatype.equals(XMLSchema.GMONTH) || datatype.equals(XMLSchema.STRING) || datatype.equals(XMLSchema.BOOLEAN) || datatype.equals(XMLSchema.BASE64BINARY) || datatype.equals(XMLSchema.HEXBINARY) || datatype.equals(XMLSchema.FLOAT) || datatype.equals(XMLSchema.DECIMAL) || datatype.equals(XMLSchema.DOUBLE) || datatype.equals(XMLSchema.ANYURI) || datatype.equals(XMLSchema.QNAME) || datatype.equals(XMLSchema.NOTATION); }
Example 11
Source File: TurtleWriter.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Internal method that differentiates between the pretty-print and streaming writer cases. * * @param st The next statement to write * @param endRDFCalled True if endRDF has been called before this method is called. This is used to buffer * statements for pretty-printing before dumping them when all statements have been * delivered to us. * @param canShortenSubjectBNode True if, in the current context, we may be able to shorten the subject of this * statement iff it is an instance of {@link BNode}. * @param canShortenObjectBNode True if, in the current context, we may be able to shorten the object of this * statement iff it is an instance of {@link BNode}. */ protected void handleStatementInternal(Statement st, boolean endRDFCalled, boolean canShortenSubjectBNode, boolean canShortenObjectBNode) { Resource subj = st.getSubject(); IRI pred = st.getPredicate(); Value obj = st.getObject(); try { if (subj.equals(lastWrittenSubject)) { if (pred.equals(lastWrittenPredicate)) { // Identical subject and predicate writer.write(","); wrapLine(prettyPrint); } else { // Identical subject, new predicate writer.write(";"); writer.writeEOL(); // Write new predicate writer.decreaseIndentation(); writePredicate(pred); writer.increaseIndentation(); wrapLine(true); path.removeLast(); path.addLast(pred); lastWrittenPredicate = pred; } } else { // New subject closePreviousStatement(); stack.addLast(subj); // Write new subject: if (prettyPrint) { writer.writeEOL(); } writeResource(subj, canShortenSubjectBNode); wrapLine(true); writer.increaseIndentation(); lastWrittenSubject = subj; // Write new predicate writePredicate(pred); wrapLine(true); path.addLast(pred); lastWrittenPredicate = pred; statementClosed = false; writer.increaseIndentation(); } writeValue(obj, canShortenObjectBNode); // Don't close the line just yet. Maybe the next // statement has the same subject and/or predicate. } catch (IOException e) { throw new RDFHandlerException(e); } }
Example 12
Source File: GeoTupleSet.java From rya with Apache License 2.0 | 4 votes |
/** * Returns an iterator over the result set of the contained IndexingExpr. * <p> * Should be thread-safe (concurrent invocation {@link OfflineIterable} this * method can be expected with some query evaluators. */ @Override public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final BindingSet bindings) throws QueryEvaluationException { final IRI funcURI = filterInfo.getFunction(); final SearchFunction searchFunction = new GeoSearchFunctionFactory(conf, geoIndexer).getSearchFunction(funcURI); String queryText; Object arg = filterInfo.getArguments()[0]; if (arg instanceof Value) { queryText = ((Value) arg).stringValue(); } else if (arg instanceof Var) { queryText = bindings.getBinding(((Var) arg).getName()).getValue().stringValue(); } else { throw new IllegalArgumentException("Query text was not resolved"); } if(funcURI.equals(GeoConstants.GEO_SF_NEAR)) { if (filterInfo.getArguments().length > 3) { throw new IllegalArgumentException("Near functions do not support more than four arguments."); } final List<String> valueList = new ArrayList<>(); for (final Object val : filterInfo.getArguments()) { if (val instanceof Value) { valueList.add(((Value)val).stringValue()); } else if (val instanceof Var) { valueList.add(bindings.getBinding(((Var) val).getName()).getValue().stringValue()); } else { throw new IllegalArgumentException("Query text was not resolved"); } } queryText = String.join(NEAR_DELIM, valueList); } else if (filterInfo.getArguments().length > 1) { throw new IllegalArgumentException("Index functions do not support more than two arguments."); } try { final CloseableIteration<BindingSet, QueryEvaluationException> iterrez = IteratorFactory .getIterator(filterInfo.getSpConstraint(), bindings, queryText, searchFunction); return iterrez; } catch (final Exception e) { System.out.println(e.getMessage()); throw e; } }
Example 13
Source File: Schema.java From rya with Apache License 2.0 | 4 votes |
/** * Determine whether a fact is contained in the Schema object * relationships or implied by schema rules. * @return True if this schema contains the semantics of the triple */ public boolean containsTriple(Statement triple) { // The schema certainly doesn't contain it if it's not a // schema-relevant triple at all. if (isSchemaTriple(triple)) { Resource s = triple.getSubject(); IRI p = triple.getPredicate(); Value o = triple.getObject(); // If this is telling us something about a property: if (properties.containsKey(s)) { OwlProperty prop = properties.get(s); // Property types: if (p.equals(RDF.TYPE)) { if ((o.equals(OWL.TRANSITIVEPROPERTY) && prop.isTransitive()) || (o.equals(OWL2.IRREFLEXIVEPROPERTY) && prop.isIrreflexive()) || (o.equals(OWL.SYMMETRICPROPERTY) && prop.isSymmetric()) || (o.equals(OWL2.ASYMMETRICPROPERTY) && prop.isAsymmetric()) || (o.equals(OWL.FUNCTIONALPROPERTY) && prop.isFunctional()) || (o.equals(OWL.INVERSEFUNCTIONALPROPERTY) && prop.isInverseFunctional())) { return true; } } // Relationships with other properties: if ((p.equals(RDFS.SUBPROPERTYOF) && prop.getSuperProperties().contains(o)) || (p.equals(OWL2.PROPERTYDISJOINTWITH) && prop.getDisjointProperties().contains(o)) || (p.equals(OWL.EQUIVALENTPROPERTY) && prop.getEquivalentProperties().contains(o)) || (p.equals(OWL.INVERSEOF) && prop.getInverseProperties().contains(o))) { return true; } // Relationships with classes: if ((p.equals(RDFS.DOMAIN) && prop.getDomain().contains(o)) || (p.equals(RDFS.RANGE) && prop.getRange().contains(o))) { return true; } } // If this is about a class relationship: if (classes.containsKey(s)) { OwlClass subject = classes.get(s); if ((p.equals(OWL.EQUIVALENTCLASS) && (subject.getEquivalentClasses().contains(o))) || (p.equals(OWL.DISJOINTWITH) && (subject.getDisjointClasses().contains(o))) || (p.equals(OWL.COMPLEMENTOF) && (subject.getComplementaryClasses().contains(o))) || (p.equals(RDFS.SUBCLASSOF) && (subject.getSuperClasses().contains(o)))) { return true; } } } return false; }
Example 14
Source File: SchemaCachingRDFSInferencerConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
void processForSchemaCache(Statement statement) { sail.acquireExclusiveWriteLock(); final IRI predicate = statement.getPredicate(); final Value object = statement.getObject(); final Resource subject = statement.getSubject(); if (predicate.equals(RDFS.SUBCLASSOF)) { sail.addSubClassOfStatement(statement); schemaChange = true; } else if (predicate.equals(RDF.TYPE) && object.equals(RDF.PROPERTY)) { sail.addProperty(subject); schemaChange = true; } else if (predicate.equals(RDFS.SUBPROPERTYOF)) { sail.addSubPropertyOfStatement(statement); schemaChange = true; } else if (predicate.equals(RDFS.RANGE)) { sail.addRangeStatement(statement); schemaChange = true; } else if (predicate.equals(RDFS.DOMAIN)) { sail.addDomainStatement(statement); schemaChange = true; } else if (predicate.equals(RDF.TYPE) && object.equals(RDFS.CLASS)) { sail.addSubClassOfStatement( sail.getValueFactory().createStatement(subject, RDFS.SUBCLASSOF, RDFS.RESOURCE)); schemaChange = true; } else if (predicate.equals(RDF.TYPE) && object.equals(RDFS.DATATYPE)) { sail.addSubClassOfStatement( sail.getValueFactory().createStatement(subject, RDFS.SUBCLASSOF, RDFS.LITERAL)); schemaChange = true; } else if (predicate.equals(RDF.TYPE) && object.equals(RDFS.CONTAINERMEMBERSHIPPROPERTY)) { sail.addSubPropertyOfStatement( sail.getValueFactory().createStatement(subject, RDFS.SUBPROPERTYOF, RDFS.MEMBER)); schemaChange = true; } else if (predicate.equals(RDF.TYPE)) { if (!sail.hasType(((Resource) object))) { sail.addType((Resource) object); schemaChange = true; } } if (!sail.hasProperty(predicate)) { sail.addProperty(predicate); schemaChange = true; } }
Example 15
Source File: SourceGenerator.java From mobi with GNU Affero General Public License v3.0 | 4 votes |
/** * TODO - make better? * * @param property The IRI of the property you want to figure the type out for. * @return The JClass representing the type of parameter the property specifies */ private JClass identifyType(final IRI property) { final Set<org.eclipse.rdf4j.model.Value> objects = this.metaModel.filter(property, RDFS.RANGE, null).objects(); if (objects.size() == 1) { final IRI rangeIri = (IRI) objects.iterator().next(); //TODO - think about moving the searching through our ontology and references to the end of this logic. // Handle our types. final Optional<String> optName = getTargetClassFullName(rangeIri); if (optName.isPresent()) { return codeModel.ref(optName.get()); } else if (rangeIri.equals(RDFS.LITERAL)) { return codeModel.ref(Literal.class); } else if (rangeIri.equals(XMLSchema.ANYURI)) { return codeModel.ref(com.mobi.rdf.api.IRI.class); } else if (rangeIri.equals(SimpleValueFactory.getInstance().createIRI(MOBI.IDENTIFIER))) { return codeModel.ref(com.mobi.rdf.api.Resource.class); } else if (rangeIri.equals(RDFS.RESOURCE)) { return codeModel.ref(Value.class); } else if (rangeIri.equals(XMLSchema.STRING)) { return codeModel.ref(String.class); } else if (rangeIri.equals(XMLSchema.BOOLEAN)) { return codeModel.ref(Boolean.class); } else if (rangeIri.equals(XMLSchema.BYTE)) { return codeModel.ref(Byte.class); } else if (rangeIri.equals(XMLSchema.DATE) || rangeIri.equals(XMLSchema.DATETIME)) { return codeModel.ref(OffsetDateTime.class); } else if (rangeIri.equals(XMLSchema.FLOAT)) { return codeModel.ref(Float.class); } else if (rangeIri.equals(XMLSchema.DOUBLE)) { return codeModel.ref(Double.class); } else if (rangeIri.equals(XMLSchema.LONG)) { return codeModel.ref(Long.class); } else if (rangeIri.equals(XMLSchema.INTEGER)) { return codeModel.ref(Integer.class); } else if (rangeIri.equals(OWL.THING)) { return codeModel.ref(Thing.class); } else { LOG.warn("ORM does not know what type to make properties of range '" + rangeIri.stringValue() + "' so we'll use Optional<Value> or Set<Value>"); // TODO - evaluate for NPE potential. return this.metaModel.filter(property, RDF.TYPE, null).objects().contains(OWL.OBJECTPROPERTY) ? codeModel.ref(Thing.class) : codeModel.ref(Value.class); } } else { // TODO - evaluate for NPE potential. LOG.warn("Property '" + property + "' " + (objects.isEmpty() ? "doesn't specify a range." : "Specifies multiple ranges")); return this.metaModel.filter(property, RDF.TYPE, null).objects().contains(OWL.OBJECTPROPERTY) ? codeModel.ref(Thing.class) : codeModel.ref(Value.class); } }
Example 16
Source File: LocalReasoner.java From rya with Apache License 2.0 | 4 votes |
/** * Determine whether a fact is a triple which might be used in some join * rule for its subject and/or object. */ public static Relevance relevantJoinRule(Fact fact, Schema schema) { // If this is schema information, we know it's already // contained in the schema object. if (Schema.isSchemaTriple(fact.getTriple())) { return Relevance.NONE; } // Otherwise, consider the semantics of the statement: IRI predIRI = fact.getPredicate(); Value object = fact.getObject(); boolean relevantToSubject = false; boolean relevantToObject = false; // Literals don't get reasoners, so determine whether object is a uri: boolean literalObject = object instanceof Literal; // Type statements can be joined if... if (predIRI.equals(RDF.TYPE)) { Resource typeIRI = (Resource) fact.getObject(); if (schema.hasClass(typeIRI)) { OwlClass c = schema.getClass(typeIRI); // 1. the type is a property restriction if (!c.getOnProperty().isEmpty() // 2. the type is relevant to a property restriction || !c.getSvfRestrictions().isEmpty() || !c.getAvfRestrictions().isEmpty() || !c.getQCRestrictions().isEmpty() // 3. the type has complementary/disjoint types || !c.getDisjointClasses().isEmpty() || !c.getComplementaryClasses().isEmpty()) { relevantToSubject = true; } } } // If the schema knows about the property: if (schema.hasProperty(predIRI)) { OwlProperty prop = schema.getProperty(predIRI); // transitivity: relevant to both if (prop.isTransitive()) { relevantToSubject = true; relevantToObject = !literalObject; } else { // disjoint properties: relevant to subject if (!prop.getDisjointProperties().isEmpty()) { relevantToSubject = true; } // Property restrictions: possibly relevant to either for (Resource rURI : prop.getRestrictions()) { OwlClass r = schema.getClass(rURI); // allValuesFrom requires a join on the subject // (if <subject type rURI>, infer object's type) if (!r.allValuesFrom().isEmpty()) { relevantToSubject = true; } // someValuesFrom requires a join on the object // (if the object is the appropriate type, infer rURI) // max cardinality requires a join on the subject if (!literalObject && (r.getMaxCardinality() >= 0 || r.getMaxQualifiedCardinality() >= 0 || !r.someValuesFrom().isEmpty())) { relevantToObject = true; } if (relevantToSubject && (relevantToObject || literalObject)) { break; } } } } return Relevance.get(relevantToSubject, relevantToObject); }
Example 17
Source File: RDFWriterTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void testPerformanceInternal(boolean storeParsedStatements) throws Exception { Random prng = new Random(this.getClass().getName().hashCode()); Model model = new LinkedHashModel(); for (int i = 0; i < 10000; i++) { Value obj = potentialObjects.get(prng.nextInt(potentialObjects.size())); if (obj == litBigPlaceholder) { StringBuilder big = new StringBuilder(); int len = 25000 + prng.nextInt(5000); for (int j = 0; j < len; j++) { big.append(((char) (32 + prng.nextInt(90)))); } obj = vf.createLiteral(big.toString()); } IRI pred = potentialPredicates.get(prng.nextInt(potentialPredicates.size())); while (obj instanceof Triple && pred.equals(RDF.TYPE)) { // Avoid statements "x rdf:type <<triple>>" as those use the shorter syntax in RDFXMLPrettyWriter // and the writer produces invalid XML in that case. Even though the RDF* triples are encoded as // valid IRIs, XML has limitations on what characters may form an XML tag name and thus a limitation // on what IRIs may be used in predicates (predicates are XML tags) or the short form of rdf:type // (where the type is also an XML tag). obj = potentialObjects.get(prng.nextInt(potentialObjects.size())); } model.add(potentialSubjects.get(prng.nextInt(potentialSubjects.size())), pred, obj); } logger.debug("Test class: " + this.getClass().getName()); logger.debug("Test statements size: " + model.size() + " (" + rdfWriterFactory.getRDFFormat() + ")"); assertFalse("Did not generate any test statements", model.isEmpty()); File testFile = tempDir.newFile("performancetest." + rdfWriterFactory.getRDFFormat().getDefaultFileExtension()); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(testFile))) { long startWrite = System.currentTimeMillis(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(out); setupWriterConfig(rdfWriter.getWriterConfig()); // Test prefixed URIs for only some of the URIs available rdfWriter.startRDF(); rdfWriter.handleNamespace(RDF.PREFIX, RDF.NAMESPACE); rdfWriter.handleNamespace(SKOS.PREFIX, SKOS.NAMESPACE); rdfWriter.handleNamespace(FOAF.PREFIX, FOAF.NAMESPACE); rdfWriter.handleNamespace(EARL.PREFIX, EARL.NAMESPACE); rdfWriter.handleNamespace("ex", exNs); for (Statement nextSt : model) { rdfWriter.handleStatement(nextSt); } rdfWriter.endRDF(); long endWrite = System.currentTimeMillis(); logger.debug( "Write took: " + (endWrite - startWrite) + " ms (" + rdfWriterFactory.getRDFFormat() + ")"); logger.debug("File size (bytes): " + testFile.length()); } try (InputStream in = new BufferedInputStream(new FileInputStream(testFile))) { RDFParser rdfParser = rdfParserFactory.getParser(); setupParserConfig(rdfParser.getParserConfig()); rdfParser.setValueFactory(vf); Model parsedModel = new LinkedHashModel(); if (storeParsedStatements) { rdfParser.setRDFHandler(new StatementCollector(parsedModel)); } long startParse = System.currentTimeMillis(); rdfParser.parse(in, "foo:bar"); long endParse = System.currentTimeMillis(); logger.debug( "Parse took: " + (endParse - startParse) + " ms (" + rdfParserFactory.getRDFFormat() + ")"); if (storeParsedStatements) { if (model.size() != parsedModel.size()) { if (model.size() < 1000) { boolean originalIsSubset = Models.isSubset(model, parsedModel); boolean parsedIsSubset = Models.isSubset(parsedModel, model); logger.debug("originalIsSubset=" + originalIsSubset); logger.debug("parsedIsSubset=" + parsedIsSubset); // System.out.println("Written statements=>"); // IOUtils.writeLines(IOUtils.readLines(new FileInputStream(testFile)), "\n", System.out); // System.out.println("Parsed statements=>"); // Rio.write(parsedModel, System.out, RDFFormat.NQUADS); } } assertEquals( "Unexpected number of statements, expected " + model.size() + " found " + parsedModel.size(), model.size(), parsedModel.size()); if (rdfParser.getRDFFormat().supportsNamespaces()) { assertTrue("Expected at least 5 namespaces, found " + parsedModel.getNamespaces().size(), parsedModel.getNamespaces().size() >= 5); assertEquals(exNs, parsedModel.getNamespace("ex").get().getName()); } } } }
Example 18
Source File: QueryEvaluationUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 2 votes |
/** * Checks whether the supplied literal is a "string literal". A "string literal" is either a simple literal, a plain * literal with language tag, or a literal with datatype xsd:string. * * @see <a href="http://www.w3.org/TR/sparql11-query/#func-string">SPARQL Functions on Strings Documentation</a> */ public static boolean isStringLiteral(Literal l) { IRI datatype = l.getDatatype(); return Literals.isLanguageLiteral(l) || datatype.equals(XMLSchema.STRING); }
Example 19
Source File: XMLDatatypeUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 2 votes |
/** * Checks whether the supplied datatype is equal to xsd:duration, xsd:dayTimeDuration, xsd:yearMonthDuration. These * are the datatypes that represents durations. * * @see Duration * @param datatype * @return true if it is a duration type */ public static boolean isDurationDatatype(IRI datatype) { return datatype.equals(XMLSchema.DURATION) || datatype.equals(XMLSchema.DAYTIMEDURATION) || datatype.equals(XMLSchema.YEARMONTHDURATION); }
Example 20
Source File: XMLDatatypeUtil.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 2 votes |
/** * Checks whether the supplied datatype is equal to xsd:decimal or one of the built-in datatypes that is derived * from xsd:decimal. * * @param datatype * @return true if it is a decimal datatype */ public static boolean isDecimalDatatype(IRI datatype) { return datatype.equals(XMLSchema.DECIMAL) || isIntegerDatatype(datatype); }