Search in sources :

Example 86 with RDFNode

use of org.apache.jena.rdf.model.RDFNode in project jena by apache.

the class DatasetAssembler method createDataset.

public Dataset createDataset(Assembler a, Resource root, Mode mode) {
    // -------- Default graph
    // Can use ja:graph or ja:defaultGraph
    Resource dftGraph = GraphUtils.getResourceValue(root, DatasetAssemblerVocab.pDefaultGraph);
    if (dftGraph == null)
        dftGraph = GraphUtils.getResourceValue(root, DatasetAssemblerVocab.pGraph);
    Model dftModel = null;
    if (dftGraph != null)
        dftModel = a.openModel(dftGraph);
    else
        // Assembler description did not define one.
        dftModel = GraphFactory.makeDefaultModel();
    Dataset ds = DatasetFactory.create(dftModel);
    // -------- Named graphs
    List<RDFNode> nodes = GraphUtils.multiValue(root, DatasetAssemblerVocab.pNamedGraph);
    for (RDFNode n : nodes) {
        if (!(n instanceof Resource))
            throw new DatasetAssemblerException(root, "Not a resource: " + FmtUtils.stringForRDFNode(n));
        Resource r = (Resource) n;
        String gName = GraphUtils.getAsStringValue(r, DatasetAssemblerVocab.pGraphName);
        Resource g = GraphUtils.getResourceValue(r, DatasetAssemblerVocab.pGraph);
        if (g == null) {
            g = GraphUtils.getResourceValue(r, DatasetAssemblerVocab.pGraphAlt);
            if (g != null) {
                Log.warn(this, "Use of old vocabulary: use :graph not :graphData");
            } else {
                throw new DatasetAssemblerException(root, "no graph for: " + gName);
            }
        }
        Model m = a.openModel(g);
        ds.addNamedModel(gName, m);
    }
    AssemblerUtils.setContext(root, ds.getContext());
    return ds;
}
Also used : Dataset(org.apache.jena.query.Dataset) Resource(org.apache.jena.rdf.model.Resource) Model(org.apache.jena.rdf.model.Model) RDFNode(org.apache.jena.rdf.model.RDFNode)

Example 87 with RDFNode

use of org.apache.jena.rdf.model.RDFNode in project Info-Evaluation by TechnionYP5777.

the class SqlRunner method getPersonalInfo.

@SuppressWarnings("unchecked")
public TableEntry getPersonalInfo(String name) throws ClassNotFoundException, SQLException, IOException, ParseException {
    Object[] inp = new Object[] { name };
    ArrayList<Row> res = conn.runQuery("SELECT name FROM basic_info WHERE name = ?", inp);
    String newName = WordUtils.capitalize(name).replaceAll(" ", "_");
    if (res.isEmpty()) {
        return getPersonalInfoFromDBpedia(newName);
    }
    ArrayList<Row> id_result = conn.runQuery("SELECT serialized_id " + "FROM serialized_query_results " + "WHERE query_identifier LIKE CONCAT('getPersonalInfo','(',?,')')", inp);
    int serialized_id = -1;
    ArrayList<Row> rows = new ArrayList<>();
    String overviewStr = "";
    if (id_result.isEmpty()) {
        Extractor ext = new Extractor(newName);
        logger.log(Level.INFO, "abstract extraction query is being executed");
        ext.executeQuery(QueryTypes.ABSTRACT);
        ResultSetRewindable results = ext.getResults();
        results.reset();
        QuerySolution solution = results.nextSolution();
        RDFNode overview = solution.get("abstract");
        overviewStr = "No Abstract";
        if (overview != null)
            if (overview.isResource())
                overviewStr = (overview.asResource() + "").split("resource/")[1];
            else if (overview.isLiteral())
                overviewStr = (overview.asLiteral() + "").split("@")[0];
        final String personalInfoQuery = "SELECT SQL_CACHE filtered_info.*, WikiID.wikiPageId " + "FROM (SELECT * FROM basic_info WHERE name = ?) AS filtered_info " + "LEFT JOIN WikiID " + "ON WikiID.name = filtered_info.name " + "LIMIT 1";
        logger.log(Level.INFO, "personal info query is being executed");
        rows = conn.runQuery(personalInfoQuery, inp);
        Object[] toSerilaize = new Object[2];
        toSerilaize[0] = rows;
        toSerilaize[1] = overviewStr;
        String query_identifier = "getPersonalInfo(" + name + ")";
        serialized_id = resultsSer.serializeQueryResults(conn, query_identifier, toSerilaize);
    } else {
        serialized_id = (int) id_result.get(0).row.get(0).getKey();
        Object[] output = (Object[]) resultsSer.deSerializeQueryResults(conn, serialized_id);
        rows = (ArrayList<Row>) output[0];
        overviewStr = (String) output[1];
    }
    Row res_row = rows.get(0);
    String birthPlace = (String) res_row.row.get(1).getValue().cast(res_row.row.get(1).getKey());
    String deathPlace = (String) res_row.row.get(2).getValue().cast(res_row.row.get(2).getKey());
    Date birthDate = null;
    if (!"".equals(res_row.row.get(3).getKey())) {
        birthDate = (java.sql.Date) res_row.row.get(3).getValue().cast(res_row.row.get(3).getKey());
    }
    Date deathDate = null;
    if (!"".equals(res_row.row.get(4).getKey())) {
        deathDate = (java.sql.Date) res_row.row.get(4).getValue().cast(res_row.row.get(4).getKey());
    }
    String occupation = (String) res_row.row.get(5).getValue().cast(res_row.row.get(5).getKey());
    String spouseName = (String) res_row.row.get(6).getValue().cast(res_row.row.get(6).getKey());
    String spouseOccupation = (String) res_row.row.get(7).getValue().cast(res_row.row.get(7).getKey());
    String photoLink = (String) res_row.row.get(8).getValue().cast(res_row.row.get(8).getKey());
    photoLink.replaceAll("'", "\'");
    String wikiPageID = (String) res_row.row.get(9).getValue().cast(res_row.row.get(9).getKey());
    TableEntry te = new TableEntry(wikiURL + wikiPageID, name, birthPlace, deathPlace, birthDate, deathDate, occupation, spouseName, spouseOccupation, photoLink, overviewStr);
    return te;
}
Also used : ArrayList(java.util.ArrayList) Date(java.sql.Date) QuerySolution(org.apache.jena.query.QuerySolution) Extractor(infoeval.main.WikiData.Extractor) ResultSetRewindable(org.apache.jena.query.ResultSetRewindable) RDFNode(org.apache.jena.rdf.model.RDFNode)

Example 88 with RDFNode

use of org.apache.jena.rdf.model.RDFNode in project Info-Evaluation by TechnionYP5777.

the class SqlRunner method getPersonalInfoFromDBpedia.

public TableEntry getPersonalInfoFromDBpedia(String name) throws ClassNotFoundException, SQLException, IOException, ParseException {
    // Object[] inp = new Object[] { name };
    // ArrayList<Row> id_result = conn.runQuery("SELECT serialized_id " +
    // "FROM serialized_query_results "
    // + "WHERE query_identifier LIKE CONCAT('getPersonalInfo','(',?,')')",
    // inp);
    // int serialized_id = -1;
    TableEntry result;
    // if (id_result.isEmpty()) {
    Extractor ext = new Extractor(name);
    logger.log(Level.INFO, "abstract extraction query is being executed");
    ext.executeQuery(QueryTypes.ABSTRACT);
    ResultSetRewindable results = ext.getResults();
    results.reset();
    QuerySolution solution = results.nextSolution();
    RDFNode overview = solution.get("abstract");
    String overviewStr = "No Abstract";
    if (overview != null)
        if (overview.isResource())
            overviewStr = (overview.asResource() + "").split("resource/")[1];
        else if (overview.isLiteral())
            overviewStr = (overview.asLiteral() + "").split("@")[0];
    logger.log(Level.INFO, "basic Info By Name extraction query is being executed");
    ext.executeQuery(QueryTypes.BASIC_INFO_BY_NAME);
    ResultSetRewindable basicInfoByNameResults = ext.getResults();
    basicInfoByNameResults.reset();
    SqlTablesFiller filler = new SqlTablesFiller();
    TableEntry te = filler.getInfo(basicInfoByNameResults);
    filler.close();
    result = new TableEntry(te);
    String newName = name.replaceAll("_", " ");
    result.setName(newName);
    result.setUrl("");
    result.setOverview(overviewStr);
    String photoLink = result.getPhotoLink();
    photoLink.replaceAll("'", "\'");
    result.setPhotoLink(photoLink);
    Object[] toSerilaize = new Object[1];
    toSerilaize[0] = result;
    /*
		 * String query_identifier = "getPersonalInfo(" + name + ")";
		 * resultsSer.serializeQueryResults(conn, query_identifier,
		 * toSerilaize); } else { serialized_id = (int)
		 * id_result.get(0).row.get(0).getKey(); Object[] output = (Object[])
		 * resultsSer.deSerializeQueryResults(conn, serialized_id); result =
		 * (TableEntry) output[0]; }
		 */
    return result;
}
Also used : QuerySolution(org.apache.jena.query.QuerySolution) Extractor(infoeval.main.WikiData.Extractor) ResultSetRewindable(org.apache.jena.query.ResultSetRewindable) SqlTablesFiller(infoeval.main.WikiData.SqlTablesFiller) RDFNode(org.apache.jena.rdf.model.RDFNode)

Example 89 with RDFNode

use of org.apache.jena.rdf.model.RDFNode in project webofneeds by researchstudio-sat.

the class DatasetToDatasetBySparqlGSPOSelectFunction method apply.

@Override
public Dataset apply(Dataset dataset) {
    dataset.begin(ReadWrite.READ);
    Dataset result = DatasetFactory.createGeneral();
    result.begin(ReadWrite.WRITE);
    Query query = QueryFactory.create(sparql);
    try (QueryExecution queryExecution = QueryExecutionFactory.create(query, dataset)) {
        ResultSet resultSet = queryExecution.execSelect();
        RDFNode currentProposal = null;
        Model currentProposalContent = ModelFactory.createDefaultModel();
        while (resultSet.hasNext()) {
            QuerySolution solution = resultSet.next();
            RDFNode proposalNode = solution.get("g");
            if (currentProposal == null) {
                // first solution: remember uri of first proposal
                currentProposal = proposalNode;
            } else {
                // the currentProposal URI and prepare a new empty model for the next proposal
                if (!currentProposal.equals(proposalNode)) {
                    // we have seen all triples of currentProposal
                    result.addNamedModel(currentProposal.asResource().getURI(), currentProposalContent);
                    currentProposalContent = ModelFactory.createDefaultModel();
                }
                currentProposal = proposalNode;
            }
            // add current triple into currentAgreementModel
            RDFNode s = solution.get("s");
            RDFNode p = solution.get("p");
            RDFNode o = solution.get("o");
            Statement newStatement = new StatementImpl(s.asResource(), new PropertyImpl(p.asResource().getURI()), o);
            currentProposalContent.add(newStatement);
        }
        // add the last model
        if (currentProposal != null) {
            result.addNamedModel(currentProposal.asResource().getURI(), currentProposalContent);
        }
        return result;
    } finally {
        dataset.commit();
        result.commit();
    }
}
Also used : Query(org.apache.jena.query.Query) QuerySolution(org.apache.jena.query.QuerySolution) Dataset(org.apache.jena.query.Dataset) Statement(org.apache.jena.rdf.model.Statement) StatementImpl(org.apache.jena.rdf.model.impl.StatementImpl) ResultSet(org.apache.jena.query.ResultSet) Model(org.apache.jena.rdf.model.Model) PropertyImpl(org.apache.jena.rdf.model.impl.PropertyImpl) QueryExecution(org.apache.jena.query.QueryExecution) RDFNode(org.apache.jena.rdf.model.RDFNode)

Example 90 with RDFNode

use of org.apache.jena.rdf.model.RDFNode in project webofneeds by researchstudio-sat.

the class WonNodeSparqlService method retrieveAllWonNodeInfo.

/**
 * Retrieve resource data of all known won nodes that are saved in the Sparql endpoint.
 *
 * @return Set of all known won node resource data
 */
public Set<WonNodeInfo> retrieveAllWonNodeInfo() {
    Set<WonNodeInfo> wonNodeInfos = new HashSet<>();
    String queryString = "SELECT ?graphUri ?nodeUri WHERE { GRAPH ?graphUri {?nodeUri won:hasUriPrefixSpecification ?c} }";
    ParameterizedSparqlString pps = new ParameterizedSparqlString();
    pps.setCommandText(queryString);
    pps.setNsPrefix("won", "http://purl.org/webofneeds/model#");
    log.debug("Query SPARQL Endpoint: {}", sparqlEndpoint);
    log.debug("Execute query: {}", pps.toString());
    QueryExecution qexec = QueryExecutionFactory.sparqlService(sparqlEndpoint, pps.asQuery());
    ResultSet results = qexec.execSelect();
    while (results.hasNext()) {
        QuerySolution qs = results.nextSolution();
        RDFNode rdfNode = qs.get("graphUri");
        if (rdfNode != null) {
            String graphUri = rdfNode.asResource().getURI();
            Dataset ds = retrieveDataset(graphUri);
            WonNodeInfo nodeInfo = getWonNodeInfoFromDataset(ds);
            wonNodeInfos.add(nodeInfo);
        }
    }
    qexec.close();
    return wonNodeInfos;
}
Also used : WonNodeInfo(won.protocol.service.WonNodeInfo) RDFNode(org.apache.jena.rdf.model.RDFNode) HashSet(java.util.HashSet)

Aggregations

RDFNode (org.apache.jena.rdf.model.RDFNode)145 Resource (org.apache.jena.rdf.model.Resource)51 Model (org.apache.jena.rdf.model.Model)30 Statement (org.apache.jena.rdf.model.Statement)27 Test (org.junit.Test)26 ArrayList (java.util.ArrayList)22 Node (org.apache.jena.graph.Node)20 QuerySolution (org.apache.jena.query.QuerySolution)20 TextIndexException (org.apache.jena.query.text.TextIndexException)17 Property (org.apache.jena.rdf.model.Property)17 Literal (org.apache.jena.rdf.model.Literal)15 SecuredRDFNode (org.apache.jena.permissions.model.SecuredRDFNode)13 Dataset (org.apache.jena.query.Dataset)13 Triple (org.apache.jena.graph.Triple)12 QueryExecution (org.apache.jena.query.QueryExecution)10 StmtIterator (org.apache.jena.rdf.model.StmtIterator)9 Query (org.apache.jena.query.Query)8 NodeIterator (org.apache.jena.rdf.model.NodeIterator)8 RDFList (org.apache.jena.rdf.model.RDFList)8 AccessDeniedException (org.apache.jena.shared.AccessDeniedException)7