| 750 | public SClass[] countInstances(String[] graphURIs, SClass[] classes) throws Exception{ |
| 751 | if( classes == null || classes.length == 0 ){ |
| 752 | return new SClass[0]; |
| 753 | } |
| 754 | HashMap<String, SClass> classMap = new HashMap<String, SClass>(); |
| 755 | for(SClass sc: classes){ |
| 756 | classMap.put(sc.getClassURI(), sc); |
| 757 | } |
| 758 | StringBuffer queryStr = new StringBuffer(); |
| 759 | queryStr.append("PREFIX owl: <http://www.w3.org/2002/07/owl#>\n"); |
| 760 | queryStr.append("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"); |
| 761 | queryStr.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"); |
| 762 | queryStr.append("SELECT DISTINCT ?cls (COUNT(?is) AS ?numOfInstances)\n"); |
| 763 | if (graphURIs != null) { |
| 764 | for (String graphURI : graphURIs) { |
| 765 | queryStr.append("FROM <"); |
| 766 | queryStr.append(graphURI); |
| 767 | queryStr.append(">\n"); |
| 768 | } |
| 769 | } |
| 770 | queryStr.append("WHERE{\n"); |
| 771 | queryStr.append(" ?is rdf:type ?cls.\n"); |
| 772 | queryStr.append(" FILTER(?cls IN ("); |
| 773 | boolean f = false; |
| 774 | Set<String> clsSet = classMap.keySet(); |
| 775 | for (String clsURI : clsSet) { |
| 776 | if (f) { |
| 777 | queryStr.append(", "); |
| 778 | } |
| 779 | f = true; |
| 780 | queryStr.append("<"); |
| 781 | queryStr.append(clsURI); |
| 782 | queryStr.append(">"); |
| 783 | } |
| 784 | queryStr.append("))\n"); |
| 785 | queryStr.append("} GROUP BY ?cls"); |
| 786 | |
| 787 | System.out.println(queryStr.toString()); |
| 788 | |
| 789 | Query query = QueryFactory.create(queryStr.toString()); |
| 790 | QueryExecution qexec = QueryExecutionFactory.sparqlService(endpointURI, |
| 791 | query); |
| 792 | |
| 793 | ResultSet results = qexec.execSelect(); |
| 794 | for (; results.hasNext();) { |
| 795 | QuerySolution sol = results.next(); |
| 796 | String uri = sol.getResource("cls").getURI(); |
| 797 | SClass sc = classMap.get(uri); |
| 798 | Literal lit = sol.getLiteral("numOfInstances"); |
| 799 | if (lit != null) { |
| 800 | int numOfInstances = lit.getInt(); |
| 801 | sc.setNumOfInstances(numOfInstances); |
| 802 | } |
| 803 | } |
| 804 | qexec.close(); |
| 805 | |
| 806 | return classes; |
| 807 | } |
| 808 | |