Java Code Examples for org.openrdf.model.Literal#getLanguage()

The following examples show how to use org.openrdf.model.Literal#getLanguage() . 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: StrlangBOp.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IV get(final IBindingSet bs) throws SparqlTypeErrorException {

    final Literal lit = getAndCheckLiteralValue(0, bs);
    
    if (lit.getDatatype() != null || lit.getLanguage() != null) {
        throw new SparqlTypeErrorException();
    }

    final Literal l = getAndCheckLiteralValue(1, bs);
    String label = lit.getLabel();
    String langLit = l.getLabel();
    final BigdataLiteral str = getValueFactory().createLiteral(label, langLit);
    return super.asIV(str, bs);

}
 
Example 2
Source File: SparqlEvaluator.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private void writeLiteral(StringBuilder sb, Value value) {
	Literal lit = (Literal) value;
	sb.append("\"");
	String label = value.stringValue();
	sb.append(encodeString(label));
	sb.append("\"");
	if (lit.getDatatype() != null) {
		// Append the literal's datatype (possibly written as an
		// abbreviated URI)
		sb.append("^^");
		writeURI(sb, lit.getDatatype());
	}
	if (lit.getLanguage() != null) {
		// Append the literal's language
		sb.append("@");
		sb.append(lit.getLanguage());
	}
}
 
Example 3
Source File: NTriplesUtilNoEscape.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public static void append(Literal lit, Appendable appendable)
        throws IOException
{
    // Do some character escaping on the label:
    appendable.append("\"");
    appendable.append(lit.getLabel());
    appendable.append("\"");

    if (lit.getDatatype() != null) {
        // Append the literal's datatype
        appendable.append("^^");
        appendable.append("<").append(lit.getDatatype().stringValue()).append(">");
    }
    else if (lit.getLanguage() != null) {
        // Append the literal's language
        appendable.append("@");
        appendable.append(lit.getLanguage());
    }
}
 
Example 4
Source File: AST2SPARQLUtil.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public String toExternal(final Literal lit) {

        final String label = lit.getLabel();
        
        final String languageCode = lit.getLanguage();
        
        final URI datatypeURI = lit.getDatatype();

        final String datatypeStr = datatypeURI == null ? null
                : toExternal(datatypeURI);

        final StringBuilder sb = new StringBuilder((label.length() + 2)
                + (languageCode != null ? (languageCode.length() + 1) : 0)
                + (datatypeURI != null ? datatypeStr.length() + 2 : 0));

        sb.append('"');
        sb.append(SPARQLUtil.encodeString(label));
        sb.append('"');

        if (languageCode != null) {
            sb.append('@');
            sb.append(languageCode);
        }

        if (datatypeURI != null) {
            sb.append("^^");
            sb.append(datatypeStr);
        }

        return sb.toString();

    }
 
Example 5
Source File: CumulusRDFValueFactory.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CumulusRDF native value from a given {@link Value}.
 * 
 * @param value the incoming {@link Value}.
 * @return a CumulusRDF native value.
 */
public static Value makeNativeValue(final Value value) {
	if (value == null || value instanceof INativeCumulusValue) {
		return value;
	}

	if (value instanceof URI) {
		return new NativeCumulusURI(value.stringValue());
	} else if (value instanceof Literal) {
		
		final Literal lit = (Literal) value;
		final String label = lit.getLabel(), language = lit.getLanguage();
		final URI datatype = lit.getDatatype();

		if (language != null) {
			return new NativeCumulusLiteral(label, language);
		} else if (datatype != null) {
			return new NativeCumulusLiteral(label, datatype);
		} else {
			return new NativeCumulusLiteral(label);
		}
		
	} else if (value instanceof BNode) {
		return new NativeCumulusBNode(value.stringValue());
	}

	return value;
}
 
Example 6
Source File: SPARQLJSONWriterBase.java    From database with GNU General Public License v2.0 5 votes vote down vote up
protected void writeValue(Value value)
	throws IOException, QueryResultHandlerException
{
	jg.writeStartObject();

	if (value instanceof URI) {
		jg.writeStringField("type", "uri");
		jg.writeStringField("value", ((URI)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;

		// TODO: Implement support for
		// BasicWriterSettings.RDF_LANGSTRING_TO_LANG_LITERAL here
		if (lit.getLanguage() != null) {
			jg.writeObjectField("xml:lang", lit.getLanguage());
		}
		// TODO: Implement support for
		// BasicWriterSettings.XSD_STRING_TO_PLAIN_LITERAL here
		if (lit.getDatatype() != null) {
			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 7
Source File: LiteralManager.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public Object createObject(Literal literal) {
	URI datatype = literal.getDatatype();
	if (datatype == null) {
		if (literal.getLanguage() == null) {
			datatype = STRING;
		} else {
			datatype = LANG_STRING;
		}
	}
	Marshall<?> marshall = findMarshall(datatype);
	return marshall.deserialize(literal);
}
 
Example 8
Source File: TurtleValueUtils.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private String writeLiteral(Literal lit) {
	StringBuilder builder=new StringBuilder();
	String label = lit.getLabel();

	if(isMultiLineString(label)) {
		// Write label as long string
		builder.append(ESCAPED_MULTI_LINE_QUOTES);
		builder.append(TurtleUtil.encodeLongString(label));
		builder.append(ESCAPED_MULTI_LINE_QUOTES);
	} else {
		// Write label as normal string
		builder.append(ESCAPED_DOUBLE_QUOTES);
		builder.append(TurtleUtil.encodeString(label));
		builder.append(ESCAPED_DOUBLE_QUOTES);
	}

	if(lit.getLanguage()!=null) {
		// Append the literal's language
		builder.append("@");
		builder.append(lit.getLanguage());
	} else {
		URI datatype = lit.getDatatype();
		if(datatype!=null) {
			// TODO: This should be configurable
			if(!canOmmitDatatype(datatype)) { // NOSONAR
				/**
				 * Append the literal's datatype (possibly written as an abbreviated
				 * URI)
				 */
				builder.append("^^");
				builder.append(writeURI(datatype));
			}
		}
	}
	return builder.toString();
}
 
Example 9
Source File: RDFUtils.java    From mustard with MIT License 4 votes vote down vote up
private static void addStatement(DTGraph<String,String> graph, Statement stmt, boolean newObject, boolean splitLiteral, Map<String, DTNode<String,String>> nodeMap) {

		DTNode<String,String> n1 = nodeMap.get(stmt.getSubject().toString());
		if (n1 == null) {
			n1 = graph.add(stmt.getSubject().toString());
			nodeMap.put(stmt.getSubject().toString(), n1);
		}

		DTNode<String, String> n2 = null;
		List<DTNode<String,String>> nodeList = new ArrayList<DTNode<String,String>>();

		if (stmt.getObject() instanceof Resource) {
			n2 = nodeMap.get(stmt.getObject().toString());
			if (n2 == null) {
				n2 = graph.add(stmt.getObject().toString());
				nodeMap.put(stmt.getObject().toString(), n2);
			}
			nodeList.add(n2);

		} else { // Literal
			if (splitLiteral) {
				ValueFactory factory = ValueFactoryImpl.getInstance();
				Literal orgLit = (Literal)stmt.getObject();
				WordIterator wi = new WordIterator(orgLit.getLabel());

				while (wi.hasNext()) {
					String word = wi.next();
					Literal lit;

					// Retain the original datatype/language tag
					if (orgLit.getDatatype() != null) {
						lit = factory.createLiteral(word, orgLit.getDatatype());
					} else if (orgLit.getLanguage() != null) {
						lit = factory.createLiteral(word, orgLit.getLanguage());
					} else {
						lit = factory.createLiteral(word);
					}

					n2 = nodeMap.get(lit.toString());

					if (n2 == null || newObject) {
						n2 = graph.add(lit.toString());
						nodeMap.put(lit.toString(), n2);
					}
					nodeList.add(n2);
				}
			} else {
				n2 = nodeMap.get(stmt.getObject().toString()); // toString() should be different from stringValue()
				if (n2 == null) {
					n2 = graph.add(stmt.getObject().toString());
					if (!newObject) {
						nodeMap.put(stmt.getObject().toString(), n2);
					}
				}
				nodeList.add(n2);
			}
		}
		for (DTNode<String,String> n : nodeList) {
			// Statements are unique, since they are in a Set, thus we have never seem this particular edge before, we know that.
			n1.connect(n, stmt.getPredicate().toString());
		}
	}
 
Example 10
Source File: StrAfterBOp.java    From database with GNU General Public License v2.0 4 votes vote down vote up
private void checkLanguage(final Literal arg1, final Literal arg2)
		throws SparqlTypeErrorException {

	final String lang1 = arg1.getLanguage();
	
	final String lang2 = arg2.getLanguage();

	if (lang1 == null && lang2 == null)
		return;
	
	if (lang1 != null && lang2 == null)
		return;
	
	if (lang1 == null && lang2 != null)
		throw new SparqlTypeErrorException();
	
	// both non-null, must be the same
	if (!lang1.equals(lang2))
		throw new SparqlTypeErrorException();
	
}
 
Example 11
Source File: StrdtBOp.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
public IV get(final IBindingSet bs) throws SparqlTypeErrorException {
    
    final IV iv = getAndCheckLiteral(0, bs);

    final IV datatype = getAndCheckBound(1, bs);
    
    if (!datatype.isURI())
        throw new SparqlTypeErrorException();

    final BigdataURI dt = (BigdataURI) asValue(datatype);

    final Literal lit = asLiteral(iv);
    
    if (lit.getDatatype() != null || lit.getLanguage() != null) {
        throw new SparqlTypeErrorException();
    }
    
    final String label = lit.getLabel();
    
    final BigdataLiteral str = getValueFactory().createLiteral(label, dt);
    
    return super.asIV(str, bs);

}
 
Example 12
Source File: LangBOp.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
public IV get(final IBindingSet bs) {

    final Literal literal = getAndCheckLiteralValue(0, bs);

    String langTag = literal.getLanguage();

    if (langTag == null) {

        langTag = "";

    }

    final BigdataValueFactory vf = getValueFactory();

    final BigdataValue lang = vf.createLiteral(langTag);

    return super.asIV(lang, bs);

}
 
Example 13
Source File: BigdataSubjectCentricFullTextIndex.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void index(final IV<?,?> subject,
            final Iterator<BigdataValue> valuesIterator) {
        
    	if (subject == null) {
    		throw new IllegalArgumentException();
    	}
    	
    	if (log.isDebugEnabled()) {
    		log.debug("indexing: " + subject);
    	}
    	
    	/*
    	 * We can use a capacity of one, because we will be indexing exactly
    	 * one subject.
    	 */
        final TokenBuffer<?> buffer = new TokenBuffer(1, this);

        int n = 0;
        
        while (valuesIterator.hasNext()) {

            final BigdataValue val = valuesIterator.next();

        	if (log.isDebugEnabled()) {
        		log.debug("value: " + val);
        	}
        	
            if (!(val instanceof Literal)) {

                /*
                 * Note: If you allow URIs to be indexed then the code which is
                 * responsible for free text search for quads must impose a
                 * filter on the subject and predicate positions to ensure that
                 * free text search can not be used to materialize literals or
                 * URIs from other graphs. This matters when the named graphs
                 * are used as an ACL mechanism. This would also be an issue if
                 * literals were allowed into the subject position.
                 */
                continue;

            }

            final Literal lit = (Literal) val;

            if (!indexDatatypeLiterals && lit.getDatatype() != null) {

                // do not index datatype literals in this manner.
                continue;

            }

            final String languageCode = lit.getLanguage();

            // Note: May be null (we will index plain literals).
            // if(languageCode==null) continue;

            final String text = lit.getLabel();

            /*
             * Note: The OVERWRITE option is turned off to avoid some of the
             * cost of re-indexing each time we see a term.
             */

//            // don't bother text indexing inline values for now
//            if (termId.isInline()) {
//                continue;
//            }
            
            index(buffer, subject, 0/* fieldId */, languageCode,
                    new StringReader(text));

            n++;

        }
        
        // flush writes to the text index.
        buffer.flush();

        if (log.isInfoEnabled())
            log.info("indexed " + n + " new values for s: " + subject);

    }
 
Example 14
Source File: LexiconConfiguration.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * If the total length of the Unicode components of the {@link Literal} is
 * less than {@link #maxInlineTextLength} then return an fully inline
 * version of the {@link Literal}.
 *
 * @param value
 *            The literal.
 *
 * @return The fully inline IV -or- <code>null</code> if the {@link Literal}
 *         could not be inlined within the configured constraints.
 */
private AbstractInlineIV<BigdataLiteral, ?> createInlineUnicodeLiteral(
        final Literal value) {

    if (maxInlineTextLength > 0) {

        /*
         * Only check the string length if we are willing to turn this into
         * a fully inline IV.
         */

        final long totalLength = BigdataValueSerializer.getStringLength(value);

        if (totalLength <= maxInlineTextLength) {

            return new FullyInlineTypedLiteralIV<BigdataLiteral>(
                    value.getLabel(), value.getLanguage(),
                    value.getDatatype());

        }

    }

    // Will not inline as Unicode.
    return null;

}
 
Example 15
Source File: LcaseBOp.java    From database with GNU General Public License v2.0 3 votes vote down vote up
@Override
public IV get(final IBindingSet bs) {

    final Literal in = getAndCheckLiteralValue(0, bs);

    final BigdataValueFactory vf = getValueFactory();

    final String label = in.getLabel().toLowerCase();

    final BigdataLiteral out;

    if (in.getLanguage() != null) {

        out = vf.createLiteral(label, in.getLanguage());

    } else if (in.getDatatype() != null) {

        out = vf.createLiteral(label, in.getDatatype());

    } else {

        out = vf.createLiteral(label);
        
    }

    return super.asIV(out, bs);

}
 
Example 16
Source File: BigdataValueSerializer.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Return the total #of characters in the RDF {@link Value}.
 * 
 * @param v
 *            The {@link Value}.
 * 
 * @return The character length of the data in the RDF {@link Value}.
 */
static public long getStringLength(final Value v) {

    if (v == null)
        throw new IllegalArgumentException();
    
    if (v instanceof URI) {

        return ((URI) v).stringValue().length();

    } else if (v instanceof Literal) {

        final Literal value = (Literal) v;

        final String label = value.getLabel();

        final int datatypeLength = value.getDatatype() == null ? 0 : value
                .getDatatype().stringValue().length();

        final int languageLength = value.getLanguage() == null ? 0 : value
                .getLanguage().length();

        final long totalLength = label.length() + datatypeLength
                + languageLength;

        return totalLength;

    } else if (v instanceof BNode) {

        return ((BNode) v).getID().length();

    } else {
        
        throw new UnsupportedOperationException();
        
    }
    
}
 
Example 17
Source File: BigdataValueSerializer.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Return the term code as defined by {@link ITermIndexCodes} for this type
 * of term. This is used to places URIs, different types of literals, and
 * bnodes into disjoint parts of the key space for sort orders.
 * 
 * @see ITermIndexCodes
 */
private byte getTermCode(final Value val) {
    
    if (val == null)
        throw new IllegalArgumentException();
    
    if (val instanceof URI) {
    
        return ITermIndexCodes.TERM_CODE_URI;
        
    } else if (val instanceof Literal) {
        
        final Literal lit = (Literal) val;
        
        if (lit.getLanguage() != null)
            return ITermIndexCodes.TERM_CODE_LCL;

        if (lit.getDatatype() != null)
            return ITermIndexCodes.TERM_CODE_DTL;

        return ITermIndexCodes.TERM_CODE_LIT;

    } else if (val instanceof BNode) {

        return ITermIndexCodes.TERM_CODE_BND;
        
    } else {
        
        throw new IllegalArgumentException("class="+val.getClass().getName());
        
    }

}
 
Example 18
Source File: BigdataLiteralImpl.java    From database with GNU General Public License v2.0 2 votes vote down vote up
final public boolean equals(final Literal o) {

        if (this == o)
            return true;
        
        if (o == null)
            return false;

		if ((o instanceof BigdataValue) //
				&& isRealIV()
				&& ((BigdataValue)o).isRealIV()
				&& ((BigdataValue) o).getValueFactory() == getValueFactory()) {

			return getIV().equals(((BigdataValue) o).getIV());

        }
        
        if (!label.equals(o.getLabel()))
            return false;

        if (language != null) {

            // the language code is case insensitive.
            return language.equalsIgnoreCase(o.getLanguage());

        } else if (o.getLanguage() != null) {

            return false;

        }

        if (datatype != null) {

            return datatype.equals(o.getDatatype());

        } else if (o.getDatatype() != null) {

            return false;
            
        }
        
        return true;
        
    }
 
Example 19
Source File: DatatypeBOp.java    From database with GNU General Public License v2.0 2 votes vote down vote up
public IV get(final IBindingSet bs) {

	    final BigdataValueFactory vf = super.getValueFactory();

        @SuppressWarnings("rawtypes")
        final IV iv = getAndCheckLiteral(0, bs);

        // not yet bound
        if (iv == null)
        	throw new SparqlTypeErrorException();

        if (log.isDebugEnabled()) {
            log.debug(iv);
        }

        /*
         * We don't need to do this anymore.  asValue(IV) does the right thing,
         * it will let us work with the IV directly in the right cases.  The
         * BOps should no longer be doing this kind of logic directly.
         */
//        if (iv.isInline() && !iv.isExtension()) {
//
//        	return asIV(iv.getDTE().getDatatypeURI(), bs);
//        	
//        }

        final Value val = asValue(iv);

        if (val instanceof Literal) {

        	final Literal literal = (Literal) val;

        	final URI datatype;

			if (literal.getDatatype() != null) {

				// literal with datatype
				datatype = literal.getDatatype();

            } else if (literal.getLanguage() != null) {

                // language-tag literal
                datatype = RDF.LANGSTRING;

			} else if (literal.getLanguage() == null) {

				// simple literal
				datatype = XSD.STRING;

			} else {

				throw new SparqlTypeErrorException();

			}

	    	return asIV(datatype, bs);

        }

        throw new SparqlTypeErrorException();

    }
 
Example 20
Source File: LexiconKeyBuilder.java    From database with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Return an unsigned byte[] that locates the value within a total ordering
 * over the RDF value space.
 * 
 * @param value
 *            An RDF value.
 * 
 * @return The sort key for that RDF value.
 */
public byte[] value2Key(final Value value) {

    if (value == null)
        throw new IllegalArgumentException();

    if (value instanceof URI) {

        final URI uri = (URI) value;

        final String term = uri.toString();

        return uri2key(term);

    } else if (value instanceof Literal) {

        final Literal lit = (Literal) value;

        final String text = lit.getLabel();

        final String languageCode = lit.getLanguage();

        final URI datatypeUri = lit.getDatatype();

        if (languageCode != null) {

            /*
             * language code literal.
             */
            return languageCodeLiteral2key(languageCode, text);

        } else if (datatypeUri != null) {

            /*
             * datatype literal.
             */
            return datatypeLiteral2key(datatypeUri, text);

        } else {

            /*
             * plain literal.
             */
            return plainLiteral2key(text);

        }

    } else if (value instanceof BNode) {

        /*
         * @todo if we know that the bnode id is a UUID that we generated
         * then we should encode that using faster logic that this unicode
         * conversion and stick the sort key on the bnode so that we do not
         * have to convert UUID to id:String to key:byte[].
         */
        final String bnodeId = ((BNode) value).getID();

        return blankNode2Key(bnodeId);

    } else {

        throw new AssertionError("Unknown value type: " + value.getClass());

    }

}