Search in sources :

Example 1 with Value

use of org.openrdf.model.Value in project qi4j-sdk by Qi4j.

the class SPARQLResource method getQuery.

private Query getQuery(Repository repository, RepositoryConnection repositoryCon, String queryStr) throws ResourceException {
    Form form = getRequest().getResourceRef().getQueryAsForm();
    Query result;
    // default query language is SPARQL
    QueryLanguage queryLn = QueryLanguage.SPARQL;
    // determine if inferred triples should be included in query evaluation
    boolean includeInferred = true;
    // build a dataset, if specified
    String[] defaultGraphURIs = form.getValuesArray(DEFAULT_GRAPH_PARAM_NAME);
    String[] namedGraphURIs = form.getValuesArray(NAMED_GRAPH_PARAM_NAME);
    DatasetImpl dataset = null;
    if (defaultGraphURIs.length > 0 || namedGraphURIs.length > 0) {
        dataset = new DatasetImpl();
        if (defaultGraphURIs.length > 0) {
            for (String defaultGraphURI : defaultGraphURIs) {
                try {
                    URI uri = repository.getValueFactory().createURI(defaultGraphURI);
                    dataset.addDefaultGraph(uri);
                } catch (IllegalArgumentException e) {
                    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Illegal URI for default graph: " + defaultGraphURI);
                }
            }
        }
        if (namedGraphURIs.length > 0) {
            for (String namedGraphURI : namedGraphURIs) {
                try {
                    URI uri = repository.getValueFactory().createURI(namedGraphURI);
                    dataset.addNamedGraph(uri);
                } catch (IllegalArgumentException e) {
                    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
                }
            }
        }
    }
    try {
        result = repositoryCon.prepareQuery(queryLn, queryStr);
        result.setIncludeInferred(includeInferred);
        if (dataset != null) {
            result.setDataset(dataset);
        }
        // determine if any variable bindings have been set on this query.
        @SuppressWarnings("unchecked") Enumeration<String> parameterNames = Collections.enumeration(form.getValuesMap().keySet());
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            if (parameterName.startsWith(BINDING_PREFIX) && parameterName.length() > BINDING_PREFIX.length()) {
                String bindingName = parameterName.substring(BINDING_PREFIX.length());
                Value bindingValue = parseValueParam(repository, form, parameterName);
                result.setBinding(bindingName, bindingValue);
            }
        }
    } catch (UnsupportedQueryLanguageException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    } catch (MalformedQueryException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    } catch (RepositoryException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e.getMessage());
    }
    return result;
}
Also used : Form(org.restlet.data.Form) RepositoryException(org.openrdf.repository.RepositoryException) DatasetImpl(org.openrdf.query.impl.DatasetImpl) URI(org.openrdf.model.URI) Value(org.openrdf.model.Value) ResourceException(org.restlet.resource.ResourceException)

Example 2 with Value

use of org.openrdf.model.Value in project blueprints by tinkerpop.

the class GraphSailTest method testAddVertex.

@Test
public void testAddVertex() throws Exception {
    GraphSail gSail = (GraphSail) sail;
    Value toAdd = new URIImpl("http://example.org/thelarch");
    assertNull(gSail.getVertex(toAdd));
    int count = countVertices();
    Vertex added = gSail.addVertex(toAdd);
    assertNotNull(added);
    assertEquals(1 + count, countVertices());
    assertEquals("http://example.org/thelarch", added.getProperty(GraphSail.VALUE));
    // also test that we get the vertex through getVertex
    added = gSail.getVertex(toAdd);
    assertNotNull(added);
    assertEquals("http://example.org/thelarch", added.getProperty(GraphSail.VALUE));
}
Also used : Vertex(com.tinkerpop.blueprints.Vertex) Value(org.openrdf.model.Value) URIImpl(org.openrdf.model.impl.URIImpl) Test(org.junit.Test)

Example 3 with Value

use of org.openrdf.model.Value in project backstage by zepheira.

the class DomLensNode method generateSubcontentAttributes.

protected void generateSubcontentAttributes(Value value, Scriptable result, Database database, SailRepositoryConnection connection) {
    ScriptableArrayBuilder arrayBuilder = new ScriptableArrayBuilder();
    for (SubcontentAttribute a : _subcontentAttributes) {
        DefaultScriptableObject o = new DefaultScriptableObject();
        o.put("name", o, a.name);
        StringBuffer sb = new StringBuffer();
        for (Fragment f : a.fragments) {
            if (f instanceof StringFragment) {
                sb.append(((StringFragment) f).text);
            } else {
                try {
                    boolean first = true;
                    ExpressionQueryResult eqr = ((ExpressionFragment) f).expression.computeOutputOnValue(value, database, connection);
                    if (eqr != null) {
                        TupleQueryResult queryResult = eqr.tupleQuery.evaluate();
                        try {
                            while (queryResult.hasNext()) {
                                BindingSet bindingSet = queryResult.next();
                                Value value2 = bindingSet.getValue(eqr.resultVar.getName());
                                if (first) {
                                    first = false;
                                } else {
                                    sb.append(";");
                                }
                                sb.append(renderInnerValueToText(value2, database, connection));
                            }
                        } finally {
                            queryResult.close();
                        }
                    } else {
                        sb.append(renderInnerValueToText(value, database, connection));
                    }
                } catch (Exception e) {
                    _logger.error("", e);
                }
            }
        }
        o.put("value", o, sb.toString());
        arrayBuilder.add(o);
    }
    result.put("subcontentAttributes", result, arrayBuilder.toArray());
}
Also used : ScriptableArrayBuilder(edu.mit.simile.backstage.util.ScriptableArrayBuilder) BindingSet(org.openrdf.query.BindingSet) DefaultScriptableObject(edu.mit.simile.backstage.util.DefaultScriptableObject) StringFragment(edu.mit.simile.backstage.model.ui.lens.SubcontentAttribute.StringFragment) ExpressionQueryResult(edu.mit.simile.backstage.model.data.ExpressionQueryResult) Value(org.openrdf.model.Value) TupleQueryResult(org.openrdf.query.TupleQueryResult) Fragment(edu.mit.simile.backstage.model.ui.lens.SubcontentAttribute.Fragment) StringFragment(edu.mit.simile.backstage.model.ui.lens.SubcontentAttribute.StringFragment) ExpressionFragment(edu.mit.simile.backstage.model.ui.lens.SubcontentAttribute.ExpressionFragment)

Example 4 with Value

use of org.openrdf.model.Value in project backstage by zepheira.

the class Database method createPropertyRecord.

private PropertyRecord createPropertyRecord(URI predicate, SailConnection sc) {
    String id = getPropertyId(predicate, sc);
    String label = SailUtilities.getStringObject(sc, predicate, RDFS.LABEL, id);
    String valueType = SailUtilities.getStringObject(sc, predicate, ExhibitOntology.VALUE_TYPE, "text");
    Properties properties = new Properties();
    CloseableIteration<? extends Statement, SailException> i = null;
    try {
        i = sc.getStatements(predicate, null, null, true);
    } catch (SailException e) {
        _logger.error("Failed to get all statements in order to get property record", e);
        return null;
    }
    if (i != null) {
        try {
            while (i.hasNext()) {
                Statement s = i.next();
                URI p = s.getPredicate();
                Value o = s.getObject();
                if (!p.equals(RDFS.LABEL) && !p.equals(ExhibitOntology.ID) && !p.equals(ExhibitOntology.VALUE_TYPE)) {
                    properties.put(p.getLocalName(), SailUtilities.valueToString(o));
                }
            }
        } catch (SailException e) {
            _logger.warn("Failed to iterate through statements", e);
        } finally {
            try {
                i.close();
            } catch (SailException e) {
                _logger.warn("Failed to close statement iterator", e);
            }
        }
    }
    return new PropertyRecord(predicate, id, label, valueType, properties);
}
Also used : Statement(org.openrdf.model.Statement) Value(org.openrdf.model.Value) SailException(org.openrdf.sail.SailException) Properties(java.util.Properties) URI(org.openrdf.model.URI)

Example 5 with Value

use of org.openrdf.model.Value in project backstage by zepheira.

the class Database method exportRDFa.

public String exportRDFa(int limit, String title) {
    try {
        RepositoryConnection con = getRepository().getConnection();
        RepositoryResult<Statement> result = con.getStatements(null, null, null, false);
        String out = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style>span {padding:4px}</style><title>" + title + "</title></head><body>";
        int itemCount = 0;
        Resource prevS = null;
        URI prevP = null;
        Value prevO = null;
        while (result.hasNext() && itemCount <= limit) {
            Statement st = result.next();
            String currLabel = null;
            Resource s = st.getSubject();
            String sStr = s.toString();
            // strip "http://127.0.0.1/" prefix from subj/pred
            if (sStr.startsWith("http://127.0.0.1/")) {
                sStr = sStr.substring(17);
            }
            URI p = st.getPredicate();
            String pStr = p.toString();
            if (pStr.startsWith("http://127.0.0.1/")) {
                pStr = pStr.substring(17);
            }
            Value o = st.getObject();
            String oStr = o.stringValue();
            // Determine if our object and subjects are URI
            boolean objectIsURI = false;
            try {
                oStr = (new java.net.URL(oStr).toString());
                objectIsURI = true;
            } catch (Exception e) {
                objectIsURI = false;
            }
            boolean subjectIsURI = false;
            try {
                sStr = (new java.net.URL(sStr).toString());
                subjectIsURI = true;
            } catch (Exception e) {
                subjectIsURI = false;
            }
            // FIXME. Use heuristic to determine if property is an image type. See above re fix.
            boolean objectIsImage = false;
            if (oStr.endsWith("png") || oStr.endsWith("jpg") || oStr.endsWith("gif") || oStr.endsWith("svg") || oStr.endsWith("jpeg")) {
                objectIsImage = true;
            }
            // arrives before we need it.
            if (pStr.equals("http://www.w3.org/2000/01/rdf-schema#label")) {
                currLabel = oStr;
            }
            // group by subject, count as an item
            if (s != prevS) {
                itemCount++;
                if (itemCount > limit)
                    break;
                if (subjectIsURI) {
                    out += "<p about=\"" + sStr + "\"" + ">\n";
                } else {
                    out += "<p about=\"#" + sStr + "\"" + ">\n";
                }
            }
            // skip externally irrelevant triples or those we handle elsewhere
            if (!pStr.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type") && !pStr.equals("http://simile.mit.edu/2006/11/exhibit#id") && !pStr.equals("http://www.w3.org/2000/01/rdf-schema#label")) {
                if (objectIsURI) {
                    // if we don't have a label, use subject
                    if (currLabel == null) {
                        currLabel = sStr;
                    }
                    if (objectIsImage) {
                        out += "<img property=\"" + pStr + "\" src=\"" + oStr + "\" alt=\"" + currLabel + "\" />";
                    } else {
                        out += "<a property=\"" + pStr + "\" href=\"" + oStr + "\">" + currLabel + "</a>";
                    }
                } else {
                    out += "<span property=\"" + pStr + "\">" + oStr + "</span>\n";
                }
            }
            prevS = s;
            prevP = p;
            prevO = o;
        }
        return out + "</body></html>";
    } catch (OpenRDFException e) {
        return "<html><head><title=\"Error\"></head><body>" + e.toString() + "</body></html>";
    }
}
Also used : RepositoryConnection(org.openrdf.repository.RepositoryConnection) Statement(org.openrdf.model.Statement) Resource(org.openrdf.model.Resource) OpenRDFException(org.openrdf.OpenRDFException) URI(org.openrdf.model.URI) SailException(org.openrdf.sail.SailException) OpenRDFException(org.openrdf.OpenRDFException) Value(org.openrdf.model.Value)

Aggregations

Value (org.openrdf.model.Value)24 URI (org.openrdf.model.URI)12 BindingSet (org.openrdf.query.BindingSet)10 Statement (org.openrdf.model.Statement)8 TupleQueryResult (org.openrdf.query.TupleQueryResult)8 ExpressionQueryResult (edu.mit.simile.backstage.model.data.ExpressionQueryResult)5 ScriptableArrayBuilder (edu.mit.simile.backstage.util.ScriptableArrayBuilder)5 QueryEvaluationException (org.openrdf.query.QueryEvaluationException)5 DefaultScriptableObject (edu.mit.simile.backstage.util.DefaultScriptableObject)4 RepositoryConnection (org.openrdf.repository.RepositoryConnection)4 RepositoryException (org.openrdf.repository.RepositoryException)4 SailException (org.openrdf.sail.SailException)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 SparqlFieldQuery (org.apache.stanbol.entityhub.query.sparql.SparqlFieldQuery)3 YardException (org.apache.stanbol.entityhub.servicesapi.yard.YardException)3 Resource (org.openrdf.model.Resource)3 HashMap (java.util.HashMap)2 Properties (java.util.Properties)2 RdfRepresentation (org.apache.stanbol.entityhub.model.sesame.RdfRepresentation)2