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

The following examples show how to use org.openrdf.model.Literal#getLabel() . 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: NativeCumulusLiteral.java    From cumulusrdf with Apache License 2.0 6 votes vote down vote up
/**
 * Loads data associated with this literal.
 */
private synchronized void load() {

	if (_has_data) {
		return;
	}

	// load data ...
	try {

		Literal lit = (Literal) _dict.getValue(_internalID, false);

		super.setDatatype(lit.getDatatype());
		super.setLabel(lit.getLabel());
		super.setLanguage(lit.getLanguage());

	} catch (final Exception exception) {
		_log.error(MessageCatalog._00075_COULDNT_LOAD_NODE, exception, Arrays.toString(_internalID));
		super.setLabel("cumulus/internal/" + Arrays.toString(_internalID));
	}

	_has_data = true;
}
 
Example 3
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 4
Source File: StrlenBOp.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public IV get(final IBindingSet bs) throws SparqlTypeErrorException {
    
    final Literal lit = getAndCheckLiteralValue(0, bs);
    final String label = lit.getLabel();
    final int length = label.length();
    return new XSDIntegerIV(BigInteger.valueOf(length));
    
}
 
Example 5
Source File: XsdUnsignedLongBOp.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public IV get(final IBindingSet bs) {

        final IV iv = getAndCheckBound(0, bs);
        
        if (log.isDebugEnabled()) {
        	log.debug(iv);
        }
        
        final Value val = asValue(iv);

        if (log.isDebugEnabled()) {
        	log.debug(val);
        }
        
        // use to create my simple literals
        final BigdataValueFactory vf = getValueFactory();

        try {
            if (val instanceof Literal) {
            	final Literal lit = (Literal) val;
                if (lit.getDatatype() != null && lit.getDatatype().equals(XSD.UNSIGNED_LONG)) {
                    // if xsd:unsignedLong literal return it
                    return iv;
            	}
            	else {
            	    final BigInteger valAsBigInt = new BigInteger(lit.getLabel());
            	    if (valAsBigInt.compareTo(MIN_UNSIGNED_LONG)>=0 && valAsBigInt.compareTo(MAX_UNSIGNED_LONG)<=0) {
                        final BigdataLiteral str = 
                            vf.createLiteral(String.valueOf(valAsBigInt.toString()), XSD.UNSIGNED_LONG);
                        return super.asIV(str, bs);
            	    }
                }
            }
        } catch (Exception e) {
            // exception handling following
        }

        throw new SparqlTypeErrorException(); // fallback
    }
 
Example 6
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 7
Source File: ClassMarshall.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public Class deserialize(Literal literal) {
	String label = literal.getLabel();
	try {
		synchronized (cl) {
			return Class.forName(label, true, cl);
		}
	} catch (ClassNotFoundException e) {
		throw new ObjectConversionException(e);
	}
}
 
Example 8
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 9
Source File: SqlTimestampMarshall.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public Timestamp deserialize(Literal literal) {
	String label = literal.getLabel();
	XMLGregorianCalendar gc = factory.newXMLGregorianCalendar(label);
	return new Timestamp(gc.toGregorianCalendar().getTimeInMillis());
}
 
Example 10
Source File: DateMarshall.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public Date deserialize(Literal literal) {
	String label = literal.getLabel();
	XMLGregorianCalendar gc = factory.newXMLGregorianCalendar(label);
	return gc.toGregorianCalendar().getTime();
}
 
Example 11
Source File: SqlTimeMarshall.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public Time deserialize(Literal literal) {
	String label = literal.getLabel();
	XMLGregorianCalendar gc = factory.newXMLGregorianCalendar(label);
	return new Time(gc.toGregorianCalendar().getTimeInMillis());
}
 
Example 12
Source File: GregorianCalendarMarshall.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public GregorianCalendar deserialize(Literal literal) {
	String label = literal.getLabel();
	XMLGregorianCalendar gc = factory.newXMLGregorianCalendar(label);
	return gc.toGregorianCalendar();
}
 
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: 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 15
Source File: DigestBOp.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);
    //Recreate since they are not thread safe
    MessageDigest md = null;
    final Literal lit = asLiteral(iv);
    if (lit.getLanguage() == null &&
        (lit.getDatatype() == null || lit.getDatatype().equals(XSD.STRING))) {
        
        try {
            String label = lit.getLabel();
            switch (op()) {
            case MD5:
                md = MessageDigest.getInstance("MD5");
                break;
            case SHA1:
                md = MessageDigest.getInstance("SHA-1");
                break;
            case SHA224:
                md = MessageDigest.getInstance("SHA-224");
                break;
            case SHA256:
                md = MessageDigest.getInstance("SHA-256");
                break;
            case SHA384:
                md = MessageDigest.getInstance("SHA-384");
                break;
           case SHA512:
                md = MessageDigest.getInstance("SHA-512");
                break;
            default:
                throw new UnsupportedOperationException();
            }
            byte[] bytes = label.getBytes("UTF-8");
            md.update(bytes);
            byte[] digest = md.digest();
            final BigdataLiteral str = getValueFactory().createLiteral(toHexString(digest));
            return super.asIV(str, bs);
        } catch (Exception e) {
            throw new SparqlTypeErrorException();
        }
    }
    throw new SparqlTypeErrorException();
}
 
Example 16
Source File: DerivedNumericsExtension.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Attempts to convert the supplied value into an internal representation
 * using BigInteger.
 */
public LiteralExtensionIV createIV(final Value value) {
    
    if (value instanceof Literal == false)
        throw new IllegalArgumentException();
    
    final Literal lit = (Literal) value;
    
    final URI dt = lit.getDatatype();
    
    if (dt == null)
        throw new IllegalArgumentException();
    
    final String dts = dt.stringValue();
    
    BigdataURI resolvedDT = null;
    for (BigdataURI val : datatypes.values()) {
        // Note: URI.stringValue() is efficient....
        if (val.stringValue().equals(dts)) {
            resolvedDT = val;
        }
    }
    
    if (resolvedDT == null)
        throw new IllegalArgumentException();
    
    final String s = lit.getLabel();

    final boolean valid;
    if (dts.equals(XSD.POSITIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidPositiveInteger(s);
    } else if (dts.equals(XSD.NEGATIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidNegativeInteger(s);
    } else if (dts.equals(XSD.NON_POSITIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidNonPositiveInteger(s);
    } else if (dts.equals(XSD.NON_NEGATIVE_INTEGER.stringValue())) {
    	valid = XMLDatatypeUtil.isValidNonNegativeInteger(s);
    } else {
    	valid = false;
    }
    
    if (!valid) {
    	throw new RuntimeException("could not correctly parse label: " + s + " for datatype: " + dts);
    }

    final BigInteger bi = XMLDatatypeUtil.parseInteger(s);
    
    final AbstractLiteralIV delegate = new XSDIntegerIV(bi);

    return new LiteralExtensionIV(delegate, resolvedDT.getIV());
    
}
 
Example 17
Source File: ConcatBOp.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
public IV get(final IBindingSet bs) {
    URI datatype = null;
    String lang = null;
    boolean allSame = true;
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < arity(); i++) {
        @SuppressWarnings("rawtypes")
        final IV v = getAndCheckLiteral(i, bs);

        if (v.isNumeric()) {
            throw new SparqlTypeErrorException();
        }
        
        String label = null;
        if (allSame) {
            final Literal lit = asLiteral(v);
            label = lit.getLabel();
            if (lit.getDatatype() != null) {
                if (lang != null) {
                    allSame = false;
                } else if (datatype == null) {
                    if (i == 0) {
                        datatype = lit.getDatatype();
                    } else {
                        allSame = false;
                    }
                } else if (!datatype.equals(lit.getDatatype())) {
                    allSame = false;
                }
            } else if (lit.getLanguage() != null) {
                if (datatype != null) {
                    allSame = false;
                } else if (lang == null) {
                    if (i == 0) {
                        lang = lit.getLanguage();
                    } else {
                        allSame = false;
                    }
                } else if (!lang.equals(lit.getLanguage())) {
                    allSame = false;
                }
            } else {
                allSame = false;
            }
        } else {
            label = literalLabel(v);
        }
        sb.append(label);
    }
    if (allSame) {
        if (datatype != null) {
            return super.asIV(getValueFactory().createLiteral(sb.toString(),datatype), bs);
        } else if (lang != null) {
            return super.asIV(getValueFactory().createLiteral(sb.toString(),lang), bs);
        }
    }
    return super.asIV(getValueFactory().createLiteral(sb.toString()), bs);

}
 
Example 18
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 19
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());

    }

}
 
Example 20
Source File: StrAfterBOp.java    From database with GNU General Public License v2.0 2 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public IV get(final IBindingSet bs) throws SparqlTypeErrorException {

    final Literal arg1 = getAndCheckLiteralValue(0, bs);

    final Literal arg2 = getAndCheckLiteralValue(1, bs);
    
    checkCompatibility(arg1, arg2);
    
    final String s2 = arg2.getLabel();
    
    if (s2.isEmpty()) {
    	
    	return ret(arg1, arg1.getLabel(), bs);
    	
    }
    
    final String s1 = arg1.getLabel();
    
    final int i = s1.indexOf(s2);
    
    // didn't find it
	if (i < 0) {
    	
    	return ret(arg1, null, bs);
    	
    }

    // found it, but it's at the end
    if (i + s2.length() == s1.length()) {
    	
    	return ret(arg1, "", bs);
    	
    }
    
    final String val = s1.substring(i + s2.length());
    
    return ret(arg1, val, bs);

}