Java Code Examples for org.apache.jena.query.QueryFactory

The following examples show how to use org.apache.jena.query.QueryFactory. These examples are extracted from open source projects. 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 Project: RDFstarTools   Source File: ParserSPARQLStarTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void registrationOK() {
	assertTrue( SPARQLParserRegistry.containsParserFactory(SPARQLStar.syntax) );
	assertTrue( SPARQLParserRegistry.parser(SPARQLStar.syntax) instanceof ParserSPARQLStar );

	final String queryString = "SELECT * WHERE { <<?s ?p ?o>> ?p2 ?o2 }";
	QueryFactory.create(queryString, SPARQLStar.syntax);

	try {
		QueryFactory.create(queryString); // This should fail with the
	}                                     // default SPARQL parser.
	catch ( QueryParseException e ) {  // Hence, this exception 
		return;                        // is expected.
	}
	fail( "Expected exception not thrown." );
}
 
Example 2
Source Project: rdflint   Source File: CustomQueryValidator.java    License: MIT License 6 votes vote down vote up
@Override
public void validateTripleSet(LintProblemSet problems, String file, List<Triple> tripeSet) {
  if (this.getParameters().getRules() == null) {
    return;
  }
  // execute sparql & custom validation
  Graph g = Factory.createGraphMem();
  tripeSet.forEach(g::add);
  Model m = ModelFactory.createModelForGraph(g);

  this.getParameters().getRules().stream()
      .filter(r -> file.matches(r.getTarget()))
      .forEach(r -> {
        Query query = QueryFactory.create(r.getQuery());
        QueryExecution qe = QueryExecutionFactory.create(query, m);

        Binding binding = new Binding();
        binding.setVariable("rs", qe.execSelect());
        binding.setVariable("log", new ProblemLogger(this, problems, file, r.getName()));
        GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
        shell.evaluate(r.getValid());
      });
}
 
Example 3
private boolean checkIsOnlydbo(final String sparqlQuery) throws QueryParseException {
	if (sparqlQuery == null) {
		return false;
	}
	Query q = QueryFactory.create(sparqlQuery);
	PrefixMapping prefixMap = q.getPrefixMapping();
	Map<String, String> map = new HashMap<>(prefixMap.getNsPrefixMap());

	Set<Entry<String, String>> remove = new HashSet<>();
	for (Entry<String, String> it : map.entrySet()) {
		if (it.getKey().equals("rdf") || it.getKey().equals("rdfs") || it.getValue().equals(DBO_URI) || it.getValue().equals(RES_URI)) {
			remove.add(it);
		}
	}
	map.entrySet().removeAll(remove);
	return map.isEmpty();
}
 
Example 4
Source Project: sparql-generate   Source File: LocationMapperAccept.java    License: Apache License 2.0 6 votes vote down vote up
public LocationMapperAccept(final Model configurationModel) {
    Query q = QueryFactory.create("PREFIX lm: <http://jena.hpl.hp.com/2004/08/location-mapping#>"
            + "SELECT * WHERE {"
            + "[] lm:mapping ?e ."
            + "?e lm:name ?name ; lm:altName ?alt ."
            + "OPTIONAL { ?e lm:media ?media . } "
            + "}");
    try (QueryExecution exec = QueryExecutionFactory.create(q, configurationModel)) {
        exec.execSelect().forEachRemaining((result) -> {
            String name = null, altName = null, media = null;
            try {
                name = result.getLiteral("name").getString();
                altName = result.getLiteral("alt").getString();
                media = (result.getLiteral("media") == null ? null : result.getLiteral("media").getString());
                altLocations.put(new LookUpRequest(name, media), new LookUpRequest(altName, media));
            } catch (Exception ex) {
                log.debug("Error while reading mapping in configuration model for name " + name + ", alt " + altName + ", media " + media, ex);
            }
        });
    }
}
 
Example 5
Source Project: sparql-generate   Source File: PlanFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A factory that creates a {@link RootPlan} from a query.
 *
 * @param queryStr the string representation of the SPARQL-Generate or
 * SPARQL-Template Query.
 * @param base the base URI, if not set explicitly in the query string
 * @return the RootPlan that may be used to execute the query.
 */
public static final RootPlan create(final String queryStr, String base) {
    Objects.requireNonNull(queryStr, "Parameter string must not be null");
    SPARQLExtQuery query;
    try {
        query = (SPARQLExtQuery) QueryFactory.create(queryStr, base,
                SPARQLExt.SYNTAX);
        if(!query.explicitlySetBaseURI()) {
        	query.setBaseURI(base);
        }
    } catch (QueryParseException ex) {
        throw new SPARQLExtException(
                "Error while parsing the query \n" + queryStr, ex);
    }
    LOG.trace("Creating plan for query: \n" + query);
    return create(query);
}
 
Example 6
Source Project: Processor   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
public OntModel fixOntModel(OntModel ontModel)
    {
        if (ontModel == null) throw new IllegalArgumentException("Model cannot be null");
        
        OntModel fixedModel = ModelFactory.createOntologyModel(ontModel.getSpecification());
        Query fix = QueryFactory.create("CONSTRUCT\n" +
"{\n" +
"  ?s ?p ?o\n" +
"}\n" +
"WHERE\n" +
"{\n" +
"  ?s ?p ?o\n" +
"  FILTER (!(?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?o = <https://www.w3.org/ns/ldt#Constraint>))\n" +
"}");
        
        try (QueryExecution qex = QueryExecutionFactory.create(fix, ontModel))
        {
            fixedModel.add(qex.execConstruct());
        }
        
        return fixedModel;
    }
 
Example 7
private static List<RDFNode> creatingAgentsFor(Resource r) {
	logger.fine("Finding creator of " + r);
	String queryStr = sparqlPrefixes + "SELECT ?agent WHERE { \n" + " { \n"
			+ "  ?r dct:creator [ \n" + "	    rdfs:member ?agent \n"
			+ "  ] \n" + " } UNION { \n" + "   ?r dct:creator ?agent .\n "
			+ "   FILTER NOT EXISTS { ?agent rdfs:member ?member } \n"
			+ " } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			r.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("r", r);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	List<RDFNode> agents = new ArrayList<>();

	while (select.hasNext()) {
		RDFNode agent = select.next().get("agent");
		logger.fine("Found: " + agent);
		agents.add(agent);
	}
	return agents;
}
 
Example 8
private static Resource mboxForAgent(Resource agentResource) {
	logger.fine("Finding mbox of " + agentResource);
	String queryStr = sparqlPrefixes + "SELECT ?mbox WHERE { \n"
			+ "		{ ?agent foaf:mbox ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:hasEmail ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:email ?email .  \n"
			+ "       BIND(IRI(CONCAT(\"mbox:\", ?email)) AS ?mbox) \n" // legacy
			+ "	    } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			agentResource.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("agent", agentResource);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	if (select.hasNext()) {
		Resource mbox = select.next().getResource("mbox");
		logger.fine("Found mbox: " + mbox);
		return mbox;
	}
	logger.fine("mbox not found");
	return null;
}
 
Example 9
Source Project: quetzal   Source File: OCUtils.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static List<ConjunctiveQuery> loadConjunctiveQueries(File queryFile) throws IOException {
	List<ConjunctiveQuery> ret = new ArrayList<ConjunctiveQuery>();
	Reader in = new FileReader(queryFile);
	for (String queryText: SPARQLFileParser.readQueries(in)) {
		queryText= queryText.trim();
		if (queryText.startsWith("#")) {
			continue;
		}
		Query query= QueryFactory.create(queryText, Syntax.syntaxSPARQL_11);
		if (!query.isSelectType()) {
			logger.debug("Ignoring non select query: {}",query.toString());
			continue;
		}
		logger.debug("Query: {}"+query);
		ret.add(new ConjunctiveQuery(query));
	}
	in.close();
	return ret;
}
 
Example 10
Source Project: quetzal   Source File: OCUtils.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static List<Query> loadQueries(File queryFile) throws IOException {
	List<Query> ret = new ArrayList<Query>();
	Reader in = new FileReader(queryFile);
	for (String queryText: SPARQLFileParser.readQueries(in)) {
		queryText= queryText.trim();
		if (queryText.startsWith("#")) {
			continue;
		}
		Query query= QueryFactory.create(queryText, Syntax.syntaxSPARQL_11);
		if (!query.isSelectType()) {
			logger.debug("Ignoring non select query: {}",query.toString());
			continue;
		}
		logger.debug("Query: {}"+query);
		ret.add(query);
	}
	in.close();
	return ret;
}
 
Example 11
Source Project: xcurator   Source File: ExTDB5.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;
    
    // Potentially expensive query.
    String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
    // See http://incubator.apache.org/jena/documentation/query/app_api.html
    
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    try {
      ResultSet results = qexec.execSelect() ;
      for ( ; results.hasNext() ; )
      {
          QuerySolution soln = results.nextSolution() ;
          int count = soln.getLiteral("count").getInt() ;
          System.out.println("count = "+count) ;
      }
    } finally { qexec.close() ; }

    // Close the dataset.
    dataset.close();
    
}
 
Example 12
Source Project: xcurator   Source File: ExTDB4.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;
    
    // Potentially expensive query.
    String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
    // See http://incubator.apache.org/jena/documentation/query/app_api.html
    
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    ResultSet results = qexec.execSelect() ;
    ResultSetFormatter.out(results) ;
    qexec.close() ;

    dataset.close();
}
 
Example 13
Source Project: xcurator   Source File: AlgebraEx.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String []args)
{
    String s = "SELECT DISTINCT ?s { ?s ?p ?o }";
    
    // Parse
    Query query = QueryFactory.create(s) ;
    System.out.println(query) ;
    
    // Generate algebra
    Op op = Algebra.compile(query) ;
    op = Algebra.optimize(op) ;
    System.out.println(op) ;
    
    // Execute it.
    QueryIterator qIter = Algebra.exec(op, ExQuerySelect1.createModel()) ;
    
    // Results
    for ( ; qIter.hasNext() ; )
    {
        Binding b = qIter.nextBinding() ;
        System.out.println(b) ;
    }
    qIter.close() ;
}
 
Example 14
public String sparql(String subject) {

		// First query takes the most specific class from a given resource.
		String ontology_service = endpoint;

		String endpointsSparql = "select ?label where {<" + subject
				+ "> <http://www.w3.org/2000/01/rdf-schema#label> ?label FILTER (lang(?label) = 'en')} LIMIT 100";

		Query sparqlQuery = QueryFactory.create(endpointsSparql, Syntax.syntaxARQ);
		QueryEngineHTTP qexec = (QueryEngineHTTP) QueryExecutionFactory.sparqlService(ontology_service, sparqlQuery);
		qexec.setModelContentType(WebContent.contentTypeRDFXML);
		ResultSet results = qexec.execSelect();
		String property = null;
		while (results.hasNext()) {
			QuerySolution qs = results.next();
			property = qs.getLiteral("?label").getLexicalForm();
		}
		return property;

	}
 
Example 15
Source Project: RDFUnit   Source File: TagRdfUnitTestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private Set<TestCase> generate(QueryExecutionFactoryModel qef, SchemaSource source, TestGenerator testGenerator) {
    Set<TestCase> tests = new HashSet<>();

    Pattern tgPattern = testGenerator.getPattern();

    Query q = QueryFactory.create(PrefixNSService.getSparqlPrefixDecl() + testGenerator.getQuery());
    try (QueryExecution qe = qef.createQueryExecution(q) ) {
        qe.execSelect().forEachRemaining(result -> {

            Optional<TestCase> tc = generateTestFromResult(testGenerator, tgPattern, result, source);
            tc.ifPresent(tests::add);

        });
    }
    return tests;
}
 
Example 16
Source Project: RDFUnit   Source File: TestGeneratorImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid() {
    Query q;
    if (pattern == null) {
        log.error("{} : Pattern {} does not exist", getUri(), getPattern());
        return false;
    }
    try {
        q = QueryFactory.create(PrefixNSService.getSparqlPrefixDecl() + getQuery());
    } catch (Exception e) {
        log.error("{} Cannot parse query:\n{}", getUri(), PrefixNSService.getSparqlPrefixDecl() + getQuery(), e);
        return false;
    }

    Collection<Var> sv = q.getProjectVars();
    if (sv.size() != pattern.getParameters().size() + 1) {
        log.error("{} Select variables are different than Pattern parameters", getUri());
        return false;
    }


    return true;
}
 
Example 17
Source Project: RDFUnit   Source File: TestCaseWithTargetTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() {

    TestCase innerTestCAse = Mockito.mock(TestCase.class);
    when(innerTestCAse.getSparqlWhere()).thenReturn(sparqlQuery);

    TestCase testCaseWithTarget = TestCaseWithTarget.builder()
            .testCase(innerTestCAse)
            .target(target)
            .filterSparql(" ?this <http://example.cpm/p> ?value .")
            .build();

    String finalSparql = PrefixNSService.getSparqlPrefixDecl() + testCaseWithTarget.getSparqlWhere();

    assertThat(finalSparql)
            .contains(target.getPattern());

    try {
        QueryFactory.create(finalSparql);
    } catch (Exception e) {
        Fail.fail("Failed sparql query:\n" + finalSparql, e);
    }

}
 
Example 18
Source Project: tarql   Source File: ARQTest.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testQuerySetValuesDataBlock() {
	List<Var> header = vars("a", "b");
	Binding b1 = binding(header, "1", "2");
	Binding b2 = binding(header, "3", "4");

	Query q = QueryFactory.create("SELECT * {}");
	q.setValuesDataBlock(header, bindings(b1, b2));
	ResultSet rs = QueryExecutionFactory.create(q, 
			ModelFactory.createDefaultModel()).execSelect();

	assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars());
	assertTrue(rs.hasNext());
	assertEquals(b1, rs.nextBinding());
	assertTrue(rs.hasNext());
	assertEquals(b2, rs.nextBinding());
	assertFalse(rs.hasNext());
}
 
Example 19
Source Project: tarql   Source File: ARQTest.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testQueryAddValuesInQueryPattern() {
	List<Var> header = vars("a", "b");
	Binding b1 = binding(header, "1", "2");
	Binding b2 = binding(header, "3", "4");

	Query q = QueryFactory.create("SELECT * {}");
	ElementGroup group = new ElementGroup();
	ElementData table = new ElementData();
	table.add(Var.alloc("a"));
	table.add(Var.alloc("b"));
	table.add(b1);
	table.add(b2);
	group.addElement(q.getQueryPattern());
	group.addElement(table);
	q.setQueryPattern(group);
	ResultSet rs = QueryExecutionFactory.create(q, 
			ModelFactory.createDefaultModel()).execSelect();

	assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars());
	assertTrue(rs.hasNext());
	assertEquals(b1, rs.nextBinding());
	assertTrue(rs.hasNext());
	assertEquals(b2, rs.nextBinding());
	assertFalse(rs.hasNext());
}
 
Example 20
protected void checkBgpAndBindOnlyQuery( String sparqlstarQueryString, String expectedResultQuery )
{
	final String baseIRI = null;
	final Query expectedQuery = QueryFactory.create(expectedResultQuery, baseIRI, Syntax.syntaxSPARQL);
	final ElementGroup expectedEG = (ElementGroup) expectedQuery.getQueryPattern();

	final Query convertedQuery = convert( sparqlstarQueryString );
	final ElementGroup convertedEG = (ElementGroup) convertedQuery.getQueryPattern();
	
	checkForEquivalence( expectedEG, mergeElementPathBlocks(convertedEG) );
}
 
Example 21
Source Project: NLIWOD   Source File: SPARQL.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Tries to parse query with apache.jena . If fails, returns false.
 *
 * @param sparql
 * @return
 */
public static boolean isValidSparqlQuery(final String sparql) {
	try {
		QueryFactory.create(sparql);
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 22
/**
 * Adds the declaration of a prefix, if its used in the sparql query, but not declared. As global prefix source {@link #globalPrefixMapping} is used, which is initialized with data from resource
 * "prefixes.properties"
 * <p>
 * In query defined prefixes override.
 * <p>
 * If uris are given in the query body which can be represented with a prefix, the uris are replaced with a prefix and a prefix declaration will be added. E.g.
 * "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" is present, it will be replaced with "rdf:type", and prefix declaration for "rdf" will be added.
 * <p>
 * This will not remove unused prefix declarations.
 * <p>
 * if you wonder why keyword "a" is replaced, this is correct behavior. This is, because mapping for rdf: is set in a PrefixMap(its default in global).
 *
 * @param sparqlQuery
 *            a sparql query
 * @return the same sparql query, but with missing PREFIX declarations added.
 */
public static String addMissingPrefixes(final String sparqlQuery) {

	/**
	 * Create a custom two stage prefix mapping. Global mappings are those defined in prefixes.properties, local mappings are those present in the querystring. Single global mappings will be added
	 * to local mappings if 1) local cannot resolve it 2) global can resolve it, 3) it is deemed as a correct mapping for given uri by the parser.
	 */
	PrefixMapping2 pmap = new TwoStagePrefixMapping(globalPrefixMapping);

	/**
	 * Create empty query, set custom mapping
	 */
	Query q1 = QueryFactory.create();
	q1.setPrefixMapping(pmap);

	/**
	 * Parse the string. if e.g. rdf:type is present in query, but there was no ""PREFIX rdf:" , they will be resolved durig this process.
	 */
	q1 = QueryFactory.parse(q1, sparqlQuery, null, null);

	/**
	 * If uris are given in the actual query which can be represented with a prefix, the uris are replaced with a prefix and a prefix declaration will be added. E.g.
	 * "<http://www.w3.org/1999/02/22-rdf-syntax-ns#>" is present, it will be replaced with "rdf:", and prefix declaration for "rdf" will be added.
	 * <p>
	 * We have to call toString twice, because the serialization of the query {@Link org.apache.jena.sparql.core.Prologue} is done before serializing the query body (thus replacing URIS and
	 * setting prefixes in mapping). so, query gets replaced, but the already done prefix declaration strings are not modified. After first toString call, all prefixes are set in the mapping,
	 * allowing for adequate serialization now.
	 */
	q1.toString();

	return q1.toString();

}
 
Example 23
Source Project: NLIWOD   Source File: EJQuestion.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public EJQuestion setLanguage(final Vector<EJLanguage> language) {
	this.language = language;
	for (EJLanguage lang : this.language) {
		try {
			QueryFactory.create(lang.getSparql());
		} catch (Exception e) {
			this.language.remove(lang);
		}
	}
	return this;
}
 
Example 24
@Test
public void quickParseabilityTest() {
	List<IQuestion> questions = LoaderController.load(Dataset.QALD7_Train_Wikidata_en);
	questions.addAll(LoaderController.load(Dataset.QALD7_Test_Wikidata_en));
	for (IQuestion it : questions) {
		String sparqlQuery = it.getSparqlQuery();
		System.out.println(sparqlQuery);
		QueryFactory.create(sparqlQuery);
	}
}
 
Example 25
@Test
public void extractProjectionVarsTest() {
	Query q = QueryFactory.create("prefix  dbp:  <http://dbpedia.org/resource/> " + "prefix  dbp2: <http://dbpedia.org/ontology/> " + "select  ?x where  { dbp:total dbp2:thumbnail ?thumbnail. "
	        		+ "?thumbnail dbp2:thumbnail ?x. ?y dbp2:thumbnail ?c}");
	
	String realAnswer = "[?thumbnail @http://dbpedia.org/ontology/thumbnail ?x]";
	
	TriplePatternExtractor triplePatternExtractor = new TriplePatternExtractor();
	Map<Var,Set<Triple>> answer = triplePatternExtractor.extractTriplePatternsForProjectionVars(q);
	Set<Triple> extractedTriple = answer.get(q.getProjectVars().get(0));
	
	Assert.assertTrue(realAnswer.equals(extractedTriple.toString()));
}
 
Example 26
@Test
public void extractTripleTest() {
	Query q = QueryFactory.create("prefix  dbp:  <http://dbpedia.org/resource/> " + "prefix  dbp2: <http://dbpedia.org/ontology/> " + "select  ?y ?c where  { dbp:total dbp2:thumbnail ?thumbnail. "
	        		+ "?thumbnail dbp2:thumbnail ?y. ?x dbp2:thumbnail ?c}");
	
	String realAnswer = "[?x @http://dbpedia.org/ontology/thumbnail ?c]";
	
	TriplePatternExtractor triplePatternExtractor = new TriplePatternExtractor();
	Set<Triple> answer = triplePatternExtractor.extractTriplePatterns(q, q.getProjectVars().get(1));
	Assert.assertTrue(realAnswer.equals(answer.toString()));
}
 
Example 27
Source Project: JedAIToolkit   Source File: EntitySPARQLReader.java    License: Apache License 2.0 5 votes vote down vote up
private void readEndpoint(String endpointUrl) throws IOException {
    //read each ntriples
    //get spo, create a separate profile for each separate subject,
    //with Attribute=predicate and Value=object
    final String sparqlQueryString1 = "select ?a ?b ?c where {?a ?b ?c}";

    final Query query = QueryFactory.create(sparqlQueryString1);
    try (QueryExecution qexec = QueryExecutionFactory.sparqlService(endpointUrl, query)) {
        final ResultSet results = qexec.execSelect();
        //ResultSetFormatter.out(System.out, results, query);
        //results = qexec.execSelect();
        
        while (results.hasNext()) {
            final QuerySolution qs = results.next();
            
            final String sub = qs.get("a").toString();
            final String pred = qs.get("b").toString();
            final String obj = qs.get("c").toString();
            if (attributesToExclude.contains(pred)) {
                continue;
            }
            
            //if already exists a profile for the subject, simply add po as <Att>-<Value>
            EntityProfile entityProfile = urlToEntity.get(sub);
            if (entityProfile == null) {
                entityProfile = new EntityProfile(sub);
                entityProfiles.add(entityProfile);
                urlToEntity.put(sub, entityProfile);
            }
            
            if (!obj.isEmpty()) {
                entityProfile.addAttribute(pred, obj);
            }
        }
    }
    //ResultSetFormatter.out(System.out, results, query);
    //results = qexec.execSelect();
}
 
Example 28
Source Project: gerbil   Source File: ERDDataset2.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Marking> findMarkings(String[] text, File annFile) throws GerbilException {
	List<Marking> markings = new ArrayList<Marking>();
	try (BufferedReader breader = new BufferedReader(new InputStreamReader(
			new FileInputStream(annFile), Charset.forName("UTF-8")))) {
		String line;
		
		while ((line = breader.readLine()) != null) {
			if(line.isEmpty()){
				continue;
			}
			String[] annotation = line.split("\t");
			int searchID = getTrecID(text[0]);
			int annoID = getTrecID(annotation[0]);
			if(searchID == annoID){
				int start = text[1].indexOf(annotation[3]);
				int length = annotation[3].length();
				
				//FIXME time consuming!
                   String freebaseID = annotation[2].substring(1, annotation[2].length()).replace("/",".");
                   Query query = QueryFactory.create(queryTemp.replace("%%v%%", freebaseID));
                   QueryExecution qexec = QueryExecutionFactory.createServiceRequest(DBPEDIA_SERVICE, query);
                   String uri =  qexec.execSelect().next().getResource("s").getURI();
                   
				
				markings.add(new NamedEntity(start, length, uri));
			}
			else if(annoID > searchID){
				//There is no annotation for the given text
				break;
			}
		}
	} catch (IOException e) {
		throw new GerbilException("Exception while reading dataset.", e,
				ErrorTypes.DATASET_LOADING_ERROR);
	}

	return markings;
}
 
Example 29
@Override
public Model generateTripleStats(String taskID, String resource, String property) {
	QueryStatistics qs = new QueryStatistics();
	String rdfs = "http://www.w3.org/2000/01/rdf-schema#";
	Model model = ModelFactory.createDefaultModel();

	for (File queryFile : queryFiles) {
		try {
			String query = FileUtils.readLineAt(0, queryFile);
			Query q = QueryFactory.create(query);
			qs.getStatistics(q);
			QueryStatistics qs2 = new QueryStatistics();
			qs2.getStatistics(q);

			String subject = resource + hashcode + "/" + queryFile.getName();

			model.add(model.createResource(subject), ResourceFactory.createProperty(rdfs + "ID"), queryFile.getName().replace("sparql", ""));
			model.add(model.createResource(subject), RDFS.label, query);
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "aggregations"), model.createTypedLiteral(qs2.aggr));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "filter"), model.createTypedLiteral(qs2.filter));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "groupBy"), model.createTypedLiteral(qs2.groupBy));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "having"), model.createTypedLiteral(qs2.having));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "triples"), model.createTypedLiteral(qs2.triples));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "offset"), model.createTypedLiteral(qs2.offset));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "optional"), model.createTypedLiteral(qs2.optional));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "orderBy"), model.createTypedLiteral(qs2.orderBy));
			model.add(model.createResource(subject), ResourceFactory.createProperty(property + "union"), model.createTypedLiteral(qs2.union));

		} catch (IOException e) {
			LOGGER.error("[QueryHandler: {{}}] Cannot read file {{}}", this.getClass().getName(),
					queryFile.getName());
		}
	}
	return model;
}
 
Example 30
/**
 * Tests the convert to select method
 */
@Test
public void testConverting() {
	ParameterizedSparqlString pss = new ParameterizedSparqlString();
	pss.setCommandText(query);
	
	assertEquals(QueryFactory.create(expectedQuery), handler.convertToSelect(pss, varNames));
}