Search in sources :

Example 71 with QuerySolution

use of org.apache.jena.query.QuerySolution 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 72 with QuerySolution

use of org.apache.jena.query.QuerySolution 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 73 with QuerySolution

use of org.apache.jena.query.QuerySolution in project webofneeds by researchstudio-sat.

the class WonConversationUtilsTest method main.

public static void main(String... args) throws Exception {
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.INFO);
    // Dataset input = loadDataset("/won/utils/agreement/input/one-agreement-one-cancellation.trig");
    Dataset input = loadDataset("/won/utils/conversationutils/input/longer-conversation.trig");
    SparqlSelectFunction<QuerySolution> selectfunction = new SparqlSelectFunction<>("/conversation/messagesForHighlevelProtocols.rq", x -> x).addOrderBy("distance", Query.ORDER_ASCENDING).addInitialBinding("senderOfFirstMessage", new ResourceImpl("https://localhost:8443/won/resource/need/4517796920802783000"));
    StopWatch sw = new StopWatch();
    sw.start();
    selectfunction.apply(input).forEach(x -> System.out.println("solution:" + x.toString()));
    sw.stop();
    System.out.println("query took: " + sw.getLastTaskTimeMillis() / 1000d + " seconds ");
    // Thread.currentThread().sleep(30000);
    sw.start();
    AgreementProtocolState state = AgreementProtocolState.of(input);
    sw.stop();
    RDFDataMgr.write(System.out, state.getAgreements(), Lang.TRIG);
    System.out.println("Analyzing the state of agreement protocol took: " + sw.getLastTaskTimeMillis() / 1000d + " seconds ");
    System.out.println(state.getAgreementProtocolUris());
    System.out.println(state.getEffects(URI.create("https://localhost:8443/won/resource/event/grj35bbhnkcrlfc72pqo")));
/*
		RdfUtils.Pair<Dataset> diff = RdfUtils.diff(input, output);
		if (!(diff.getFirst().isEmpty() && diff.getSecond().isEmpty())) {
			System.out.println("diff - only in input:");
			RDFDataMgr.write(System.out, diff.getFirst(), Lang.TRIG);
			System.out.println("diff - only in output:");
			RDFDataMgr.write(System.out, diff.getSecond(), Lang.TRIG);
		} else {
			System.out.println("input and output are equal");
		}
		*/
// Dataset output = HighlevelProtocols.getProposals(input);
// RDFDataMgr.write(System.out, output, Lang.TRIG);
// initialBinding.add("senderNeed", new ResourceImpl("https://localhost:8443/won/resource/need/7820503869697675000"));
// initialBinding.add("senderConnection", new ResourceImpl("https://localhost:8443/won/resource/connection/4t9deo4t6bqx83jxk5ex"));
// URI uri = WonConversationUtils.getLatestMessageOfNeed(input, URI.create("https://localhost:8443/won/resource/need/7820503869697675000"));
// URI uri = WonConversationUtils.getLatestMessageOfNeed(input, URI.create("https://192.168.124.49:8443/won/resource/need/z35td13ftmn5k1hzella"));
// System.out.println("uri: " + uri);
/*
		List<QuerySolution> actual = WonConversationQueryBuilder.getBuilder((x -> x))
				//.senderNeed(URI.create("https://localhost:8443/won/resource/need/7820503869697675000"))
				.newestFirst()
				.noResponses()
				.build()
				.apply(input);
		*/
// System.out.println("actual: \n" + actual.stream().map(x -> x.toString()).collect(Collectors.joining("\n")));
/*
		URI uri = WonConversationUtils.getLatestProposesMessageOfNeed(input, URI.create("https://localhost:8443/won/resource/need/7820503869697675000"));
		System.out.println("uri: " + uri);
		uri = WonConversationUtils.getLatestAcceptsMessageOfNeed(input, URI.create("https://localhost:8443/won/resource/need/7820503869697675000"));
		System.out.println("uri: " + uri);*/
}
Also used : ResourceImpl(org.apache.jena.rdf.model.impl.ResourceImpl) QuerySolution(org.apache.jena.query.QuerySolution) Dataset(org.apache.jena.query.Dataset) SparqlSelectFunction(won.protocol.util.SparqlSelectFunction) AgreementProtocolState(won.protocol.agreement.AgreementProtocolState) Logger(ch.qos.logback.classic.Logger) StopWatch(org.springframework.util.StopWatch)

Example 74 with QuerySolution

use of org.apache.jena.query.QuerySolution in project webofneeds by researchstudio-sat.

the class DatasetBackedOwnerCallbackAdapter method makeConnection.

@Override
protected Connection makeConnection(final WonMessage wonMessage) {
    URI connUri = wonMessage.getReceiverURI();
    ParameterizedSparqlString pss = new ParameterizedSparqlString();
    pss.setNsPrefix("won", WON.BASE_URI);
    pss.setCommandText(QUERY_CONNECTION);
    pss.setIri("con", connUri.toString());
    Query query = pss.asQuery();
    QueryExecution qExec = QueryExecutionFactory.create(query, dataset);
    qExec.getContext().set(TDB.symUnionDefaultGraph, true);
    try {
        Connection con = null;
        final ResultSet results = qExec.execSelect();
        if (results.hasNext()) {
            QuerySolution soln = results.next();
            if (results.hasNext()) {
                throw new DataIntegrityException("Query must not yield multiple solutions");
            }
            con = new Connection();
            con.setConnectionURI(getURIFromSolution(soln, "con"));
            con.setTypeURI(getURIFromSolution(soln, "type"));
            con.setNeedURI(getURIFromSolution(soln, "need"));
            con.setState(ConnectionState.fromURI(getURIFromSolution(soln, "state")));
            con.setRemoteNeedURI(getURIFromSolution(soln, "remoteNeed"));
            con.setRemoteConnectionURI(getURIFromSolution(soln, "remoteCon"));
        }
        return con;
    } finally {
        if (!qExec.isClosed()) {
            qExec.close();
        }
    }
}
Also used : Query(org.apache.jena.query.Query) QuerySolution(org.apache.jena.query.QuerySolution) DataIntegrityException(won.protocol.exception.DataIntegrityException) Connection(won.protocol.model.Connection) ResultSet(org.apache.jena.query.ResultSet) ParameterizedSparqlString(org.apache.jena.query.ParameterizedSparqlString) URI(java.net.URI) QueryExecution(org.apache.jena.query.QueryExecution)

Example 75 with QuerySolution

use of org.apache.jena.query.QuerySolution in project legato by DOREMUS-ANR.

the class CBDBuilder method getResources.

/**
 ***************************************************
 * Get all resource of a given class from an RDF model
 ****************************************************
 */
public static List<Resource> getResources(Model model, List<String> classnames) {
    List<Resource> results = new ArrayList<Resource>();
    for (String classname : classnames) {
        String sparqlQueryString = "SELECT DISTINCT ?s { ?s a <" + classname + "> }";
        Query query = QueryFactory.create(sparqlQueryString);
        QueryExecution qexec = QueryExecutionFactory.create(query, model);
        ResultSet queryResults = qexec.execSelect();
        while (queryResults.hasNext()) {
            QuerySolution qs = queryResults.nextSolution();
            results.add(qs.getResource("?s"));
        }
        qexec.close();
    }
    return results;
}
Also used : Query(org.apache.jena.query.Query) QuerySolution(org.apache.jena.query.QuerySolution) Resource(org.apache.jena.rdf.model.Resource) ArrayList(java.util.ArrayList) ResultSet(org.apache.jena.query.ResultSet) QueryExecution(org.apache.jena.query.QueryExecution)

Aggregations

QuerySolution (org.apache.jena.query.QuerySolution)125 ResultSet (org.apache.jena.query.ResultSet)103 QueryExecution (org.apache.jena.query.QueryExecution)96 ArrayList (java.util.ArrayList)70 Test (org.junit.Test)69 Dataset (org.apache.jena.query.Dataset)44 Query (org.apache.jena.query.Query)44 Resource (org.apache.jena.rdf.model.Resource)43 Literal (org.apache.jena.rdf.model.Literal)21 RDFNode (org.apache.jena.rdf.model.RDFNode)20 Model (org.apache.jena.rdf.model.Model)12 HashMap (java.util.HashMap)7 ResultSetRewindable (org.apache.jena.query.ResultSetRewindable)6 Extractor (infoeval.main.WikiData.Extractor)4 Node (org.apache.jena.graph.Node)4 DatasetGraph (org.apache.jena.sparql.core.DatasetGraph)4 IOException (java.io.IOException)3 Date (java.sql.Date)3 SimpleDateFormat (java.text.SimpleDateFormat)3 LinkedList (java.util.LinkedList)3