org.eclipse.rdf4j.model.vocabulary.XMLSchema Java Examples

The following examples show how to use org.eclipse.rdf4j.model.vocabulary.XMLSchema. 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: SmartUriAdapter.java    From rya with Apache License 2.0 6 votes vote down vote up
private static IRI determineType(final String data) {
    if (Ints.tryParse(data) != null) {
        return XMLSchema.INTEGER;
    } else if (Doubles.tryParse(data) != null) {
        return XMLSchema.DOUBLE;
    } else if (Floats.tryParse(data) != null) {
        return XMLSchema.FLOAT;
    } else if (isShort(data)) {
        return XMLSchema.SHORT;
    } else if (Longs.tryParse(data) != null) {
        return XMLSchema.LONG;
    } if (Boolean.parseBoolean(data)) {
        return XMLSchema.BOOLEAN;
    } else if (isByte(data)) {
        return XMLSchema.BYTE;
    } else if (isDate(data)) {
        return XMLSchema.DATETIME;
    } else if (isUri(data)) {
        return XMLSchema.ANYURI;
    }

    return XMLSchema.STRING;
}
 
Example #2
Source File: XMLDatatypeMathUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static IRI getDatatypeForDuration(Duration duration) {
	// Could not be implemented with Duration.getXMLSchemaType that is too strict ("P1Y" is considered invalid)

	boolean yearSet = duration.isSet(DatatypeConstants.YEARS);
	boolean monthSet = duration.isSet(DatatypeConstants.MONTHS);
	boolean daySet = duration.isSet(DatatypeConstants.DAYS);
	boolean hourSet = duration.isSet(DatatypeConstants.HOURS);
	boolean minuteSet = duration.isSet(DatatypeConstants.MINUTES);
	boolean secondSet = duration.isSet(DatatypeConstants.SECONDS);

	if (!yearSet && !monthSet) {
		return XMLSchema.DAYTIMEDURATION;
	}
	if (!daySet && !hourSet && !minuteSet && !secondSet) {
		return XMLSchema.YEARMONTHDURATION;
	}
	return XMLSchema.DURATION;
}
 
Example #3
Source File: ValueTypeSupportRegistryImpl.java    From inception with Apache License 2.0 6 votes vote down vote up
private String getDataType(KBStatement aStatement, KBProperty aProperty)
{
    String datatype = null;
    
    if (aStatement.getValue() != null) {
        Class<?> clazz = aStatement.getValue().getClass();
        IRI type = DefaultDatatypeMapper.getDatatypeURI(clazz);

        // Mapping fails for NaiveIRI class, so check manually
        // if the value is an instance of IRI
        if (type == null && aStatement.getValue() instanceof IRI) {
            type = XMLSchema.ANYURI;
        }
        datatype = type != null ? type.stringValue() : null;
    }
    
    if (datatype == null && aProperty != null && aProperty.getRange() != null) {
        return aProperty.getRange();
    }
    
    if (datatype == null) {
        datatype = XMLSchema.STRING.stringValue();
    }
    
    return datatype;
}
 
Example #4
Source File: DistanceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test distance between two cities, in meters.
 *
 * @throws IOException
 */
@Test
public void testDistanceAmBxl() throws IOException {
	BindingSet bs = GeoSPARQLTests.getBindingSet("distance.rq");

	assertNotNull("Bindingset is null", bs);

	Value value = bs.getBinding("dist").getValue();
	assertNotNull("Binded value is null", value);

	assertTrue("Value is not a literal", value instanceof Literal);
	Literal l = (Literal) value;
	assertTrue("Literal not of type double", l.getDatatype().equals(XMLSchema.DOUBLE));

	assertEquals("Distance Amsterdam-Brussels not correct", 173, l.doubleValue() / 1000, 0.5);
}
 
Example #5
Source File: HalyardValueExprEvaluation.java    From Halyard with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate a {@link Datatype} node
 * @param node the node to evaluate
 * @param bindings the set of named value bindings
 * @return a {@link Literal} representing the evaluation of the argument of the {@link Datatype}.
 * @throws ValueExprEvaluationException
 * @throws QueryEvaluationException
 */
private Value evaluate(Datatype node, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException {
    Value v = evaluate(node.getArg(), bindings);
    if (v instanceof Literal) {
        Literal literal = (Literal) v;
        if (literal.getDatatype() != null) {
            // literal with datatype
            return literal.getDatatype();
        } else if (literal.getLanguage() != null) {
            return RDF.LANGSTRING;
        } else {
            // simple literal
            return XMLSchema.STRING;
        }
    }
    throw new ValueExprEvaluationException();
}
 
Example #6
Source File: EvaluationStrategyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDatetimeSubtypesExtended() {
	ValueFactory vf = extendedRepo.getValueFactory();

	try (RepositoryConnection conn = extendedRepo.getConnection()) {
		Literal l1 = vf.createLiteral("2009", XMLSchema.GYEAR);
		Literal l2 = vf.createLiteral("2009-01", XMLSchema.GYEARMONTH);
		IRI s1 = vf.createIRI("urn:s1");
		IRI s2 = vf.createIRI("urn:s2");
		conn.add(s1, RDFS.LABEL, l1);
		conn.add(s2, RDFS.LABEL, l2);

		String query = "SELECT * WHERE { ?s rdfs:label ?l . FILTER(?l >= \"2008\"^^xsd:gYear) }";

		List<BindingSet> result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate());
		assertEquals(2, result.size());
	}
}
 
Example #7
Source File: StrBeforeTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testEvaluate4a() {

	Literal leftArg = f.createLiteral("foobar");
	Literal rightArg = f.createLiteral("b", XMLSchema.STRING);

	try {
		Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg);

		assertEquals("foo", result.getLabel());
		assertEquals(XMLSchema.STRING, result.getDatatype());

	} catch (ValueExprEvaluationException e) {
		fail(e.getMessage());
	}
}
 
Example #8
Source File: ValueComparatorTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Tests whether various numerics are properly sorted in a list with mixed value types.
 */
@Test
public void testOrder2() throws Exception {
	Literal en4 = vf.createLiteral("4", "en");
	Literal int10 = vf.createLiteral(10);
	Literal int9 = vf.createLiteral(9);
	Literal plain9 = vf.createLiteral("9");
	Literal integer5 = vf.createLiteral("5", XMLSchema.INTEGER);
	Literal float9 = vf.createLiteral(9f);
	Literal plain4 = vf.createLiteral("4");
	Literal plain10 = vf.createLiteral("10");

	List<Literal> valueList = Arrays.asList(en4, int10, int9, plain9, integer5, float9, plain4, plain10);
	Collections.sort(valueList, cmp);

	assertTrue(valueList.indexOf(integer5) < valueList.indexOf(float9));
	assertTrue(valueList.indexOf(integer5) < valueList.indexOf(int9));
	assertTrue(valueList.indexOf(integer5) < valueList.indexOf(int10));
	assertTrue(valueList.indexOf(float9) < valueList.indexOf(int10));
	assertTrue(valueList.indexOf(int9) < valueList.indexOf(int10));
	assertTrue(valueList.indexOf(int9) < valueList.indexOf(int10));
}
 
Example #9
Source File: ValueFactoryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.rdf4j.model.impl.AbstractValueFactory#createLiteral(javax.xml.datatype.XMLGregorianCalendar)}
 * .
 */
@Test
public void testCreateLiteralXMLGregorianCalendar() {
	GregorianCalendar c = new GregorianCalendar();
	c.setTime(new Date());
	try {
		XMLGregorianCalendar xmlGregCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
		Literal l = f.createLiteral(xmlGregCalendar);
		assertNotNull(l);
		assertEquals(l.getDatatype(), XMLSchema.DATETIME);
		// TODO check lexical value?
	} catch (DatatypeConfigurationException e) {
		e.printStackTrace();
		fail("Could not instantiate javax.xml.datatype.DatatypeFactory");
	}
}
 
Example #10
Source File: DecimalFormat.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Value evaluate(ValueFactory valueFactory, Value arg1, Value arg2) throws ValueExprEvaluationException {
	if (!(arg1 instanceof Literal) || !(arg2 instanceof Literal)) {
		throw new ValueExprEvaluationException("Both arguments must be literals");
	}
	Literal number = (Literal) arg1;
	Literal format = (Literal) arg2;

	java.text.DecimalFormat formatter = new java.text.DecimalFormat(format.getLabel());
	String value;
	if (XMLSchema.INT.equals(number.getDatatype()) || XMLSchema.LONG.equals(number.getDatatype())
			|| XMLSchema.SHORT.equals(number.getDatatype()) || XMLSchema.BYTE.equals(number.getDatatype())) {
		value = formatter.format(number.longValue());
	} else if (XMLSchema.DECIMAL.equals(number.getDatatype())) {
		value = formatter.format(number.decimalValue());
	} else if (XMLSchema.INTEGER.equals(number.getDatatype())) {
		value = formatter.format(number.integerValue());
	} else {
		value = formatter.format(number.doubleValue());
	}
	return valueFactory.createLiteral(value);
}
 
Example #11
Source File: HalyardSummary.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Override
protected void setup(Context context) throws IOException, InterruptedException {
    this.conf = context.getConfiguration();
    this.splitOutput = conf.get(TARGET).contains("{0}");
    this.outputLimit = conf.getLong("mapreduce.input.fileinputformat.split.maxsize", Long.MAX_VALUE);
    String ng = conf.get(TARGET_GRAPH);
    this.namedGraph = ng == null ? null : SVF.createIRI(ng);
    this.decimationFactor = conf.getInt(DECIMATION_FACTOR, DEFAULT_DECIMATION_FACTOR);
    sail = new HBaseSail(conf, conf.get(SOURCE), false, 0, true, 0, null, null);
    sail.initialize();
    setupOutput();
    write(CARDINALITY, RDF.TYPE, RDF.PROPERTY);
    write(CARDINALITY, RDFS.LABEL, SVF.createLiteral("cardinality"));
    write(CARDINALITY, RDFS.COMMENT, SVF.createLiteral("cardinality is positive integer [0..63], it is a binary logarithm of the pattern occurences (2^63 is the maximum allowed number of occurences)"));
    write(CARDINALITY, RDFS.RANGE, XMLSchema.INTEGER);
}
 
Example #12
Source File: ConcatTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void stringLiteralHandling() {
	Literal result = concatFunc.evaluate(vf, foo, bar);

	assertThat(result.stringValue()).isEqualTo("foobar");
	assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING);
	assertThat(result.getLanguage().isPresent()).isFalse();
}
 
Example #13
Source File: DateTimeRyaTypeResolverTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
  public void testGarbageIn() throws Exception {
      String currentTime = "Blablabla";
RyaType ryaType = new RyaType(XMLSchema.DATETIME, currentTime );
Throwable threw=null;
try {
	new DateTimeRyaTypeResolver().serialize(ryaType);
} catch (java.lang.IllegalArgumentException exception) {
	threw = exception;
}
assertNotNull("Expected to catch bad format message.",threw);
assertEquals("Caught bad format message.","Invalid format: \"Blablabla\"", threw.getMessage());
  }
 
Example #14
Source File: ConcatTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void mixedLiteralHandling() {
	Literal result = concatFunc.evaluate(vf, foo, bar_en);

	assertThat(result.stringValue()).isEqualTo("foobar");
	assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING);
	assertThat(result.getLanguage().isPresent()).isFalse();
}
 
Example #15
Source File: TestDateTimeCast.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testCastPlainLiteral() {
	Literal plainLit = f.createLiteral("1999-09-09T00:00:01");
	try {
		Literal result = dtCast.evaluate(f, plainLit);
		assertNotNull(result);
		assertEquals(XMLSchema.DATETIME, result.getDatatype());
	} catch (ValueExprEvaluationException e) {
		fail(e.getMessage());
	}
}
 
Example #16
Source File: GroupIteratorTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testAvgEmptySet() throws QueryEvaluationException {
	Group group = new Group(EMPTY_ASSIGNMENT);
	group.addGroupElement(new GroupElem("avg", new Avg(new Var("a"))));
	GroupIterator gi = new GroupIterator(evaluator, group, EmptyBindingSet.getInstance());

	assertThat(gi.next().getBinding("avg").getValue())
			.describedAs("AVG on empty set should result in 0")
			.isEqualTo(vf.createLiteral("0", XMLSchema.INTEGER));
}
 
Example #17
Source File: QueryClauseLikeGenerator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private QueryBuilder getQueryBuilder(Attribute attr, String fieldName, Object queryValue) {
  if (isTaggedType(attr, XMLSchema.TOKEN)) {
    return QueryBuilders.wildcardQuery(fieldName, format("*%s*", queryValue));
  } else {
    return QueryBuilders.matchPhrasePrefixQuery(fieldName, queryValue)
        .maxExpansions(50)
        .slop(10)
        .analyzer(DEFAULT_ANALYZER);
  }
}
 
Example #18
Source File: StringLiteralValueSupport.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accepts(KBStatement aStatement, KBProperty aProperty)
{
    // accept statements with null as value so that the StringEditor appears as default case
    if (aStatement.getValue() == null) {
        return false;
    }
    IRI iri = DefaultDatatypeMapper.getDatatypeURI((aStatement.getValue()).getClass());
    // Conditions for different datatype URI apart from String
    boolean accept = XMLSchema.STRING.equals(iri);
    
    return iri != null && accept ;
}
 
Example #19
Source File: SPARQLTSVCustomTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Only Literals with the XML Schema numeric types should be simplified.
 * <p>
 * NOTE: This will fail when using RDF-1.1, as the datatype {@link XMLSchema#STRING} is implied and hence is not
 * generally represented.
 *
 * @throws Exception
 */
@Ignore("This test does not work with RDF-1.1")
@Test
public void testSES2126QuotedLiteralIntegerAsStringExplicitType() throws Exception {
	List<String> bindingNames = Arrays.asList("test");
	TupleQueryResult tqr = new IteratingTupleQueryResult(bindingNames,
			Arrays.asList(new ListBindingSet(bindingNames,
					SimpleValueFactory.getInstance().createLiteral("1", XMLSchema.STRING))));
	String result = writeTupleResult(tqr);
	assertEquals("?test\n\"1\"^^<http://www.w3.org/2001/XMLSchema#string>\n", result);
}
 
Example #20
Source File: MongoStatementMetadataNodeIT.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if the StatementMetadataNode joins BindingSet correctly for
 * variables appearing in metadata statements. In this case, the metadata
 * statements are (_:blankNode <http://createdOn 2017-01-04 ) and
 * (_:blankNode <http://createdBy> ?y). The variable ?y appears as the
 * object in the above metadata statement and its values are joined to the
 * constraint BindingSets in the example below.
 */
@Test
public void simpleQueryWithBindingSetJoinOnProperty() throws Exception {
    final MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();
        final StatementMetadata metadata = new StatementMetadata();
        metadata.addMetadata(new RyaIRI("http://createdBy"), new RyaType("Joe"));
        metadata.addMetadata(new RyaIRI("http://createdOn"), new RyaType(XMLSchema.DATE, "2017-01-04"));

        final RyaStatement statement1 = new RyaStatement(new RyaIRI("http://Joe"), new RyaIRI("http://worksAt"),
                new RyaType("CoffeeShop"), new RyaIRI("http://context"), "", metadata);
        dao.add(statement1);

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq = parser.parseQuery(query, null);
        final List<StatementPattern> spList = StatementPatternCollector.process(pq.getTupleExpr());
        final StatementMetadataNode<MongoDBRdfConfiguration> node = new StatementMetadataNode<>(spList, conf);

        final QueryBindingSet bsConstraint = new QueryBindingSet();
        bsConstraint.addBinding("x", VF.createLiteral("CoffeeShop"));
        bsConstraint.addBinding("y", VF.createLiteral("Doug"));

        final CloseableIteration<BindingSet, QueryEvaluationException> iteration = node.evaluate(bsConstraint);

        final List<BindingSet> bsList = new ArrayList<>();
        while (iteration.hasNext()) {
            bsList.add(iteration.next());
        }

        Assert.assertEquals(0, bsList.size());
        dao.delete(statement1, conf);
    } finally {
        dao.destroy();
    }
}
 
Example #21
Source File: LiteralsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.rdf4j.model.util.Literals#createLiteral(org.eclipse.rdf4j.model.ValueFactory, java.lang.Object)}
 * .
 */
@Test
public void testCreateLiteralObjectDouble() throws Exception {

	Object obj = new Double(42);
	Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj);
	assertNotNull(l);
	assertEquals(l.getDatatype(), XMLSchema.DOUBLE);
	assertEquals(l.getLabel(), "42.0");

}
 
Example #22
Source File: LowerCase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length != 1) {
		throw new ValueExprEvaluationException("LCASE requires exactly 1 argument, got " + args.length);
	}

	if (args[0] instanceof Literal) {
		Literal literal = (Literal) args[0];

		// LowerCase function accepts only string literals.
		if (QueryEvaluationUtil.isStringLiteral(literal)) {
			String lexicalValue = literal.getLabel().toLowerCase();
			Optional<String> language = literal.getLanguage();

			if (language.isPresent()) {
				return valueFactory.createLiteral(lexicalValue, language.get());
			} else if (XMLSchema.STRING.equals(literal.getDatatype())) {
				return valueFactory.createLiteral(lexicalValue, XMLSchema.STRING);
			} else {
				return valueFactory.createLiteral(lexicalValue);
			}
		} else {
			throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]);
		}
	} else {
		throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]);
	}

}
 
Example #23
Source File: MongoEntityStorageIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void update() throws Exception {
    final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME);

    // Store Alice in the repository.
    final Entity alice = Entity.builder()
            .setSubject( new RyaIRI("urn:SSN/111-11-1111") )
            .setExplicitType(new RyaIRI("urn:person"))
            .setProperty(new RyaIRI("urn:person"), new Property(new RyaIRI("urn:name"), new RyaType(XMLSchema.STRING, "Alice")))
            .setProperty(new RyaIRI("urn:person"), new Property(new RyaIRI("urn:age"), new RyaType(XMLSchema.INT, "30")))
            .setProperty(new RyaIRI("urn:person"), new Property(new RyaIRI("urn:eye"), new RyaType(XMLSchema.STRING, "blue")))
            .build();

    storage.create(alice);

    // Show Alice was stored.
    Optional<Entity> latest = storage.get(new RyaIRI("urn:SSN/111-11-1111"));
    assertEquals(alice, latest.get());

    // Change Alice's eye color to brown.
    final Entity updated = Entity.builder(alice)
            .setVersion(latest.get().getVersion() + 1)
            .setProperty(new RyaIRI("urn:person"), new Property(new RyaIRI("urn:eye"), new RyaType(XMLSchema.STRING, "brown")))
            .build();

    storage.update(alice, updated);

    // Fetch the Alice object and ensure it has the new value.
    latest = storage.get(new RyaIRI("urn:SSN/111-11-1111"));

    assertEquals(updated, latest.get());
}
 
Example #24
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
DataVisitor() {
	appendPrefix(RDF.PREFIX, RDF.NAMESPACE);
	appendPrefix(RDFS.PREFIX, RDFS.NAMESPACE);
	appendPrefix(SESAME.PREFIX, SESAME.NAMESPACE);
	appendPrefix(OWL.PREFIX, OWL.NAMESPACE);
	appendPrefix(XMLSchema.PREFIX, XMLSchema.NAMESPACE);
	appendPrefix(FN.PREFIX, FN.NAMESPACE);
	buf.append(" ");
}
 
Example #25
Source File: KafkaExportIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void count() throws Exception {
    // A query that counts the number of unique items that are in the inventory.
    final String sparql =
            "SELECT (count(?item) as ?itemCount) { " +
                "?item <urn:id> ?id . " +
            "}";

    // Create the Statements that will be loaded into Rya.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Collection<Statement> statements = Sets.newHashSet(
            // Three that are part of the count.
            vf.createStatement(vf.createIRI("urn:apple"), vf.createIRI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),
            vf.createStatement(vf.createIRI("urn:gum"), vf.createIRI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),
            vf.createStatement(vf.createIRI("urn:sandwich"), vf.createIRI("urn:id"), vf.createLiteral(UUID.randomUUID().toString())),

            // One that is not.
            vf.createStatement(vf.createIRI("urn:sandwich"), vf.createIRI("urn:price"), vf.createLiteral(3.99)));

    // Create the PCJ in Fluo and load the statements into Rya.
    final String pcjId = loadDataAndCreateQuery(sparql, statements);

    // Create the expected results of the SPARQL query once the PCJ has been computed.
    final MapBindingSet expectedResult = new MapBindingSet();
    expectedResult.addBinding("itemCount", vf.createLiteral("3", XMLSchema.INTEGER));

    // Ensure the last result matches the expected result.
    final VisibilityBindingSet result = readLastResult(pcjId);
    assertEquals(expectedResult, result);
}
 
Example #26
Source File: KryoVisibilityBindingSetSerializer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static Value makeValue(final String valueString, final IRI typeURI) {
    // Convert the String Value into a Value.
    if (typeURI.equals(XMLSchema.ANYURI)) {
        return VF.createIRI(valueString);
    } else {
        return VF.createLiteral(valueString, typeURI);
    }
}
 
Example #27
Source File: RyaToRdfConversions.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a {@link RyaType} into a {@link Literal} representation of the
 * {@code ryaType}.
 * @param ryaType the {@link RyaType} to convert.
 * @return the {@link Literal} representation of the {@code ryaType}.
 */
public static Literal convertLiteral(final RyaType ryaType) {
    if (XMLSchema.STRING.equals(ryaType.getDataType())) {
        return VF.createLiteral(ryaType.getData());
    } else if (RDF.LANGSTRING.equals(ryaType.getDataType())) {
        final String data = ryaType.getData();
        final String language = ryaType.getLanguage();
        if (language != null && Literals.isValidLanguageTag(language)) {
            return VF.createLiteral(data, language);
        } else {
            return VF.createLiteral(data, LiteralLanguageUtils.UNDETERMINED_LANGUAGE);
        }
    }
    return VF.createLiteral(ryaType.getData(), ryaType.getDataType());
}
 
Example #28
Source File: XMLDatatypeUtilTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testNormalize() {
	assertEquals("-1.0E-1", XMLDatatypeUtil.normalize("-0.1", XMLSchema.DOUBLE));
	assertEquals("1.0E-1", XMLDatatypeUtil.normalize("0.1", XMLSchema.DOUBLE));
	assertEquals("1.001E2", XMLDatatypeUtil.normalize("100.1", XMLSchema.DOUBLE));
	assertEquals("1.011E2", XMLDatatypeUtil.normalize("101.1", XMLSchema.DOUBLE));
	assertEquals("-1.011E2", XMLDatatypeUtil.normalize("-101.1", XMLSchema.DOUBLE));
}
 
Example #29
Source File: TagPopulatorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testPopulate() {
  when(tagFactory.create("token")).thenReturn(token);
  when(tagFactory.create("case-sensitive")).thenReturn(caseSensitive);
  when(dataService.getRepository(TagMetadata.TAG, Tag.class)).thenReturn(tagRepository);

  tagPopulator.populate();

  verify(tagRepository).upsertBatch(List.of(token, caseSensitive));
  verify(token).setRelationIri(RDF.TYPE.toString());
  verify(token).setObjectIri(XMLSchema.TOKEN.toString());

  verify(caseSensitive).setRelationIri(RDF.TYPE.toString());
  verify(caseSensitive).setObjectIri(Vocabulary.CASE_SENSITIVE.toString());
}
 
Example #30
Source File: LiteralsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.rdf4j.model.util.Literals#createLiteralOrFail(org.eclipse.rdf4j.model.ValueFactory, java.lang.Object)}
 * .
 */
@Test
public void testCreateLiteralOrFailObjectShort() throws Exception {

	Object obj = Short.parseShort("42");
	Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj);
	assertNotNull(l);
	assertEquals(l.getDatatype(), XMLSchema.SHORT);
	assertEquals("42", l.getLabel());

}