diff --git a/.gitignore b/.gitignore index ebfd2a7..6a95d52 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ build databases stores *~ +/.idea catalog-* \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..1e712f9 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,19 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..3b31283 --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_3_0.xml b/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_3_0.xml new file mode 100644 index 0000000..e90bc9c --- /dev/null +++ b/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_3_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_3_3.xml b/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_3_3.xml new file mode 100644 index 0000000..87b1692 --- /dev/null +++ b/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_3_3.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_3_3.xml b/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_3_3.xml new file mode 100644 index 0000000..4d18ceb --- /dev/null +++ b/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_3_3.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__com_github_andrewoma_dexx_dexx_collections_0_2.xml b/.idea/libraries/Maven__com_github_andrewoma_dexx_dexx_collections_0_2.xml new file mode 100644 index 0000000..04210c5 --- /dev/null +++ b/.idea/libraries/Maven__com_github_andrewoma_dexx_dexx_collections_0_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__com_github_jsonld_java_jsonld_java_0_7_0.xml b/.idea/libraries/Maven__com_github_jsonld_java_jsonld_java_0_7_0.xml new file mode 100644 index 0000000..151a99f --- /dev/null +++ b/.idea/libraries/Maven__com_github_jsonld_java_jsonld_java_0_7_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__com_openlink_virtuoso_virtjdbc4_1_7_1_0.xml b/.idea/libraries/Maven__com_openlink_virtuoso_virtjdbc4_1_7_1_0.xml new file mode 100644 index 0000000..6df5cf8 --- /dev/null +++ b/.idea/libraries/Maven__com_openlink_virtuoso_virtjdbc4_1_7_1_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__commons_cli_commons_cli_1_3.xml b/.idea/libraries/Maven__commons_cli_commons_cli_1_3.xml new file mode 100644 index 0000000..49e7d40 --- /dev/null +++ b/.idea/libraries/Maven__commons_cli_commons_cli_1_3.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__commons_codec_commons_codec_1_6.xml b/.idea/libraries/Maven__commons_codec_commons_codec_1_6.xml new file mode 100644 index 0000000..e8a6a9f --- /dev/null +++ b/.idea/libraries/Maven__commons_codec_commons_codec_1_6.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__commons_io_commons_io_2_4.xml b/.idea/libraries/Maven__commons_io_commons_io_2_4.xml new file mode 100644 index 0000000..bc2aad0 --- /dev/null +++ b/.idea/libraries/Maven__commons_io_commons_io_2_4.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__log4j_log4j_1_2_17.xml b/.idea/libraries/Maven__log4j_log4j_1_2_17.xml new file mode 100644 index 0000000..e383c1b --- /dev/null +++ b/.idea/libraries/Maven__log4j_log4j_1_2_17.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_commons_commons_csv_1_0.xml b/.idea/libraries/Maven__org_apache_commons_commons_csv_1_0.xml new file mode 100644 index 0000000..bce492c --- /dev/null +++ b/.idea/libraries/Maven__org_apache_commons_commons_csv_1_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_commons_commons_lang3_3_3_2.xml b/.idea/libraries/Maven__org_apache_commons_commons_lang3_3_3_2.xml new file mode 100644 index 0000000..83cba3e --- /dev/null +++ b/.idea/libraries/Maven__org_apache_commons_commons_lang3_3_3_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_4_2_6.xml b/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_4_2_6.xml new file mode 100644 index 0000000..d869964 --- /dev/null +++ b/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_4_2_6.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_cache_4_2_6.xml b/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_cache_4_2_6.xml new file mode 100644 index 0000000..9b8a172 --- /dev/null +++ b/.idea/libraries/Maven__org_apache_httpcomponents_httpclient_cache_4_2_6.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_httpcomponents_httpcore_4_2_5.xml b/.idea/libraries/Maven__org_apache_httpcomponents_httpcore_4_2_5.xml new file mode 100644 index 0000000..fb94228 --- /dev/null +++ b/.idea/libraries/Maven__org_apache_httpcomponents_httpcore_4_2_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_jena_jena_arq_3_0_1.xml b/.idea/libraries/Maven__org_apache_jena_jena_arq_3_0_1.xml new file mode 100644 index 0000000..3cac16a --- /dev/null +++ b/.idea/libraries/Maven__org_apache_jena_jena_arq_3_0_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_jena_jena_base_3_0_1.xml b/.idea/libraries/Maven__org_apache_jena_jena_base_3_0_1.xml new file mode 100644 index 0000000..14cdff7 --- /dev/null +++ b/.idea/libraries/Maven__org_apache_jena_jena_base_3_0_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_jena_jena_core_3_0_1.xml b/.idea/libraries/Maven__org_apache_jena_jena_core_3_0_1.xml new file mode 100644 index 0000000..9a3afaa --- /dev/null +++ b/.idea/libraries/Maven__org_apache_jena_jena_core_3_0_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_jena_jena_iri_3_0_1.xml b/.idea/libraries/Maven__org_apache_jena_jena_iri_3_0_1.xml new file mode 100644 index 0000000..48bd070 --- /dev/null +++ b/.idea/libraries/Maven__org_apache_jena_jena_iri_3_0_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_jena_jena_shaded_guava_3_0_1.xml b/.idea/libraries/Maven__org_apache_jena_jena_shaded_guava_3_0_1.xml new file mode 100644 index 0000000..b476c7b --- /dev/null +++ b/.idea/libraries/Maven__org_apache_jena_jena_shaded_guava_3_0_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_apache_thrift_libthrift_0_9_2.xml b/.idea/libraries/Maven__org_apache_thrift_libthrift_0_9_2.xml new file mode 100644 index 0000000..ac1ee5b --- /dev/null +++ b/.idea/libraries/Maven__org_apache_thrift_libthrift_0_9_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_slf4j_jcl_over_slf4j_1_7_12.xml b/.idea/libraries/Maven__org_slf4j_jcl_over_slf4j_1_7_12.xml new file mode 100644 index 0000000..5aeb229 --- /dev/null +++ b/.idea/libraries/Maven__org_slf4j_jcl_over_slf4j_1_7_12.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_13.xml b/.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_13.xml new file mode 100644 index 0000000..4fd913d --- /dev/null +++ b/.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_13.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__org_slf4j_slf4j_log4j12_1_7_12.xml b/.idea/libraries/Maven__org_slf4j_slf4j_log4j12_1_7_12.xml new file mode 100644 index 0000000..855bb31 --- /dev/null +++ b/.idea/libraries/Maven__org_slf4j_slf4j_log4j12_1_7_12.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__virtuoso_virtjdbc_4_1.xml b/.idea/libraries/Maven__virtuoso_virtjdbc_4_1.xml new file mode 100644 index 0000000..c728eed --- /dev/null +++ b/.idea/libraries/Maven__virtuoso_virtjdbc_4_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__xerces_xercesImpl_2_11_0.xml b/.idea/libraries/Maven__xerces_xercesImpl_2_11_0.xml new file mode 100644 index 0000000..285d5e8 --- /dev/null +++ b/.idea/libraries/Maven__xerces_xercesImpl_2_11_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/Maven__xml_apis_xml_apis_1_4_01.xml b/.idea/libraries/Maven__xml_apis_xml_apis_1_4_01.xml new file mode 100644 index 0000000..9aadd29 --- /dev/null +++ b/.idea/libraries/Maven__xml_apis_xml_apis_1_4_01.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..e96534f --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index b2d7864..d6ca9b5 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,9 @@ The Virtuoso Jena RDF Data Provider is a fully operational Native Graph Model St http://virtuoso.openlinksw.com/dataspace/doc/dav/wiki/Main/VirtJenaProvider -However, current release (2.6.2) of the Virtuoso Jena Provider is designed to work with Virtuoso JDBC 3 Driver and Jena versions above 2.5.5 +However, current release (3.0.1) of the Virtuoso Jena Provider is designed to work with Virtuoso JDBC 3 Driver and Jena versions above 2.5.5 Current release supports neither Virtuoso JDBC 4 Driver nor Jena version 2.6.4 above, where Jena Framework became a top level Apache Project. -This project includes modifications on Virtuoso Jena Provider 2.6.2 so that, it can work with Virtuoso JDBC 4 Driver and current latest Jena release 2.10.0 +This project includes modifications on Virtuoso Jena Provider 2.6.2 so that, it can work with Virtuoso JDBC 4 Driver and current latest Jena release 3.0.1 ## Installation =========== diff --git a/lib/virtuoso/virtjdbc4/4.0/virtjdbc4-4.0.jar b/lib/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar similarity index 69% rename from lib/virtuoso/virtjdbc4/4.0/virtjdbc4-4.0.jar rename to lib/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar index 2663a6e..b207f0c 100644 Binary files a/lib/virtuoso/virtjdbc4/4.0/virtjdbc4-4.0.jar and b/lib/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar differ diff --git a/lib/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom b/lib/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom new file mode 100644 index 0000000..02fa48e --- /dev/null +++ b/lib/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom @@ -0,0 +1,27 @@ + + 4.0.0 + virtuoso + virtjdbc + 4.0 + POM was created from install:install-file + diff --git a/lib/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar b/lib/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar new file mode 100644 index 0000000..1c6ccec Binary files /dev/null and b/lib/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar differ diff --git a/lib/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom b/lib/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom new file mode 100644 index 0000000..87605c7 --- /dev/null +++ b/lib/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom @@ -0,0 +1,27 @@ + + 4.0.0 + virtuoso + virtjdbc + 4.1 + POM was created from install:install-file + diff --git a/lib/virtuoso/virtjdbc/maven-metadata-local.xml b/lib/virtuoso/virtjdbc/maven-metadata-local.xml new file mode 100644 index 0000000..a0d93d6 --- /dev/null +++ b/lib/virtuoso/virtjdbc/maven-metadata-local.xml @@ -0,0 +1,30 @@ + + virtuoso + virtjdbc + + 4.1 + + 4.1 + 4.0 + + + diff --git a/lib/virtuoso/virtjdbc4/4.0/_maven.repositories b/lib/virtuoso/virtjdbc4/4.0/_maven.repositories deleted file mode 100644 index 5c7d78e..0000000 --- a/lib/virtuoso/virtjdbc4/4.0/_maven.repositories +++ /dev/null @@ -1,4 +0,0 @@ -#NOTE: This is an internal implementation file, its format can be changed without prior notice. -#Wed Jan 30 11:17:50 EET 2013 -virtjdbc3-3.0.jar>= -virtjdbc3-3.0.pom>= diff --git a/lib/virtuoso/virtjdbc4/4.0/virtjdbc4-4.0.pom b/lib/virtuoso/virtjdbc4/4.0/virtjdbc4-4.0.pom deleted file mode 100644 index d427d19..0000000 --- a/lib/virtuoso/virtjdbc4/4.0/virtjdbc4-4.0.pom +++ /dev/null @@ -1,9 +0,0 @@ - - - 4.0.0 - virtuoso - virtjdbc4 - 4.0 - POM was created from install:install-file - diff --git a/lib/virtuoso/virtjdbc4/maven-metadata-local.xml b/lib/virtuoso/virtjdbc4/maven-metadata-local.xml deleted file mode 100644 index 7c3f651..0000000 --- a/lib/virtuoso/virtjdbc4/maven-metadata-local.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - virtuoso - virtjdbc4 - - 4.0 - - 4.0 - - 20130130091750 - - diff --git a/pom.xml b/pom.xml index 5c7a351..ae0b5aa 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ tr.com.srdc virt-jena - 2.6.2-srdc + 3.0.1-srdc jar Virtuoso Jena Wrapper - SRDC updates with org.apache.jena @@ -13,20 +13,38 @@ - - virtuoso - virtjdbc4 - 4.0 + + + virtuoso + virtjdbc + jar + 4.1 + true + + + + com.openlink.virtuoso + virtjdbc4-1 + 7.1.0 + true org.apache.jena jena-core - 2.10.0 + 3.0.1 + true org.apache.jena jena-arq - 2.10.0 + 3.0.1 + true + + + org.slf4j + slf4j-api + 1.7.13 + true @@ -55,11 +73,40 @@ + - in-project-virtjdbc + + always + + + always + + in-project-virtjdbc In Project Repo for VirtJDBC file://${project.basedir}/lib + + + + + maven.aksw.internal + University Leipzig, AKSW Maven2 Repository + http://maven.aksw.org/archiva/repository/internal + + + maven.aksw.snapshots + University Leipzig, AKSW Maven2 Repository + http://maven.aksw.org/archiva/repository/snapshots + diff --git a/src/main/java/virtuoso/jena/driver/Version.java b/src/main/java/virtuoso/jena/driver/Version.java index 3e1b518..83b6207 100644 --- a/src/main/java/virtuoso/jena/driver/Version.java +++ b/src/main/java/virtuoso/jena/driver/Version.java @@ -25,15 +25,15 @@ public class Version { - protected static final String DRV_VER = "2.6.2"; + protected static final String DRV_VER = "3.0.1"; - // The major and minor version number - protected static final String build_id = "1.6"; + // The major and minor version number + protected static final String build_id = "1.7"; - public static void main(String args[]) { - System.out - .println("OpenLink Virtuoso(TM) Provider for Jena(TM) Version " - + DRV_VER + " [Build " + build_id + "]"); - } + public static void main(String args[]) { + System.out + .println("OpenLink Virtuoso(TM) Provider for Jena(TM) Version " + + DRV_VER + " [Build " + build_id + "]"); + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtBulkUpdateHandler.java b/src/main/java/virtuoso/jena/driver/VirtBulkUpdateHandler.java index 8adcb10..3847b39 100644 --- a/src/main/java/virtuoso/jena/driver/VirtBulkUpdateHandler.java +++ b/src/main/java/virtuoso/jena/driver/VirtBulkUpdateHandler.java @@ -22,97 +22,96 @@ */ package virtuoso.jena.driver; +import org.apache.jena.graph.*; +import org.apache.jena.graph.impl.GraphBase; +import org.apache.jena.util.iterator.ExtendedIterator; + import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; -import com.hp.hpl.jena.graph.GraphEvents; -import com.hp.hpl.jena.graph.Node; -import com.hp.hpl.jena.graph.Triple; -import com.hp.hpl.jena.graph.impl.SimpleBulkUpdateHandler; -import com.hp.hpl.jena.shared.JenaException; - -public class VirtBulkUpdateHandler extends SimpleBulkUpdateHandler { - - public VirtBulkUpdateHandler(VirtGraph parent) { - super(parent); - } - - // --java5 or newer @Override - public void add(Triple[] triples) { - addIterator(Arrays.asList(triples).iterator(), false); - manager.notifyAddArray(graph, triples); - } - - // --java5 or newer @Override - protected void add(List triples, boolean notify) { - addIterator(triples.iterator(), false); - if (notify) - manager.notifyAddList(graph, triples); - } - - // --java5 or newer @Override - public void addIterator(Iterator it, boolean notify) { - VirtGraph _graph = (VirtGraph) this.graph; - List list = notify ? new ArrayList() : null; - - try { - boolean autoCommit = _graph.getConnection().getAutoCommit(); - if (autoCommit) - _graph.getConnection().setAutoCommit(false); - _graph.add(it, list); - if (autoCommit) { - _graph.getConnection().commit(); - _graph.getConnection().setAutoCommit(true); - } - } catch (Exception e) { - throw new JenaException("Couldn't create transaction:" + e); - } - if (notify) - manager.notifyAddIterator(graph, list); - } - - public void delete(Triple[] triples) { - deleteIterator(Arrays.asList(triples).iterator(), false); - manager.notifyDeleteArray(graph, triples); - } - - protected void delete(List triples, boolean notify) { - deleteIterator(triples.iterator(), false); - if (notify) - manager.notifyDeleteList(graph, triples); - } - - public void deleteIterator(Iterator it, boolean notify) { - VirtGraph _graph = (VirtGraph) this.graph; - List list = notify ? new ArrayList() : null; - - try { - boolean autoCommit = _graph.getConnection().getAutoCommit(); - if (autoCommit) - _graph.getConnection().setAutoCommit(false); - _graph.delete(it, list); - if (autoCommit) { - _graph.getConnection().commit(); - _graph.getConnection().setAutoCommit(true); - } - } catch (Exception e) { - throw new JenaException("Couldn't create transaction:" + e); - } - if (notify) - manager.notifyDeleteIterator(graph, list); - } - - public void removeAll() { - VirtGraph _graph = (VirtGraph) this.graph; - _graph.clearGraph(_graph.getGraphName()); - notifyRemoveAll(); - } - - public void remove(Node s, Node p, Node o) { - VirtGraph _graph = (VirtGraph) this.graph; - _graph.delete_match(Triple.createMatch(s, p, o)); - manager.notifyEvent(graph, GraphEvents.remove(s, p, o)); - } +/** + * @deprecated from jena 3.X.X use instead {@link VirtGraph} + */ +public class VirtBulkUpdateHandler extends GraphBase { + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtBulkUpdateHandler.class); + + private final Graph graph; + + public VirtBulkUpdateHandler(VirtGraph parent) { + super(); + graph = parent; + } + + // --java5 or newer @Override + public void add(Triple[] triples) { + addIterator(Arrays.asList(triples).iterator(), false); + gem.notifyAddArray(graph, triples); + } + + // --java5 or newer @Override + protected void add(List triples, boolean notify) { + addIterator(triples.iterator(), false); + if (notify) + gem.notifyAddList(graph, triples); + } + + // --java5 or newer @Override + public void addIterator(Iterator it, boolean notify) { + VirtGraph _graph = (VirtGraph) this.graph; + List list; + if (notify) list = new ArrayList<>(); + else list = null; + + _graph = _graph.prepareGraphConnection(_graph, it, list); + + if (notify) + gem.notifyAddIterator(_graph, list); + } + + public void delete(Triple[] triples) { + deleteIterator(Arrays.asList(triples).iterator(), false); + gem.notifyDeleteArray(graph, triples); + } + + protected void delete(List triples, boolean notify) { + deleteIterator(triples.iterator(), false); + if (notify) + gem.notifyDeleteList(graph, triples); + } + + public void deleteIterator(Iterator it, boolean notify) { + VirtGraph _graph = (VirtGraph) this.graph; + List list; + if (notify) list = new ArrayList<>(); + else list = null; + + _graph = _graph.prepareGraphConnection(_graph, it, list); + + if (notify) + gem.notifyDeleteIterator(_graph, list); + } + + public void removeAll() { + VirtGraph _graph = (VirtGraph) this.graph; + _graph.clearGraph(_graph.getGraphName()); + } + + @Override + public void remove(Node s, Node p, Node o) { + VirtGraph _graph = (VirtGraph) this.graph; + _graph.delete_match(Triple.createMatch(s, p, o)); + gem.notifyEvent(_graph, GraphEvents.remove(s, p, o)); + } + + @Override + protected ExtendedIterator graphBaseFind(Triple triplePattern) { + return super.graphBaseFind( + triplePattern.getMatchSubject(), triplePattern.getMatchPredicate(), triplePattern.getMatchObject()); + } + + } diff --git a/src/main/java/virtuoso/jena/driver/VirtDataSource.java b/src/main/java/virtuoso/jena/driver/VirtDataSource.java index 93da8e2..9b609bb 100644 --- a/src/main/java/virtuoso/jena/driver/VirtDataSource.java +++ b/src/main/java/virtuoso/jena/driver/VirtDataSource.java @@ -23,398 +23,490 @@ package virtuoso.jena.driver; import java.sql.ResultSet; +import java.sql.SQLException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import org.apache.jena.graph.Graph; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.graph.Triple; +import org.apache.jena.query.Dataset; +import org.apache.jena.query.LabelExistsException; +import org.apache.jena.query.ReadWrite; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.shared.JenaException; +import org.apache.jena.shared.Lock; +import org.apache.jena.shared.LockNone; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.core.Quad; +import org.apache.jena.sparql.util.Context; import virtuoso.jdbc4.VirtuosoDataSource; -import com.hp.hpl.jena.graph.Graph; -import com.hp.hpl.jena.graph.Node; -import com.hp.hpl.jena.graph.Triple; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.LabelExistsException; -import com.hp.hpl.jena.query.ReadWrite; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.shared.JenaException; -import com.hp.hpl.jena.shared.Lock; -import com.hp.hpl.jena.sparql.core.DatasetGraph; -import com.hp.hpl.jena.sparql.core.Quad; -import com.hp.hpl.jena.sparql.util.Context; - public class VirtDataSource extends VirtGraph implements Dataset { - /** - * Default model - may be null - according to Javadoc - */ - Model defaultModel = null; - - public VirtDataSource() { - super(); - } - - public VirtDataSource(String _graphName, VirtuosoDataSource _ds) { - super(_graphName, _ds); - } - - protected VirtDataSource(VirtGraph g) { - this.graphName = g.getGraphName(); - setReadFromAllGraphs(g.getReadFromAllGraphs()); - this.url_hostlist = g.getGraphUrl(); - this.user = g.getGraphUser(); - this.password = g.getGraphPassword(); - this.roundrobin = g.roundrobin; - setFetchSize(g.getFetchSize()); - this.connection = g.getConnection(); - } - - public VirtDataSource(String url_hostlist, String user, String password) { - super(url_hostlist, user, password); - } - - /** Set the background graph. Can be set to null for none. */ - public void setDefaultModel(Model model) { - if (!(model instanceof VirtDataSource)) - throw new IllegalArgumentException( - "VirtDataSource supports only VirtModel as default model"); - defaultModel = model; - } - - /** Set a named graph. */ - public void addNamedModel(String name, Model model) - throws LabelExistsException { - String query = "select count(*) from (sparql select * where { graph `iri(??)` { ?s ?p ?o }})f"; - ResultSet rs = null; - int ret = 0; - - checkOpen(); - try { - java.sql.PreparedStatement ps = prepareStatement(query); - ps.setString(1, name); - rs = ps.executeQuery(); - if (rs.next()) - ret = rs.getInt(1); - rs.close(); - ps.close(); - } catch (Exception e) { - throw new JenaException(e); - } - - try { - if (ret != 0) - throw new LabelExistsException("A model with ID '" + name - + "' already exists."); - Graph g = model.getGraph(); - int count = 0; - java.sql.PreparedStatement ps = prepareStatement(sinsert); - - for (Iterator i = g.find(Node.ANY, Node.ANY, Node.ANY); i.hasNext();) { - Triple t = (Triple) i.next(); - - ps.setString(1, name); - bindSubject(ps, 2, t.getSubject()); - bindPredicate(ps, 3, t.getPredicate()); - bindObject(ps, 4, t.getObject()); - ps.addBatch(); - count++; - if (count > BATCH_SIZE) { - ps.executeBatch(); - ps.clearBatch(); - count = 0; - } - } - if (count > 0) { - ps.executeBatch(); - ps.clearBatch(); - } - ps.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - /** Remove a named graph. */ - public void removeNamedModel(String name) { - String exec_text = "sparql clear graph <" + name + ">"; - - checkOpen(); - try { - java.sql.Statement stmt = createStatement(); - stmt.executeQuery(exec_text); - stmt.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - /** Change a named graph for another uisng the same name */ - public void replaceNamedModel(String name, Model model) { - try { - getConnection().setAutoCommit(false); - removeNamedModel(name); - addNamedModel(name, model); - getConnection().commit(); - getConnection().setAutoCommit(true); - } catch (Exception e) { - try { - getConnection().rollback(); - } catch (Exception e2) { - throw new JenaException( - "Could not replace model, and could not rollback!", e2); - } - throw new JenaException("Could not replace model:", e); - } - } - - /** Get the default graph as a Jena Model */ - public Model getDefaultModel() { - return defaultModel; - } - - /** Get a graph by name as a Jena Model */ - public Model getNamedModel(String name) { - try { - VirtuosoDataSource _ds = getDataSource(); - if (_ds != null) - return new VirtModel(new VirtGraph(name, _ds)); - else - return new VirtModel(new VirtGraph(name, this.getGraphUrl(), - this.getGraphUser(), this.getGraphPassword())); - } catch (Exception e) { - throw new JenaException(e); - } - } - - /** Does the dataset contain a model with the name supplied? */ - public boolean containsNamedModel(String name) { - String query = "select count(*) from (sparql select * where { graph `iri(??)` { ?s ?p ?o }})f"; - ResultSet rs = null; - int ret = 0; - - checkOpen(); - try { - java.sql.PreparedStatement ps = prepareStatement(query); - ps.setString(1, name); - rs = ps.executeQuery(); - if (rs.next()) - ret = rs.getInt(1); - rs.close(); - ps.close(); - } catch (Exception e) { - throw new JenaException(e); - } - return (ret != 0); - } - - /** List the names */ - public Iterator listNames() { - String exec_text = "DB.DBA.SPARQL_SELECT_KNOWN_GRAPHS()"; - ResultSet rs = null; - int ret = 0; - - checkOpen(); - try { - List names = new LinkedList(); - - java.sql.Statement stmt = createStatement(); - rs = stmt.executeQuery(exec_text); - while (rs.next()) - names.add(rs.getString(1)); - rs.close(); - stmt.close(); - return names.iterator(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - Lock lock = null; - - /** Get the lock for this dataset */ - public Lock getLock() { - if (lock == null) - lock = new com.hp.hpl.jena.shared.LockNone(); - return lock; - } - - /** Get the dataset in graph form */ - public DatasetGraph asDatasetGraph() { - return new VirtDataSetGraph(this); - } - - public class VirtDataSetGraph implements DatasetGraph { - - VirtDataSource vd = null; - - public VirtDataSetGraph(VirtDataSource vds) { - vd = vds; - } - - public Graph getDefaultGraph() { - return vd; - } - - public Graph getGraph(Node graphNode) { - try { - return new VirtGraph(graphNode.toString(), vd.getGraphUrl(), - vd.getGraphUser(), vd.getGraphPassword()); - } catch (Exception e) { - throw new JenaException(e); - } - } - - public boolean containsGraph(Node graphNode) { - return containsNamedModel(graphNode.toString()); - } - - public Iterator listGraphNodes() { - String exec_text = "DB.DBA.SPARQL_SELECT_KNOWN_GRAPHS()"; - ResultSet rs = null; - int ret = 0; - - vd.checkOpen(); - try { - List names = new LinkedList(); - - java.sql.Statement stmt = vd.createStatement(); - rs = stmt.executeQuery(exec_text); - while (rs.next()) - names.add(Node.createURI(rs.getString(1))); - rs.close(); - stmt.close(); - return names.iterator(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - public Lock getLock() { - return vd.getLock(); - } - - public long size() { - return vd.size(); - } - - public void close() { - vd.close(); - } - - public void add(Quad arg0) { - // TODO Auto-generated method stub - - } - - public void add(Node arg0, Node arg1, Node arg2, Node arg3) { - // TODO Auto-generated method stub - - } - - public void addGraph(Node arg0, Graph arg1) { - // TODO Auto-generated method stub - - } - - public boolean contains(Quad arg0) { - // TODO Auto-generated method stub - return false; - } - - public boolean contains(Node arg0, Node arg1, Node arg2, Node arg3) { - // TODO Auto-generated method stub - return false; - } - - public void delete(Quad arg0) { - // TODO Auto-generated method stub - - } - - public void delete(Node arg0, Node arg1, Node arg2, Node arg3) { - // TODO Auto-generated method stub - - } - - public void deleteAny(Node arg0, Node arg1, Node arg2, Node arg3) { - // TODO Auto-generated method stub - - } - - public Iterator find() { - // TODO Auto-generated method stub - return null; - } - - public Iterator find(Quad arg0) { - // TODO Auto-generated method stub - return null; - } - - public Iterator find(Node arg0, Node arg1, Node arg2, Node arg3) { - // TODO Auto-generated method stub - return null; - } - - public Iterator findNG(Node arg0, Node arg1, Node arg2, Node arg3) { - // TODO Auto-generated method stub - return null; - } - - public Context getContext() { - // TODO Auto-generated method stub - return null; - } - - public boolean isEmpty() { - // TODO Auto-generated method stub - return false; - } - - public void removeGraph(Node arg0) { - // TODO Auto-generated method stub - - } - - public void setDefaultGraph(Graph arg0) { - // TODO Auto-generated method stub - - } - - } - - public void abort() { - // TODO Auto-generated method stub - - } - - public void begin(ReadWrite arg0) { - // TODO Auto-generated method stub - - } - - public void commit() { - // TODO Auto-generated method stub - - } - - public void end() { - // TODO Auto-generated method stub + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtDataSource.class); + + /** + * Default model - may be null - according to Javadoc + */ + Model defaultModel = null; + Lock lock = null; + + public VirtDataSource() { + super(); + } + + public VirtDataSource(String _graphName, VirtuosoDataSource _ds) { + super(_graphName, _ds); + } + + protected VirtDataSource(VirtGraph g) { + this.graphName = g.getGraphName(); + setReadFromAllGraphs(g.getReadFromAllGraphs()); + this.url_hostlist = g.getGraphUrl(); + this.user = g.getGraphUser(); + this.password = g.getGraphPassword(); + this.roundrobin = g.roundrobin; + setFetchSize(g.getFetchSize()); + this.connection = g.getConnection(); + } + + public VirtDataSource(String url_hostlist, String user, String password) { + super(url_hostlist, user, password); + } + + /** + * Set a named graph. + * + * @param name the {@link String} + * @param model the {@link Model} + */ + @Override + public void addNamedModel(String name, Model model) + throws LabelExistsException { + String query = "select count(*) from (sparql select * where { graph `iri(??)` { ?s ?p ?o }})f"; + ResultSet rs; + int ret = 0; + + checkOpen(); + try { + try (java.sql.PreparedStatement ps = createPreparedStatement(query)) { + ps.setString(1, name); + rs = ps.executeQuery(); + if (rs.next()) + ret = rs.getInt(1); + rs.close(); + } + } catch (Exception e) { + throw new JenaException(e); + } + + try { + if (ret != 0) + throw new LabelExistsException("A model with ID '" + name + + "' already exists."); + Graph g = model.getGraph(); + int count = 0; + try (java.sql.PreparedStatement ps = createPreparedStatement(sinsert)) { + for (Iterator i = g.find(Node.ANY, Node.ANY, Node.ANY); i.hasNext(); ) { + Triple t = (Triple) i.next(); + + ps.setString(1, name); + bindSubject(ps, 2, t.getSubject()); + bindPredicate(ps, 3, t.getPredicate()); + bindObject(ps, 4, t.getObject()); + ps.addBatch(); + count++; + if (count > BATCH_SIZE) { + ps.executeBatch(); + ps.clearBatch(); + count = 0; + } + } + if (count > 0) { + ps.executeBatch(); + ps.clearBatch(); + } + } + } catch (LabelExistsException | SQLException e) { + throw new JenaException(e); + } + } + + /** + * Remove a named graph. + * + * @param name the {@link String} + */ + @Override + public void removeNamedModel(String name) { + String exec_text = "sparql clear graph <" + name + ">"; + + checkOpen(); + try { + try (java.sql.Statement stmt = createStatement()) { + stmt.executeQuery(exec_text); + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + /** + * Change a named graph for another uisng the same name + * + * @param name the {@link String} + * @param model the {@link Model} + */ + @Override + public void replaceNamedModel(String name, Model model) { + try { + getConnection().setAutoCommit(false); + removeNamedModel(name); + addNamedModel(name, model); + getConnection().commit(); + getConnection().setAutoCommit(true); + } catch (SQLException | LabelExistsException e) { + try { + getConnection().rollback(); + } catch (Exception e2) { + throw new JenaException( + "Could not replace model, and could not rollback!", e2); + } + throw new JenaException("Could not replace model:", e); + } + } + + /** + * Get the default graph as a Jena Model + * + * @return the {òlink Model} + */ + @Override + public Model getDefaultModel() { + return defaultModel; + } + + /** + * Set the background graph. Can be set to null for none. + * + * @param model the {@link Model} + */ + @Override + public void setDefaultModel(Model model) { + if (!(model instanceof VirtDataSource)) + throw new IllegalArgumentException( + "VirtDataSource supports only VirtModel as default model"); + defaultModel = model; + } + + /** + * Get a graph by name as a Jena Model + * + * @param name the {@link String} + * @return the {@link Model} + */ + @Override + public Model getNamedModel(String name) { + try { + VirtuosoDataSource _ds = getDataSource(); + if (_ds != null) + return new VirtModel(new VirtGraph(name, _ds)); + else + return new VirtModel(new VirtGraph(name, this.getGraphUrl(), + this.getGraphUser(), this.getGraphPassword())); + } catch (Exception e) { + throw new JenaException(e); + } + } + + /** + * Does the dataset contain a model with the name supplied? + * + * @param name the {@link String} + * @return the {@link Model} + */ + @Override + public boolean containsNamedModel(String name) { + String query = "select count(*) from (sparql select * where { graph `iri(??)` { ?s ?p ?o }})f"; + ResultSet rs; + int ret = 0; + + checkOpen(); + try { + try (java.sql.PreparedStatement ps = createPreparedStatement(query)) { + ps.setString(1, name); + rs = ps.executeQuery(); + if (rs.next()) + ret = rs.getInt(1); + rs.close(); + } + } catch (Exception e) { + throw new JenaException(e); + } + return (ret != 0); + } + + /** + * List the names + * + * @return {@link Iterator} + */ + @Override + public Iterator listNames() { + String exec_text = "DB.DBA.SPARQL_SELECT_KNOWN_GRAPHS()"; + ResultSet rs; + int ret = 0; + + checkOpen(); + try { + List names = new LinkedList<>(); + + try (java.sql.Statement stmt = createStatement()) { + rs = stmt.executeQuery(exec_text); + while (rs.next()) + names.add(rs.getString(1)); + rs.close(); + } + return names.iterator(); + } catch (Exception e) { + throw new JenaException(e); + } + } + + /** + * Get the lock for this dataset + * + * @return {@link Lock} + */ + @Override + public Lock getLock() { + if (lock == null) + lock = new LockNone(); + return lock; + } + + /** + * Get the dataset in graph form + * + * @return {@link DatasetGraph} + */ + @Override + public DatasetGraph asDatasetGraph() { + return new VirtDataSetGraph(this); + } + + @Override + public void abort() { + // TODO Auto-generated method stub + + } + + @Override + public void begin(ReadWrite arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void commit() { + // TODO Auto-generated method stub + + } + + @Override + public void end() { + // TODO Auto-generated method stub + + } + + @Override + public Context getContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isInTransaction() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsTransactions() { + // TODO Auto-generated method stub + return false; + } + + public class VirtDataSetGraph implements DatasetGraph { + + VirtDataSource vd = null; + + public VirtDataSetGraph(VirtDataSource vds) { + vd = vds; + } + + @Override + public Graph getDefaultGraph() { + return vd; + } + + @Override + public void setDefaultGraph(Graph arg0) { + // TODO Auto-generated method stub + + } + + @Override + public Graph getGraph(Node graphNode) { + try { + return new VirtGraph(graphNode.toString(), vd.getGraphUrl(), + vd.getGraphUser(), vd.getGraphPassword()); + } catch (Exception e) { + throw new JenaException(e); + } + } + + @Override + public boolean containsGraph(Node graphNode) { + return containsNamedModel(graphNode.toString()); + } + + @Override + public Iterator listGraphNodes() { + String exec_text = "DB.DBA.SPARQL_SELECT_KNOWN_GRAPHS()"; + ResultSet rs; + int ret = 0; + + vd.checkOpen(); + try { + List names = new LinkedList<>(); + + try (java.sql.Statement stmt = vd.createStatement()) { + rs = stmt.executeQuery(exec_text); + while (rs.next()) + names.add(NodeFactory.createURI(rs.getString(1))); + rs.close(); + } + return names.iterator(); + } catch (Exception e) { + throw new JenaException(e); + } + } + + @Override + public Lock getLock() { + return vd.getLock(); + } + + @Override + public long size() { + return vd.size(); + } + + @Override + public void close() { + vd.close(); + } + + @Override + public void add(Quad arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void add(Node arg0, Node arg1, Node arg2, Node arg3) { + // TODO Auto-generated method stub + + } + + @Override + public void addGraph(Node arg0, Graph arg1) { + // TODO Auto-generated method stub + + } + + @Override + public boolean contains(Quad arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void clear() { + + } + + @Override + public boolean contains(Node arg0, Node arg1, Node arg2, Node arg3) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void delete(Quad arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void delete(Node arg0, Node arg1, Node arg2, Node arg3) { + // TODO Auto-generated method stub + + } + + @Override + public void deleteAny(Node arg0, Node arg1, Node arg2, Node arg3) { + // TODO Auto-generated method stub + + } + + @Override + public Iterator find() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Iterator find(Quad arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Iterator find(Node arg0, Node arg1, Node arg2, Node arg3) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Iterator findNG(Node arg0, Node arg1, Node arg2, Node arg3) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Context getContext() { + // TODO Auto-generated method stub + return null; + } - } + @Override + public boolean isEmpty() { + // TODO Auto-generated method stub + return false; + } - public Context getContext() { - // TODO Auto-generated method stub - return null; - } + @Override + public void removeGraph(Node arg0) { + // TODO Auto-generated method stub - public boolean isInTransaction() { - // TODO Auto-generated method stub - return false; - } + } - public boolean supportsTransactions() { - // TODO Auto-generated method stub - return false; - } + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtGraph.java b/src/main/java/virtuoso/jena/driver/VirtGraph.java index 4b2b024..27148fa 100644 --- a/src/main/java/virtuoso/jena/driver/VirtGraph.java +++ b/src/main/java/virtuoso/jena/driver/VirtGraph.java @@ -28,931 +28,776 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.Iterator; -import java.util.List; - +import java.util.*; + +import org.apache.jena.datatypes.TypeMapper; +import org.apache.jena.graph.*; +import org.apache.jena.graph.impl.GraphBase; +import org.apache.jena.rdf.model.impl.ModelCom; +import org.apache.jena.shared.AddDeniedException; +import org.apache.jena.shared.DeleteDeniedException; +import org.apache.jena.shared.JenaException; +import org.apache.jena.shared.PrefixMapping; +import org.apache.jena.util.iterator.ExtendedIterator; +import org.apache.jena.util.iterator.NiceIterator; import virtuoso.jdbc4.VirtuosoConnectionPoolDataSource; import virtuoso.jdbc4.VirtuosoDataSource; -import virtuoso.sql.ExtendedString; -import virtuoso.sql.RdfBox; - -import com.hp.hpl.jena.datatypes.RDFDatatype; -import com.hp.hpl.jena.datatypes.TypeMapper; -import com.hp.hpl.jena.graph.BulkUpdateHandler; -import com.hp.hpl.jena.graph.GraphEvents; -import com.hp.hpl.jena.graph.Node; -import com.hp.hpl.jena.graph.TransactionHandler; -import com.hp.hpl.jena.graph.Triple; -import com.hp.hpl.jena.graph.TripleMatch; -import com.hp.hpl.jena.graph.impl.GraphBase; -import com.hp.hpl.jena.rdf.model.AnonId; -import com.hp.hpl.jena.rdf.model.impl.ModelCom; -import com.hp.hpl.jena.shared.AddDeniedException; -import com.hp.hpl.jena.shared.DeleteDeniedException; -import com.hp.hpl.jena.shared.JenaException; -import com.hp.hpl.jena.shared.PrefixMapping; -import com.hp.hpl.jena.util.iterator.ExtendedIterator; -import com.hp.hpl.jena.util.iterator.NiceIterator; public class VirtGraph extends GraphBase { - static { - VirtuosoQueryEngine.register(); - } - - static public final String DEFAULT = "virt:DEFAULT"; - protected String graphName; - protected boolean readFromAllGraphs = false; - protected String url_hostlist; - protected String user; - protected String password; - protected boolean roundrobin = false; - protected int prefetchSize = 200; - protected Connection connection = null; - protected String ruleSet = null; - protected boolean useSameAs = false; - protected int queryTimeout = 0; - static final String sinsert = "sparql insert into graph iri(??) { `iri(??)` `iri(??)` `bif:__rdf_long_from_batch_params(??,??,??)` }"; - static final String sdelete = "sparql delete from graph iri(??) {`iri(??)` `iri(??)` `bif:__rdf_long_from_batch_params(??,??,??)`}"; - static final int BATCH_SIZE = 5000; - static final String utf8 = "charset=utf-8"; - static final String charset = "UTF-8"; - - private VirtuosoConnectionPoolDataSource pds = new VirtuosoConnectionPoolDataSource(); - private VirtuosoDataSource ds; - - private boolean isDSconnection = false; - - public VirtGraph() { - this(null, "jdbc:virtuoso://localhost:1111/charset=UTF-8", null, null, - false); - } - - public VirtGraph(String graphName) { - this(graphName, "jdbc:virtuoso://localhost:1111/charset=UTF-8", null, - null, false); - } - - public VirtGraph(String graphName, String _url_hostlist, String user, - String password) { - this(graphName, _url_hostlist, user, password, false); - } - - public VirtGraph(String url_hostlist, String user, String password) { - this(null, url_hostlist, user, password, false); - } - - public VirtGraph(String _graphName, VirtuosoDataSource _ds) { - super(); - - this.url_hostlist = _ds.getServerName(); - this.graphName = _graphName; - this.user = _ds.getUser(); - this.password = _ds.getPassword(); - - if (this.graphName == null) - this.graphName = DEFAULT; - - try { - connection = _ds.getConnection(); - isDSconnection = true; - ds = _ds; - ModelCom m = new ModelCom(this); // don't drop is it needed for - // initialize internal Jena - // classes - TypeMapper tm = TypeMapper.getInstance(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - public VirtGraph(VirtuosoDataSource _ds) { - this(null, _ds); - } - - public VirtGraph(String graphName, String _url_hostlist, String user, - String password, boolean _roundrobin) { - super(); - - this.url_hostlist = _url_hostlist.trim(); - this.roundrobin = _roundrobin; - this.graphName = graphName; - this.user = user; - this.password = password; - - if (this.graphName == null) - this.graphName = DEFAULT; - - try { - if (url_hostlist.startsWith("jdbc:virtuoso://")) { - - String url = url_hostlist; - if (url.toLowerCase().indexOf(utf8) == -1) { - if (url.charAt(url.length() - 1) != '/') - url = url + "/charset=UTF-8"; - else - url = url + "charset=UTF-8"; - } - if (roundrobin - && url.toLowerCase().indexOf("roundrobin=") == -1) { - if (url.charAt(url.length() - 1) != '/') - url = url + "/roundrobin=1"; - else - url = url + "roundrobin=1"; - } - Class.forName("virtuoso.jdbc4.Driver"); - connection = DriverManager.getConnection(url, user, password); - } else { - pds.setServerName(url_hostlist); - pds.setUser(user); - pds.setPassword(password); - pds.setCharset(charset); - pds.setRoundrobin(roundrobin); - javax.sql.PooledConnection pconn = pds.getPooledConnection(); - connection = pconn.getConnection(); - isDSconnection = true; - } - - ModelCom m = new ModelCom(this); // don't drop is it needed for - // initialize internal Jena - // classes - TypeMapper tm = TypeMapper.getInstance(); - } catch (Exception e) { - throw new JenaException(e); - } - - } - - // getters - public VirtuosoDataSource getDataSource() { - if (isDSconnection) - return (ds != null ? ds : (VirtuosoDataSource) pds); - else - return null; - } - - public String getGraphName() { - return this.graphName; - } - - public String getGraphUrl() { - return this.url_hostlist; - } - - public String getGraphUser() { - return this.user; - } - - public String getGraphPassword() { - return this.password; - } - - public Connection getConnection() { - return this.connection; - } - - public int getFetchSize() { - return this.prefetchSize; - } - - public void setFetchSize(int sz) { - this.prefetchSize = sz; - } - - public int getQueryTimeout() { - return this.queryTimeout; - } - - public void setQueryTimeout(int seconds) { - this.queryTimeout = seconds; - } - - public int getCount() { - return size(); - } - - public void remove(List triples) { - delete(triples.iterator(), null); - } - - public void remove(Triple t) { - delete(t); - } - - public boolean getReadFromAllGraphs() { - return readFromAllGraphs; - } - - public void setReadFromAllGraphs(boolean val) { - readFromAllGraphs = val; - } - - public String getRuleSet() { - return ruleSet; - } - - public void setRuleSet(String _ruleSet) { - ruleSet = _ruleSet; - } - - public boolean getSameAs() { - return useSameAs; - } - - public void setSameAs(boolean _sameAs) { - useSameAs = _sameAs; - } - - public void createRuleSet(String ruleSetName, String uriGraphRuleSet) { - checkOpen(); - - try { - java.sql.Statement st = createStatement(); - st.execute("rdfs_rule_set('" + ruleSetName + "', '" - + uriGraphRuleSet + "')"); - st.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - public void removeRuleSet(String ruleSetName, String uriGraphRuleSet) { - checkOpen(); - - try { - java.sql.Statement st = createStatement(); - st.execute("rdfs_rule_set('" + ruleSetName + "', '" - + uriGraphRuleSet + "', 1)"); - st.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - private static String escapeString(String s) { - StringBuffer buf = new StringBuffer(s.length()); - int i = 0; - char ch; - while (i < s.length()) { - ch = s.charAt(i++); - if (ch == '\'') - buf.append('\\'); - buf.append(ch); - } - return buf.toString(); - } - - protected java.sql.Statement createStatement() throws java.sql.SQLException { - checkOpen(); - java.sql.Statement st = connection.createStatement(); - if (queryTimeout > 0) - st.setQueryTimeout(queryTimeout); - st.setFetchSize(prefetchSize); - return st; - } - - protected java.sql.PreparedStatement prepareStatement(String sql) - throws java.sql.SQLException { - checkOpen(); - java.sql.PreparedStatement st = connection.prepareStatement(sql); - if (queryTimeout > 0) - st.setQueryTimeout(queryTimeout); - st.setFetchSize(prefetchSize); - return st; - } - - // GraphBase overrides - public static String Node2Str(Node n) { - if (n.isURI()) { - return "<" + n + ">"; - } else if (n.isBlank()) { - return "<_:" + n + ">"; - } else if (n.isLiteral()) { - String s; - StringBuffer sb = new StringBuffer(); - sb.append("'"); - sb.append(escapeString(n.getLiteralValue().toString())); - sb.append("'"); - - s = n.getLiteralLanguage(); - if (s != null && s.length() > 0) { - sb.append("@"); - sb.append(s); - } - s = n.getLiteralDatatypeURI(); - if (s != null && s.length() > 0) { - sb.append("^^<"); - sb.append(s); - sb.append(">"); - } - return sb.toString(); - } else { - return "<" + n + ">"; - } - } - - void bindSubject(PreparedStatement ps, int col, Node n) throws SQLException { - if (n == null) - return; - if (n.isURI()) - ps.setString(col, n.toString()); - else if (n.isBlank()) - ps.setString(col, "_:" + n.toString()); - else - throw new SQLException( - "Only URI or Blank nodes can be used as subject"); - } - - void bindPredicate(PreparedStatement ps, int col, Node n) - throws SQLException { - if (n == null) - return; - if (n.isURI()) - ps.setString(col, n.toString()); - else - throw new SQLException("Only URI nodes can be used as predicate"); - } - - void bindObject(PreparedStatement ps, int col, Node n) throws SQLException { - if (n == null) - return; - if (n.isURI()) { - ps.setInt(col, 1); - ps.setString(col + 1, n.toString()); - ps.setNull(col + 2, java.sql.Types.VARCHAR); - } else if (n.isBlank()) { - ps.setInt(col, 1); - ps.setString(col + 1, "_:" + n.toString()); - ps.setNull(col + 2, java.sql.Types.VARCHAR); - } else if (n.isLiteral()) { - String llang = n.getLiteralLanguage(); - String ltype = n.getLiteralDatatypeURI(); - if (llang != null && llang.length() > 0) { - ps.setInt(col, 5); - ps.setString(col + 1, n.getLiteralValue().toString()); - ps.setString(col + 2, n.getLiteralLanguage()); - } else if (ltype != null && ltype.length() > 0) { - ps.setInt(col, 4); - ps.setString(col + 1, n.getLiteralValue().toString()); - ps.setString(col + 2, n.getLiteralDatatypeURI()); - } else { - ps.setInt(col, 3); - ps.setString(col + 1, n.getLiteralValue().toString()); - ps.setNull(col + 2, java.sql.Types.VARCHAR); - } - } else { - ps.setInt(col, 3); - ps.setString(col + 1, n.toString()); - ps.setNull(col + 2, java.sql.Types.VARCHAR); - } - } - - // --java5 or newer @Override - public void performAdd(Triple t) { - java.sql.PreparedStatement ps; - - try { - ps = prepareStatement(sinsert); - ps.setString(1, this.graphName); - bindSubject(ps, 2, t.getSubject()); - bindPredicate(ps, 3, t.getPredicate()); - bindObject(ps, 4, t.getObject()); - - ps.execute(); - ps.close(); - } catch (Exception e) { - throw new AddDeniedException(e.toString()); - } - } - - public void performDelete(Triple t) { - java.sql.PreparedStatement ps; - - try { - ps = prepareStatement(sdelete); - ps.setString(1, this.graphName); - bindSubject(ps, 2, t.getSubject()); - bindPredicate(ps, 3, t.getPredicate()); - bindObject(ps, 4, t.getObject()); - - ps.execute(); - ps.close(); - } catch (Exception e) { - throw new DeleteDeniedException(e.toString()); - } - } - - /** - * more efficient - */ - // --java5 or newer @Override - protected int graphBaseSize() { - StringBuffer sb = new StringBuffer( - "select count(*) from (sparql define input:storage \"\" "); - - if (ruleSet != null) - sb.append(" define input:inference '" + ruleSet + "'\n "); - - if (useSameAs) - sb.append(" define input:same-as \"yes\"\n "); - - if (readFromAllGraphs) - sb.append(" select * where {?s ?p ?o })f"); - else - sb.append(" select * where { graph `iri(??)` { ?s ?p ?o }})f"); - - ResultSet rs = null; - int ret = 0; - - checkOpen(); - - try { - java.sql.PreparedStatement ps = prepareStatement(sb.toString()); - - if (!readFromAllGraphs) - ps.setString(1, graphName); - - rs = ps.executeQuery(); - if (rs.next()) - ret = rs.getInt(1); - rs.close(); - ps.close(); - } catch (Exception e) { - throw new JenaException(e); - } - return ret; - } - - /** - * maybe more efficient than default impl - * - */ - // --java5 or newer @Override - protected boolean graphBaseContains(Triple t) { - ResultSet rs = null; - String S, P, O; - StringBuffer sb = new StringBuffer("sparql define input:storage \"\" "); - String exec_text; - - checkOpen(); - - S = " ?s "; - P = " ?p "; - O = " ?o "; - - if (!Node.ANY.equals(t.getSubject())) - S = Node2Str(t.getSubject()); - - if (!Node.ANY.equals(t.getPredicate())) - P = Node2Str(t.getPredicate()); - - if (!Node.ANY.equals(t.getObject())) - O = Node2Str(t.getObject()); - - if (ruleSet != null) - sb.append(" define input:inference '" + ruleSet + "'\n "); - - if (useSameAs) - sb.append(" define input:same-as \"yes\"\n "); - - if (readFromAllGraphs) - sb.append(" select * where { " + S + " " + P + " " + O - + " } limit 1"); - else - sb.append(" select * where { graph <" + graphName + "> { " + S - + " " + P + " " + O + " }} limit 1"); - - try { - java.sql.Statement stmt = createStatement(); - rs = stmt.executeQuery(sb.toString()); - boolean ret = rs.next(); - rs.close(); - stmt.close(); - return ret; - } catch (Exception e) { - throw new JenaException(e); - } - } - - // --java5 or newer @Override - public ExtendedIterator graphBaseFind(TripleMatch tm) { - String S, P, O; - StringBuffer sb = new StringBuffer("sparql "); - - checkOpen(); - - S = " ?s "; - P = " ?p "; - O = " ?o "; - - if (tm.getMatchSubject() != null) - S = Node2Str(tm.getMatchSubject()); - - if (tm.getMatchPredicate() != null) - P = Node2Str(tm.getMatchPredicate()); - - if (tm.getMatchObject() != null) - O = Node2Str(tm.getMatchObject()); - - if (ruleSet != null) - sb.append(" define input:inference '" + ruleSet + "'\n "); - - if (useSameAs) - sb.append(" define input:same-as \"yes\"\n "); - - if (readFromAllGraphs) - sb.append(" select * where { " + S + " " + P + " " + O + " }"); - else - sb.append(" select * from <" + graphName + "> where { " + S + " " - + P + " " + O + " }"); - - try { - java.sql.PreparedStatement stmt; - stmt = prepareStatement(sb.toString()); - return new VirtResSetIter(this, stmt.executeQuery(), tm, stmt); - } catch (Exception e) { - throw new JenaException(e); - } - } - - // --java5 or newer @Override - public void close() { - try { - super.close(); // will set closed = true - connection.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - // Extra functions - - public void clear() { - clearGraph(this.graphName); - getEventManager().notifyEvent(this, GraphEvents.removeAll); - } - - public void read(String url, String type) { - String exec_text; - - exec_text = "sparql load \"" + url + "\" into graph <" + graphName - + ">"; - - checkOpen(); - try { - java.sql.Statement stmt = createStatement(); - stmt.execute(exec_text); - stmt.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - // --java5 or newer @SuppressWarnings("unchecked") - void add(Iterator it, List list) { - try { - PreparedStatement ps = prepareStatement(sinsert); - int count = 0; - - while (it.hasNext()) { - Triple t = (Triple) it.next(); - - if (list != null) - list.add(t); - - ps.setString(1, this.graphName); - bindSubject(ps, 2, t.getSubject()); - bindPredicate(ps, 3, t.getPredicate()); - bindObject(ps, 4, t.getObject()); - ps.addBatch(); - count++; - - if (count > BATCH_SIZE) { - ps.executeBatch(); - ps.clearBatch(); - count = 0; - } - } - - if (count > 0) { - ps.executeBatch(); - ps.clearBatch(); - } - ps.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - void delete(Iterator it, List list) { - try { - while (it.hasNext()) { - Triple triple = (Triple) it.next(); - - if (list != null) - list.add(triple); - - performDelete(triple); - } - } catch (Exception e) { - throw new JenaException(e); - } - } - - void delete_match(TripleMatch tm) { - String S, P, O; - Node nS, nP, nO; - - checkOpen(); - - S = "?s"; - P = "?p"; - O = "?o"; - - nS = tm.getMatchSubject(); - nP = tm.getMatchPredicate(); - nO = tm.getMatchObject(); - - try { - if (nS == null && nP == null && nO == null) { - - clearGraph(this.graphName); - - } else if (nS != null && nP != null && nO != null) { - java.sql.PreparedStatement ps; - - ps = prepareStatement(sdelete); - ps.setString(1, this.graphName); - bindSubject(ps, 2, nS); - bindPredicate(ps, 3, nP); - bindObject(ps, 4, nO); - - ps.execute(); - ps.close(); - - } else { - - if (nS != null) - S = Node2Str(nS); - - if (nP != null) - P = Node2Str(nP); - - if (nO != null) - O = Node2Str(nO); - - String query = "sparql delete from graph <" + this.graphName - + "> { " + S + " " + P + " " + O + " } from <" - + this.graphName + "> where { " + S + " " + P + " " + O - + " }"; - - java.sql.Statement stmt = createStatement(); - stmt.execute(query); - stmt.close(); - } - } catch (Exception e) { - throw new DeleteDeniedException(e.toString()); - } - } - - void clearGraph(String name) { - String query = "sparql clear graph iri(??)"; - - checkOpen(); - - try { - java.sql.PreparedStatement ps = prepareStatement(query); - ps.setString(1, name); - ps.execute(); - ps.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - public ExtendedIterator reifierTriples(TripleMatch m) { - return NiceIterator.emptyIterator(); - } - - public int reifierSize() { - return 0; - } - - // --java5 or newer @Override - public TransactionHandler getTransactionHandler() { - return new VirtTransactionHandler(this); - } - // --java5 or newer @Override - public BulkUpdateHandler getBulkUpdateHandler() { + static public final String DEFAULT = "virt:DEFAULT"; + static final String sinsert = "sparql insert into graph iri(??) { `iri(??)` `iri(??)` `bif:__rdf_long_from_batch_params(??,??,??)` }"; + static final String sdelete = "sparql delete from graph iri(??) {`iri(??)` `iri(??)` `bif:__rdf_long_from_batch_params(??,??,??)`}"; + static final int BATCH_SIZE = 5000; + static final String utf8 = "charset=utf-8"; + static final String charset = "UTF-8"; + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtGraph.class); + + static { + VirtuosoQueryEngine.register(); + } + + protected String graphName; + protected boolean readFromAllGraphs = false; + protected String url_hostlist; + protected String user; + protected String password; + protected boolean roundrobin = false; + protected int prefetchSize = 200; + protected Connection connection = null; + protected String ruleSet = null; + protected boolean useSameAs = false; + protected int queryTimeout = 0; + protected VirtPrefixMapping m_prefixMapping = null; + private VirtuosoConnectionPoolDataSource pds = new VirtuosoConnectionPoolDataSource(); + private VirtuosoDataSource ds; + private boolean isDSconnection = false; + + public VirtGraph() { + this(null, "jdbc:virtuoso://localhost:1111/charset=UTF-8", null, null, + false); + } + + public VirtGraph(String graphName) { + this(graphName, "jdbc:virtuoso://localhost:1111/charset=UTF-8", null, + null, false); + } + + public VirtGraph(String graphName, String _url_hostlist, String user, + String password) { + this(graphName, _url_hostlist, user, password, false); + } + + public VirtGraph(String url_hostlist, String user, String password) { + this(null, url_hostlist, user, password, false); + } + + public VirtGraph(String _graphName, VirtuosoDataSource _ds) { + super(); + + this.url_hostlist = _ds.getServerName(); + this.graphName = _graphName; + this.user = _ds.getUser(); + this.password = _ds.getPassword(); + + if (this.graphName == null) + this.graphName = DEFAULT; + + try { + connection = _ds.getConnection(); + isDSconnection = true; + ds = _ds; + // don't drop is it needed for initialize internal Jena classes + ModelCom m = new ModelCom(this); + + TypeMapper tm = TypeMapper.getInstance(); + } catch (Exception e) { + throw new JenaException(e); + } + } + + public VirtGraph(VirtuosoDataSource _ds) { + this(null, _ds); + } + + public VirtGraph(String graphName, String _url_hostlist, String user, + String password, boolean _roundrobin) { + super(); + + this.url_hostlist = _url_hostlist.trim(); + this.roundrobin = _roundrobin; + this.graphName = graphName; + this.user = user; + this.password = password; + + if (this.graphName == null) + this.graphName = DEFAULT; + + try { + if (url_hostlist.startsWith("jdbc:virtuoso://")) { + + String url = url_hostlist; + if (!url.toLowerCase().contains(utf8)) { + if (url.charAt(url.length() - 1) != '/') + url = url + "/charset=UTF-8"; + else + url = url + "charset=UTF-8"; + } + if (roundrobin + && !url.toLowerCase().contains("roundrobin=")) { + if (url.charAt(url.length() - 1) != '/') + url = url + "/roundrobin=1"; + else + url = url + "roundrobin=1"; + } + Class.forName("virtuoso.jdbc4.Driver"); + connection = DriverManager.getConnection(url, user, password); + } else { + pds.setServerName(url_hostlist); + pds.setUser(user); + pds.setPassword(password); + pds.setCharset(charset); + pds.setRoundrobin(roundrobin); + javax.sql.PooledConnection pconn = pds.getPooledConnection(); + connection = pconn.getConnection(); + isDSconnection = true; + } + + ModelCom m = new ModelCom(this); // don't drop is it needed for + // initialize internal Jena + // classes + TypeMapper tm = TypeMapper.getInstance(); + } catch (ClassNotFoundException | SQLException e) { + throw new JenaException(e); + } + + } + + + + + + // getters + public VirtuosoDataSource getDataSource() { + if (isDSconnection) + return (ds != null ? ds : pds); + else + return null; + } + + public String getGraphName() { + return this.graphName; + } + + public String getGraphUrl() { + return this.url_hostlist; + } + + public String getGraphUser() { + return this.user; + } + + public String getGraphPassword() { + return this.password; + } + + public Connection getConnection() { + return this.connection; + } + + public int getFetchSize() { + return this.prefetchSize; + } + + public void setFetchSize(int sz) { + this.prefetchSize = sz; + } + + public int getQueryTimeout() { + return this.queryTimeout; + } + + public void setQueryTimeout(int seconds) { + this.queryTimeout = seconds; + } + + public int getCount() { + return size(); + } + + public void remove(List triples) { + delete(triples.iterator(), null); + } + + public void remove(Triple t) { + delete(t); + } + + public boolean getReadFromAllGraphs() { + return readFromAllGraphs; + } + + public void setReadFromAllGraphs(boolean val) { + readFromAllGraphs = val; + } + + public String getRuleSet() { + return ruleSet; + } + + public void setRuleSet(String _ruleSet) { + ruleSet = _ruleSet; + } + + public boolean getSameAs() { + return useSameAs; + } + + public void setSameAs(boolean _sameAs) { + useSameAs = _sameAs; + } + + public void createRuleSet(String ruleSetName, String uriGraphRuleSet) { + checkOpen(); + + try { + try (java.sql.Statement st = createStatement()) { + st.execute("rdfs_rule_set('" + ruleSetName + "', '" + + uriGraphRuleSet + "')"); + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + public void removeRuleSet(String ruleSetName, String uriGraphRuleSet) { + checkOpen(); + + try { + try (java.sql.Statement st = createStatement()) { + st.execute("rdfs_rule_set('" + ruleSetName + "', '" + + uriGraphRuleSet + "', 1)"); + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + protected java.sql.Statement createStatement() throws java.sql.SQLException { + checkOpen(); + java.sql.Statement st = connection.createStatement(); + if (queryTimeout > 0) + st.setQueryTimeout(queryTimeout); + st.setFetchSize(prefetchSize); + return st; + } + + protected java.sql.PreparedStatement createPreparedStatement(String sql) + throws java.sql.SQLException { + checkOpen(); + java.sql.PreparedStatement st = connection.prepareStatement(sql); + if (queryTimeout > 0) + st.setQueryTimeout(queryTimeout); + st.setFetchSize(prefetchSize); + return st; + } + + protected void executePrepareStatementOnGraph( + java.sql.PreparedStatement ps, String graphName, Triple t) throws SQLException { + ps.setString(1, graphName); + bindSubject(ps, 2, t.getSubject()); + bindPredicate(ps, 3, t.getPredicate()); + bindObject(ps, 4, t.getObject()); + ps.execute(); + ps.close(); + } + + void bindSubject(PreparedStatement ps, int col, Node n) throws SQLException { + if (n == null) return; + if (n.isURI()) ps.setString(col, n.toString()); + else if (n.isBlank()) ps.setString(col, "_:" + n.toString()); + else + throw new SQLException( + "Only URI or Blank nodes can be used as subject"); + } + + void bindPredicate(PreparedStatement ps, int col, Node n) + throws SQLException { + if (n == null) return; + if (n.isURI()) ps.setString(col, n.toString()); + else + throw new SQLException("Only URI nodes can be used as predicate"); + } + + void bindObject(PreparedStatement ps, int col, Node n) throws SQLException { + if (n == null) + return; + if (n.isURI()) { + ps.setInt(col, 1); + ps.setString(col + 1, n.toString()); + ps.setNull(col + 2, java.sql.Types.VARCHAR); + } else if (n.isBlank()) { + ps.setInt(col, 1); + ps.setString(col + 1, "_:" + n.toString()); + ps.setNull(col + 2, java.sql.Types.VARCHAR); + } else if (n.isLiteral()) { + String llang = n.getLiteralLanguage(); + String ltype = n.getLiteralDatatypeURI(); + if (llang != null && llang.length() > 0) { + ps.setInt(col, 5); + ps.setString(col + 1, n.getLiteralValue().toString()); + ps.setString(col + 2, n.getLiteralLanguage()); + } else if (ltype != null && ltype.length() > 0) { + ps.setInt(col, 4); + ps.setString(col + 1, n.getLiteralValue().toString()); + ps.setString(col + 2, n.getLiteralDatatypeURI()); + } else { + ps.setInt(col, 3); + ps.setString(col + 1, n.getLiteralValue().toString()); + ps.setNull(col + 2, java.sql.Types.VARCHAR); + } + } else { + ps.setInt(col, 3); + ps.setString(col + 1, n.toString()); + ps.setNull(col + 2, java.sql.Types.VARCHAR); + } + } + + // --java5 or newer @Override + @Override + public void performAdd(Triple t) { + java.sql.PreparedStatement ps; + try { + ps = createPreparedStatement(sinsert); + executePrepareStatementOnGraph(ps, this.graphName, t); + + } catch (Exception e) { + throw new AddDeniedException(e.toString()); + } + } + + @Override + public void performDelete(Triple t) { + java.sql.PreparedStatement ps; + + try { + ps = createPreparedStatement(sdelete); + executePrepareStatementOnGraph(ps, this.graphName, t); + } catch (Exception e) { + throw new DeleteDeniedException(e.toString()); + } + } + + /** + * more efficient + * + * @return {@link Integer} + */ + // --java5 or newer @Override + @Override + protected int graphBaseSize() { + StringBuilder sb = new StringBuilder( + "select count(*) from (sparql define input:storage \"\" "); + + if (ruleSet != null) + sb.append(" define input:inference '").append(ruleSet).append("'\n "); + + if (useSameAs) + sb.append(" define input:same-as \"yes\"\n "); + + if (readFromAllGraphs) + sb.append(" select * where {?s ?p ?o })f"); + else + sb.append(" select * where { graph `iri(??)` { ?s ?p ?o }})f"); + + ResultSet rs; + int ret = 0; + + checkOpen(); + + try { + try (java.sql.PreparedStatement ps = createPreparedStatement(sb.toString())) { + if (!readFromAllGraphs) + ps.setString(1, graphName); + + rs = ps.executeQuery(); + if (rs.next()) + ret = rs.getInt(1); + rs.close(); + } + } catch (Exception e) { + throw new JenaException(e); + } + return ret; + } + + /** + * maybe more efficient than default impl + * + * @param t {@link Triple} + * @return {@link Boolean} + */ + // --java5 or newer @Override + @Override + protected boolean graphBaseContains(Triple t) { + ResultSet rs; + String S, P, O; + StringBuilder sb = new StringBuilder("sparql define input:storage \"\" "); + + checkOpen(); + + S = " ?s "; + P = " ?p "; + O = " ?o "; + + if (!Node.ANY.equals(t.getSubject())) + S = VirtUtilities.toString(t.getSubject()); + + if (!Node.ANY.equals(t.getPredicate())) + P = VirtUtilities.toString(t.getPredicate()); + + if (!Node.ANY.equals(t.getObject())) + O = VirtUtilities.toString(t.getObject()); + + if (ruleSet != null) + sb.append(" define input:inference '").append(ruleSet).append("'\n "); + + if (useSameAs) + sb.append(" define input:same-as \"yes\"\n "); + + if (readFromAllGraphs) + sb.append(" select * where { ") + .append(S).append(" ") + .append(P).append(" ") + .append(O) + .append(" } limit 1"); + else + sb.append(" select * where { graph <").append(graphName).append("> { ") + .append(S).append(" ") + .append(P).append(" ") + .append(O) + .append(" }} limit 1"); + + try { + boolean ret; + try (java.sql.Statement stmt = createStatement()) { + rs = stmt.executeQuery(sb.toString()); + ret = rs.next(); + rs.close(); + } + return ret; + } catch (Exception e) { + throw new JenaException(e); + } + } + + // --java5 or newer @Override + @Override + public ExtendedIterator graphBaseFind(Triple tm) { + String S, P, O; + StringBuilder sb = new StringBuilder("sparql "); + + checkOpen(); + + S = " ?s "; + P = " ?p "; + O = " ?o "; + + if (tm.getMatchSubject() != null) + S = VirtUtilities.toString(tm.getMatchSubject()); + + if (tm.getMatchPredicate() != null) + P = VirtUtilities.toString(tm.getMatchPredicate()); + + if (tm.getMatchObject() != null) + O = VirtUtilities.toString(tm.getMatchObject()); + + if (ruleSet != null) + sb.append(" define input:inference '").append(ruleSet).append("'\n "); + + if (useSameAs) + sb.append(" define input:same-as \"yes\"\n "); + + if (readFromAllGraphs) + sb.append(" select * where { ") + .append(S).append(" ") + .append(P).append(" ") + .append(O) + .append(" }"); + else + sb.append(" select * from <").append(graphName).append("> where { ") + .append(S).append(" ") + .append(P).append(" ") + .append(O) + .append(" }"); + + try { + java.sql.PreparedStatement stmt; + stmt = createPreparedStatement(sb.toString()); + return new VirtResSetIter(this, stmt.executeQuery(), tm, stmt); + } catch (Exception e) { + throw new JenaException(e); + } + } + + // Extra functions + + // --java5 or newer @Override + @Override + public void close() { + try { + super.close(); // will set closed = true + connection.close(); + } catch (Exception e) { + throw new JenaException(e); + } + } + + @Override + public void clear() { + clearGraph(this.graphName); + getEventManager().notifyEvent(this, GraphEvents.removeAll); + } + + public void read(String url, String type) { + String exec_text; + + exec_text = "sparql load \"" + url + "\" into graph <" + graphName + ">"; + + checkOpen(); + try { + try (java.sql.Statement stmt = createStatement()) { + stmt.execute(exec_text); + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + // --java5 or newer @SuppressWarnings("unchecked") + void add(Iterator it, List list) { + try { + try (PreparedStatement ps = createPreparedStatement(sinsert)) { + int count = 0; + + while (it.hasNext()) { + Triple t = it.next(); + + if (list != null) + list.add(t); + + ps.setString(1, this.graphName); + bindSubject(ps, 2, t.getSubject()); + bindPredicate(ps, 3, t.getPredicate()); + bindObject(ps, 4, t.getObject()); + ps.addBatch(); + count++; + + if (count > BATCH_SIZE) { + ps.executeBatch(); + ps.clearBatch(); + count = 0; + } + } + + if (count > 0) { + ps.executeBatch(); + ps.clearBatch(); + } + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + void delete(Iterator it, List list) { + try { + while (it.hasNext()) { + Triple triple = it.next(); + + if (list != null) + list.add(triple); + + performDelete(triple); + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + void delete_match(Triple tm) { + String S, P, O; + Node nS, nP, nO; + + checkOpen(); + + S = "?s"; + P = "?p"; + O = "?o"; + + nS = tm.getMatchSubject(); + nP = tm.getMatchPredicate(); + nO = tm.getMatchObject(); + + try { + if (nS == null && nP == null && nO == null) { + + clearGraph(this.graphName); + + } else if (nS != null && nP != null && nO != null) { + java.sql.PreparedStatement ps; + + ps = createPreparedStatement(sdelete); + ps.setString(1, this.graphName); + bindSubject(ps, 2, nS); + bindPredicate(ps, 3, nP); + bindObject(ps, 4, nO); + + ps.execute(); + ps.close(); + + } else { + + if (nS != null) + S = VirtUtilities.toString(nS); + + if (nP != null) + P = VirtUtilities.toString(nP); + + if (nO != null) + O = VirtUtilities.toString(nO); + + String query = "sparql delete from graph <" + this.graphName + + "> { " + S + " " + P + " " + O + " } from <" + + this.graphName + "> where { " + S + " " + P + " " + O + + " }"; + + try (java.sql.Statement stmt = createStatement()) { + stmt.execute(query); + } + } + } catch (Exception e) { + throw new DeleteDeniedException(e.toString()); + } + } + + void clearGraph(String name) { + String query = "sparql clear graph iri(??)"; + checkOpen(); + try { + try (java.sql.PreparedStatement ps = createPreparedStatement(query)) { + ps.setString(1, name); + ps.execute(); + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + public ExtendedIterator reifierTriples(Triple m) { + return NiceIterator.emptyIterator(); + } + + public int reifierSize() { + return 0; + } + + // --java5 or newer @Override + /*public BulkUpdateHandler getBulkUpdateHandler() { if (bulkHandler == null) bulkHandler = new VirtBulkUpdateHandler(this); return bulkHandler; - } - - protected VirtPrefixMapping m_prefixMapping = null; - - public PrefixMapping getPrefixMapping() { - if (m_prefixMapping == null) - m_prefixMapping = new VirtPrefixMapping(this); - return m_prefixMapping; - } - - public static Node Object2Node(Object o) { - if (o == null) - return null; - - if (o instanceof ExtendedString) { - ExtendedString vs = (ExtendedString) o; - - if (vs.getIriType() == ExtendedString.IRI - && (vs.getStrType() & 0x01) == 0x01) { - if (vs.toString().indexOf("_:") == 0) - return Node.createAnon(AnonId.create(vs.toString() - .substring(2))); // _: - else - return Node.createURI(vs.toString()); - - } else if (vs.getIriType() == ExtendedString.BNODE) { - return Node.createAnon(AnonId - .create(vs.toString().substring(9))); // nodeID:// - - } else { - return Node.createLiteral(vs.toString()); - } - - } else if (o instanceof RdfBox) { - - RdfBox rb = (RdfBox) o; - String rb_type = rb.getType(); - RDFDatatype dt = null; - - if (rb_type != null) - dt = TypeMapper.getInstance().getSafeTypeByName(rb_type); - return Node.createLiteral(rb.toString(), rb.getLang(), dt); - - } else if (o instanceof java.lang.Integer) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#integer"); - return Node.createLiteral(o.toString(), null, dt); - - } else if (o instanceof java.lang.Short) { - - RDFDatatype dt = null; - // dt = - // TypeMapper.getInstance().getSafeTypeByName("http://www.w3.org/2001/XMLSchema#short"); - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#integer"); - return Node.createLiteral(o.toString(), null, dt); - - } else if (o instanceof java.lang.Float) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#float"); - return Node.createLiteral(o.toString(), null, dt); - - } else if (o instanceof java.lang.Double) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#double"); - return Node.createLiteral(o.toString(), null, dt); - - } else if (o instanceof java.math.BigDecimal) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#decimal"); - return Node.createLiteral(o.toString(), null, dt); - - } else if (o instanceof java.sql.Blob) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#hexBinary"); - return Node.createLiteral(o.toString(), null, dt); - - } else if (o instanceof java.sql.Date) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#date"); - return Node.createLiteral(o.toString(), null, dt); - - } else if (o instanceof java.sql.Timestamp) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#dateTime"); - return Node.createLiteral(Timestamp2String((java.sql.Timestamp) o), - null, dt); - - } else if (o instanceof java.sql.Time) { - - RDFDatatype dt = null; - dt = TypeMapper.getInstance().getSafeTypeByName( - "http://www.w3.org/2001/XMLSchema#time"); - return Node.createLiteral(o.toString(), null, dt); - - } else { - - return Node.createLiteral(o.toString()); - } - } - - private static String Timestamp2String(java.sql.Timestamp v) { - GregorianCalendar cal = new GregorianCalendar(); - cal.setTime(v); - - int year = cal.get(Calendar.YEAR); - int month = cal.get(Calendar.MONTH) + 1; - int day = cal.get(Calendar.DAY_OF_MONTH); - int hour = cal.get(Calendar.HOUR_OF_DAY); - int minute = cal.get(Calendar.MINUTE); - int second = cal.get(Calendar.SECOND); - int nanos = v.getNanos(); - - String yearS; - String monthS; - String dayS; - String hourS; - String minuteS; - String secondS; - String nanosS; - String zeros = "000000000"; - String yearZeros = "0000"; - StringBuffer timestampBuf; - - if (year < 1000) { - yearS = "" + year; - yearS = yearZeros.substring(0, (4 - yearS.length())) + yearS; - } else { - yearS = "" + year; - } - - if (month < 10) - monthS = "0" + month; - else - monthS = Integer.toString(month); - - if (day < 10) - dayS = "0" + day; - else - dayS = Integer.toString(day); - - if (hour < 10) - hourS = "0" + hour; - else - hourS = Integer.toString(hour); - - if (minute < 10) - minuteS = "0" + minute; - else - minuteS = Integer.toString(minute); - - if (second < 10) - secondS = "0" + second; - else - secondS = Integer.toString(second); - - if (nanos == 0) { - nanosS = "0"; - } else { - nanosS = Integer.toString(nanos); - - // Add leading 0 - nanosS = zeros.substring(0, (9 - nanosS.length())) + nanosS; - - // Truncate trailing 0 - char[] nanosChar = new char[nanosS.length()]; - nanosS.getChars(0, nanosS.length(), nanosChar, 0); - int truncIndex = 8; - while (nanosChar[truncIndex] == '0') { - truncIndex--; - } - nanosS = new String(nanosChar, 0, truncIndex + 1); - } - - timestampBuf = new StringBuffer(); - timestampBuf.append(yearS); - timestampBuf.append("-"); - timestampBuf.append(monthS); - timestampBuf.append("-"); - timestampBuf.append(dayS); - timestampBuf.append("T"); - timestampBuf.append(hourS); - timestampBuf.append(":"); - timestampBuf.append(minuteS); - timestampBuf.append(":"); - timestampBuf.append(secondS); - timestampBuf.append("."); - timestampBuf.append(nanosS); - - return (timestampBuf.toString()); - } + }*/ + + // --java5 or newer @Override + @Override + public TransactionHandler getTransactionHandler() { + return new VirtTransactionHandler(this); + } + + @Override + public PrefixMapping getPrefixMapping() { + if (m_prefixMapping == null) + m_prefixMapping = new VirtPrefixMapping(this); + return m_prefixMapping; + } + + // --java5 or newer @Override + public void add(Triple[] triples) { + addIterator(Arrays.asList(triples).iterator(), false); + gem.notifyAddArray(this, triples); + } + + // --java5 or newer @Override + protected void add(List triples, boolean notify) { + addIterator(triples.iterator(), false); + if (notify) + gem.notifyAddList(this, triples); + } + + // --java5 or newer @Override + public void addIterator(Iterator it, boolean notify) { + VirtGraph _graph = this; + List list; + if (notify) list = new ArrayList<>(); + else list = null; + + _graph = prepareGraphConnection(_graph, it, list); + + if (notify) + gem.notifyAddIterator(_graph, list); + } + + public VirtGraph prepareGraphConnection(VirtGraph _graph, Iterator it, List list) { + try { + boolean autoCommit = _graph.getConnection().getAutoCommit(); + if (autoCommit) + _graph.getConnection().setAutoCommit(false); + _graph.add(it, list); + if (autoCommit) { + _graph.getConnection().commit(); + _graph.getConnection().setAutoCommit(true); + } + } catch (Exception e) { + throw new JenaException("Couldn't create transaction:" + e); + } + return _graph; + } + + public void delete(Triple[] triples) { + deleteIterator(Arrays.asList(triples).iterator(), false); + gem.notifyDeleteArray(this, triples); + } + + protected void delete(List triples, boolean notify) { + deleteIterator(triples.iterator(), false); + if (notify) + gem.notifyDeleteList(this, triples); + } + + public void deleteIterator(Iterator it, boolean notify) { + VirtGraph _graph = this; + List list; + if (notify) list = new ArrayList<>(); + else list = null; + + prepareGraphConnection(_graph, it, list); + + if (notify) + gem.notifyDeleteIterator(_graph, list); + } + + public void removeAll() { + VirtGraph _graph = this; + _graph.clearGraph(_graph.getGraphName()); + } + + @Override + public void remove(Node s, Node p, Node o) { + VirtGraph _graph = this; + _graph.delete_match(Triple.createMatch(s, p, o)); + gem.notifyEvent(this, GraphEvents.remove(s, p, o)); + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtInfGraph.java b/src/main/java/virtuoso/jena/driver/VirtInfGraph.java index 2258e20..474631d 100644 --- a/src/main/java/virtuoso/jena/driver/VirtInfGraph.java +++ b/src/main/java/virtuoso/jena/driver/VirtInfGraph.java @@ -23,219 +23,237 @@ package virtuoso.jena.driver; -//import java.sql.*; -import java.util.Iterator; +import org.apache.jena.graph.Graph; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.Triple; +import org.apache.jena.graph.compose.MultiUnion; +import org.apache.jena.reasoner.*; +import org.apache.jena.util.iterator.ExtendedIterator; -import com.hp.hpl.jena.graph.Graph; -import com.hp.hpl.jena.graph.Node; -import com.hp.hpl.jena.graph.Triple; -import com.hp.hpl.jena.graph.compose.MultiUnion; -import com.hp.hpl.jena.reasoner.Derivation; -import com.hp.hpl.jena.reasoner.InfGraph; -import com.hp.hpl.jena.reasoner.Reasoner; -import com.hp.hpl.jena.reasoner.ReasonerException; -import com.hp.hpl.jena.reasoner.StandardValidityReport; -import com.hp.hpl.jena.reasoner.ValidityReport; -import com.hp.hpl.jena.util.iterator.ExtendedIterator; +import java.util.Iterator; public class VirtInfGraph extends VirtGraph implements InfGraph { - protected boolean recordDerivations; - - public VirtInfGraph(String _ruleSet, boolean useSameAs, String graphName) { - super(graphName); - setRuleSet(_ruleSet); - setSameAs(useSameAs); - } - - public VirtInfGraph(String _ruleSet, boolean useSameAs, String graphName, - String url_hostlist, String user, String password) { - super(graphName, url_hostlist, user, password); - setRuleSet(_ruleSet); - setSameAs(useSameAs); - } - - public VirtInfGraph(String _ruleSet, boolean useSameAs, String graphName, - String url_hostlist, String user, String password, - boolean roundrobin) { - super(graphName, url_hostlist, user, password, roundrobin); - setRuleSet(_ruleSet); - setSameAs(useSameAs); - } - - /** - * Return the raw RDF data Graph being processed (i.e. the argument to the - * Reasonder.bind call that created this InfGraph). - */ - public Graph getRawGraph() { - VirtGraph g = new VirtGraph(getGraphName(), getGraphUrl(), - getGraphUser(), getGraphPassword(), roundrobin); - return g; - } - - /** - * Return the Reasoner which is being used to answer queries to this graph. - */ - public Reasoner getReasoner() { - return null; // ??TODO - } - - /** - * Replace the underlying data graph for this inference graph and start any - * inferences over again. This is primarily using in setting up ontology - * imports processing to allow an imports multiunion graph to be inserted - * between the inference graph and the raw data, before processing. - * - * @param data - * the new raw data graph - */ - public void rebind(Graph data) { - } - - /** - * Cause the inference graph to reconsult the underlying graph to take into - * account changes. Normally changes are made through the InfGraph's add and - * remove calls are will be handled appropriately. However, in some cases - * changes are made "behind the InfGraph's back" and this forces a full - * reconsult of the changed data. - */ - public void rebind() { - } - - /** - * Perform any initial processing and caching. This call is optional. Most - * engines either have negligable set up work or will perform an implicit - * "prepare" if necessary. The call is provided for those occasions where - * substantial preparation work is possible (e.g. running a forward chaining - * rule system) and where an application might wish greater control over - * when this prepration is done. - */ - public void prepare() { - } - - /** - * Reset any internal caches. Some systems, such as the tabled backchainer, - * retain information after each query. A reset will wipe this information - * preventing unbounded memory use at the expense of more expensive future - * queries. A reset does not cause the raw data to be reconsulted and so is - * less expensive than a rebind. - */ - public void reset() { - } - - /** - * Test a global boolean property of the graph. This might included - * properties like consistency, OWLSyntacticValidity etc. It remains to be - * seen what level of generality is needed here. We could replace this by a - * small number of specific tests for common concepts. - * - * @param property - * the URI of the property to be tested - * @return a Node giving the value of the global property, this may be a - * boolean literal, some other literal value (e.g. a size). - */ - public Node getGlobalProperty(Node property) { - throw new ReasonerException("Global property not implemented: " - + property); - } - - /** - * A convenience version of getGlobalProperty which can only return a - * boolean result. - */ - public boolean testGlobalProperty(Node property) { - Node resultNode = getGlobalProperty(property); - if (resultNode.isLiteral()) { - Object result = resultNode.getLiteralValue(); - if (result instanceof Boolean) { - return ((Boolean) result).booleanValue(); - } - } - throw new ReasonerException( - "Global property test returned non-boolean value" - + "\nTest was: " + property + "\nResult was: " - + resultNode); - } - - /** - * Test the consistency of the bound data. This normally tests the validity - * of the bound instance data against the bound schema data. - * - * @return a ValidityReport structure - */ - public ValidityReport validate() { - checkOpen(); - return new StandardValidityReport(); - } - - /** - * An extension of the Graph.find interface which allows the caller to - * encode complex expressions in RDF and then refer to those expressions - * within the query triple. For example, one might encode a class expression - * and then ask if there are any instances of this class expression in the - * InfGraph. - * - * @param subject - * the subject Node of the query triple, may be a Node in the - * graph or a node in the parameter micro-graph or null - * @param property - * the property to be retrieved or null - * @param object - * the object Node of the query triple, may be a Node in the - * graph or a node in the parameter micro-graph. - * @param param - * a small graph encoding an expression which the subject and/or - * object nodes refer. - */ - public ExtendedIterator find(Node subject, Node property, - Node object, Graph param) { - return cloneWithPremises(param).find(subject, property, object); - } - - /** - * Return a new inference graph which is a clone of the current graph - * together with an additional set of data premises. The default - * implementation loses ALL partial deductions so far. Some subclasses may - * be able to a more efficient job. - */ - public Graph cloneWithPremises(Graph premises) { - MultiUnion union = new MultiUnion(); - union.addGraph(this); - union.setBaseGraph(this); - union.addGraph(premises); - return union; - } - - /** - * Switch on/off drivation logging - */ - public void setDerivationLogging(boolean logOn) { - recordDerivations = logOn; - } - - /** - * Return the derivation of the given triple (which is the result of some - * previous find operation). Not all reasoneers will support derivations. - * - * @return an iterator over Derivation records or null if there is no - * derivation information available for this triple. - */ - public Iterator getDerivation(Triple triple) { - return null; - } - - /** - * Returns a derivations graph. The rule reasoners typically create a graph - * containing those triples added to the base graph due to rule firings. In - * some applications it can useful to be able to access those deductions - * directly, without seeing the raw data which triggered them. In - * particular, this allows the forward rules to be used as if they were - * rewrite transformation rules. - * - * @return the deductions graph, if relevant for this class of inference - * engine or null if not. - */ - public Graph getDeductionsGraph() { - return null; - } + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtInfGraph.class); + + protected boolean recordDerivations; + + public VirtInfGraph(String _ruleSet, boolean useSameAs, String graphName) { + super(graphName); + setRuleSet(_ruleSet); + setSameAs(useSameAs); + } + + public VirtInfGraph(String _ruleSet, boolean useSameAs, String graphName, + String url_hostlist, String user, String password) { + super(graphName, url_hostlist, user, password); + setRuleSet(_ruleSet); + setSameAs(useSameAs); + } + + public VirtInfGraph(String _ruleSet, boolean useSameAs, String graphName, + String url_hostlist, String user, String password, + boolean roundrobin) { + super(graphName, url_hostlist, user, password, roundrobin); + setRuleSet(_ruleSet); + setSameAs(useSameAs); + } + + /** + * Return the raw RDF data Graph being processed (i.e. the argument to the + * Reasonder.bind call that created this InfGraph). + * + * @return {@link Graph} + */ + @Override + public Graph getRawGraph() { + return new VirtGraph(getGraphName(), getGraphUrl(), + getGraphUser(), getGraphPassword(), roundrobin); + } + + /** + * Return the Reasoner which is being used to answer queries to this graph. + * + * @return {@link Reasoner} + */ + @Override + public Reasoner getReasoner() { + return null; // ??TODO + } + + /** + * Replace the underlying data graph for this inference graph and start any + * inferences over again. This is primarily using in setting up ontology + * imports processing to allow an imports multiunion graph to be inserted + * between the inference graph and the raw data, before processing. + * + * @param data the new raw data graph + */ + @Override + public void rebind(Graph data) { + } + + /** + * Cause the inference graph to reconsult the underlying graph to take into + * account changes. Normally changes are made through the InfGraph's add and + * remove calls are will be handled appropriately. However, in some cases + * changes are made "behind the InfGraph's back" and this forces a full + * reconsult of the changed data. + */ + @Override + public void rebind() { + } + + /** + * Perform any initial processing and caching. This call is optional. Most + * engines either have negligable set up work or will perform an implicit + * "prepare" if necessary. The call is provided for those occasions where + * substantial preparation work is possible (e.g. running a forward chaining + * rule system) and where an application might wish greater control over + * when this prepration is done. + */ + @Override + public void prepare() { + } + + /** + * Reset any internal caches. Some systems, such as the tabled backchainer, + * retain information after each query. A reset will wipe this information + * preventing unbounded memory use at the expense of more expensive future + * queries. A reset does not cause the raw data to be reconsulted and so is + * less expensive than a rebind. + */ + @Override + public void reset() { + } + + /** + * Test a global boolean property of the graph. This might included + * properties like consistency, OWLSyntacticValidity etc. It remains to be + * seen what level of generality is needed here. We could replace this by a + * small number of specific tests for common concepts. + * + * @param property the URI of the property to be tested + * @return a Node giving the value of the global property, this may be a + * boolean literal, some other literal value (e.g. a size). + */ + @Override + public Node getGlobalProperty(Node property) { + throw new ReasonerException("Global property not implemented: " + + property); + } + + /** + * A convenience version of getGlobalProperty which can only return a + * boolean result. + * + * @param property the {@link Node} Jena property. + * @return the {@link Boolean} is True if all the operation ared one. + */ + @Override + public boolean testGlobalProperty(Node property) { + Node resultNode = getGlobalProperty(property); + if (resultNode.isLiteral()) { + Object result = resultNode.getLiteralValue(); + if (result instanceof Boolean) { + return (Boolean) result; + } + } + throw new ReasonerException( + "Global property test returned non-boolean value" + + "\nTest was: " + property + "\nResult was: " + + resultNode); + } + + /** + * Test the consistency of the bound data. This normally tests the validity + * of the bound instance data against the bound schema data. + * + * @return a ValidityReport structure + */ + @Override + public ValidityReport validate() { + checkOpen(); + return new StandardValidityReport(); + } + + /** + * An extension of the Graph.find interface which allows the caller to + * encode complex expressions in RDF and then refer to those expressions + * within the query triple. For example, one might encode a class expression + * and then ask if there are any instances of this class expression in the + * InfGraph. + * + * @param subject the subject Node of the query triple, may be a Node in the + * graph or a node in the parameter micro-graph or null + * @param property the property to be retrieved or null + * @param object the object Node of the query triple, may be a Node in the + * graph or a node in the parameter micro-graph. + * @param param a small graph encoding an expression which the subject and/or + * object nodes refer. + * @return the {@link ExtendedIterator} of Triple. + */ + @Override + public ExtendedIterator find(Node subject, Node property, + Node object, Graph param) { + return cloneWithPremises(param).find(subject, property, object); + } + + /** + * Return a new inference graph which is a clone of the current graph + * together with an additional set of data premises. The default + * implementation loses ALL partial deductions so far. Some subclasses may + * be able to a more efficient job. + * + * @param premises the {@link Graph} jena. + * @return the {@link Graph} + */ + public Graph cloneWithPremises(Graph premises) { + MultiUnion union = new MultiUnion(); + union.addGraph(this); + union.setBaseGraph(this); + union.addGraph(premises); + return union; + } + + /** + * Switch on/off drivation logging + * + * @param logOn {@link Boolean} + */ + @Override + public void setDerivationLogging(boolean logOn) { + recordDerivations = logOn; + } + + /** + * Return the derivation of the given triple (which is the result of some + * previous find operation). Not all reasoneers will support derivations. + * + * @param triple {@link Triple} + * @return an iterator over Derivation records or null if there is no + * derivation information available for this triple. + */ + @Override + public Iterator getDerivation(Triple triple) { + return null; + } + + /** + * Returns a derivations graph. The rule reasoners typically create a graph + * containing those triples added to the base graph due to rule firings. In + * some applications it can useful to be able to access those deductions + * directly, without seeing the raw data which triggered them. In + * particular, this allows the forward rules to be used as if they were + * rewrite transformation rules. + * + * @return the deductions graph, if relevant for this class of inference + * engine or null if not. + */ + @Override + public Graph getDeductionsGraph() { + return null; + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtModel.java b/src/main/java/virtuoso/jena/driver/VirtModel.java index 7d601d4..826e049 100644 --- a/src/main/java/virtuoso/jena/driver/VirtModel.java +++ b/src/main/java/virtuoso/jena/driver/VirtModel.java @@ -22,64 +22,67 @@ */ package virtuoso.jena.driver; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.impl.ModelCom; import virtuoso.jdbc4.VirtuosoDataSource; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.rdf.model.impl.ModelCom; - public class VirtModel extends ModelCom { - /** - * @param base - */ - public VirtModel(VirtGraph base) { - super(base); - } + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtModel.class); + + /** + * @param base {@link VirtGraph} + */ + public VirtModel(VirtGraph base) { + super(base); + } - public static VirtModel openDefaultModel(VirtuosoDataSource ds) { - return new VirtModel(new VirtGraph(ds)); - } + public static VirtModel openDefaultModel(VirtuosoDataSource ds) { + return new VirtModel(new VirtGraph(ds)); + } - public static VirtModel openDatabaseModel(String graphName, - VirtuosoDataSource ds) { - return new VirtModel(new VirtGraph(graphName, ds)); - } + public static VirtModel openDatabaseModel(String graphName, + VirtuosoDataSource ds) { + return new VirtModel(new VirtGraph(graphName, ds)); + } - public static VirtModel openDefaultModel(String url, String user, - String password) { - return new VirtModel(new VirtGraph(url, user, password)); - } + public static VirtModel openDefaultModel(String url, String user, + String password) { + return new VirtModel(new VirtGraph(url, user, password)); + } - public static VirtModel openDatabaseModel(String graphName, String url, - String user, String password) { - return new VirtModel(new VirtGraph(graphName, url, user, password)); - } + public static VirtModel openDatabaseModel(String graphName, String url, + String user, String password) { + return new VirtModel(new VirtGraph(graphName, url, user, password)); + } - // --java5 or newer @Override - public Model removeAll() { - try { - VirtGraph _graph = (VirtGraph) this.graph; - _graph.clear(); - } catch (ClassCastException e) { - super.removeAll(); - } - return this; - } + // --java5 or newer @Override + @Override + public Model removeAll() { + try { + VirtGraph _graph = (VirtGraph) this.graph; + _graph.clear(); + } catch (ClassCastException e) { + super.removeAll(); + } + return this; + } - public void createRuleSet(String ruleSetName, String uriGraphRuleSet) { - ((VirtGraph) this.graph).createRuleSet(ruleSetName, uriGraphRuleSet); - } + public void createRuleSet(String ruleSetName, String uriGraphRuleSet) { + ((VirtGraph) this.graph).createRuleSet(ruleSetName, uriGraphRuleSet); + } - public void removeRuleSet(String ruleSetName, String uriGraphRuleSet) { - ((VirtGraph) this.graph).removeRuleSet(ruleSetName, uriGraphRuleSet); - } + public void removeRuleSet(String ruleSetName, String uriGraphRuleSet) { + ((VirtGraph) this.graph).removeRuleSet(ruleSetName, uriGraphRuleSet); + } - public void setRuleSet(String _ruleSet) { - ((VirtGraph) this.graph).setRuleSet(_ruleSet); - } + public void setRuleSet(String _ruleSet) { + ((VirtGraph) this.graph).setRuleSet(_ruleSet); + } - public void setSameAs(boolean _sameAs) { - ((VirtGraph) this.graph).setSameAs(_sameAs); - } + public void setSameAs(boolean _sameAs) { + ((VirtGraph) this.graph).setSameAs(_sameAs); + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtPrefixMapping.java b/src/main/java/virtuoso/jena/driver/VirtPrefixMapping.java index b57b3bb..b5bd025 100644 --- a/src/main/java/virtuoso/jena/driver/VirtPrefixMapping.java +++ b/src/main/java/virtuoso/jena/driver/VirtPrefixMapping.java @@ -26,101 +26,105 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; -import java.util.Iterator; import java.util.Map; -import com.hp.hpl.jena.shared.JenaException; -import com.hp.hpl.jena.shared.PrefixMapping; -import com.hp.hpl.jena.shared.impl.PrefixMappingImpl; +import org.apache.jena.shared.JenaException; +import org.apache.jena.shared.PrefixMapping; +import org.apache.jena.shared.impl.PrefixMappingImpl; public class VirtPrefixMapping extends PrefixMappingImpl { - protected VirtGraph m_graph = null; - - /** - * Constructor for a persistent prefix mapping. - * - */ - public VirtPrefixMapping(VirtGraph graph) { - super(); - m_graph = graph; - - // Populate the prefix map using data from the - // persistent graph properties - String query = "DB.DBA.XML_SELECT_ALL_NS_DECLS (3)"; - try { - Statement stmt = m_graph.createStatement(); - ResultSet rs = stmt.executeQuery(query); - - while (rs.next()) { - String prefix = rs.getString(1); - String uri = rs.getString(2); - if (uri != null && uri != null) - super.setNsPrefix(prefix, uri); - } - rs.close(); - stmt.close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - public PrefixMapping removeNsPrefix(String prefix) { - String query = "DB.DBA.XML_REMOVE_NS_BY_PREFIX(?, 1)"; - super.removeNsPrefix(prefix); - - try { - PreparedStatement ps = m_graph.prepareStatement(query); - ps.setString(1, prefix); - ps.execute(); - ps.close(); - } catch (Exception e) { - throw new JenaException(e); - } - - return this; - } - - /* - * (non-Javadoc) Override the default implementation so we can catch the - * write operation and update the persistent store. - * - * @see com.hp.hpl.jena.shared.PrefixMapping#setNsPrefix(java.lang.String, - * java.lang.String) - */ - public PrefixMapping setNsPrefix(String prefix, String uri) { - super.setNsPrefix(prefix, uri); - - String query = "DB.DBA.XML_SET_NS_DECL(?, ?, 1)"; - - // All went well, so persist the prefix by adding it to the graph - // properties - // (the addPrefix call will overwrite any existing mapping with the same - // prefix - // so it matches the behaviour of the prefixMappingImpl). - try { - PreparedStatement ps = m_graph.prepareStatement(query); - ps.setString(1, prefix); - ps.setString(2, uri); - ps.execute(); - ps.close(); - } catch (Exception e) { - throw new JenaException(e.toString()); - } - return this; - } - - public PrefixMapping setNsPrefixes(PrefixMapping other) { - return setNsPrefixes(other.getNsPrefixMap()); - } - - public PrefixMapping setNsPrefixes(Map other) { - checkUnlocked(); - Iterator it = other.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry e = (Map.Entry) it.next(); - setNsPrefix((String) e.getKey(), (String) e.getValue()); - } - return this; - } + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtPrefixMapping.class); + + protected VirtGraph m_graph = null; + + /** + * Constructor for a persistent prefix mapping. + * + * @param graph the {@link VirtGraph} + */ + public VirtPrefixMapping(VirtGraph graph) { + super(); + m_graph = graph; + + // Populate the prefix map using data from the + // persistent graph properties + String query = "DB.DBA.XML_SELECT_ALL_NS_DECLS (3)"; + try { + try (Statement stmt = m_graph.createStatement(); ResultSet rs = stmt.executeQuery(query)) { + + while (rs.next()) { + String prefix = rs.getString(1); + String uri = rs.getString(2); + if (uri != null) + super.setNsPrefix(prefix, uri); + } + } + } catch (Exception e) { + throw new JenaException(e); + } + } + + @Override + public PrefixMapping removeNsPrefix(String prefix) { + String query = "DB.DBA.XML_REMOVE_NS_BY_PREFIX(?, 1)"; + super.removeNsPrefix(prefix); + + try { + try (PreparedStatement ps = m_graph.createPreparedStatement(query)) { + ps.setString(1, prefix); + ps.execute(); + } + } catch (Exception e) { + throw new JenaException(e); + } + + return this; + } + + /* + * (non-Javadoc) Override the default implementation so we can catch the + * write operation and update the persistent store. + * + * @see com.hp.hpl.jena.shared.PrefixMapping#setNsPrefix(java.lang.String, + * java.lang.String) + */ + @Override + public PrefixMapping setNsPrefix(String prefix, String uri) { + super.setNsPrefix(prefix, uri); + + String query = "DB.DBA.XML_SET_NS_DECL(?, ?, 1)"; + + // All went well, so persist the prefix by adding it to the graph + // properties + // (the addPrefix call will overwrite any existing mapping with the same + // prefix + // so it matches the behaviour of the prefixMappingImpl). + try { + try (PreparedStatement ps = m_graph.createPreparedStatement(query)) { + ps.setString(1, prefix); + ps.setString(2, uri); + ps.execute(); + } + } catch (Exception e) { + throw new JenaException(e.toString()); + } + return this; + } + + @Override + public PrefixMapping setNsPrefixes(PrefixMapping other) { + return setNsPrefixes(other.getNsPrefixMap()); + } + + @Override + public PrefixMapping setNsPrefixes(Map other) { + checkUnlocked(); + for (Object o : other.entrySet()) { + Map.Entry e = (Map.Entry) o; + setNsPrefix((String) e.getKey(), (String) e.getValue()); + } + return this; + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtResSetIter.java b/src/main/java/virtuoso/jena/driver/VirtResSetIter.java index 814e5a4..51435a7 100644 --- a/src/main/java/virtuoso/jena/driver/VirtResSetIter.java +++ b/src/main/java/virtuoso/jena/driver/VirtResSetIter.java @@ -23,132 +23,142 @@ package virtuoso.jena.driver; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.Triple; +import org.apache.jena.shared.JenaException; +import org.apache.jena.util.iterator.NiceIterator; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.NoSuchElementException; -import com.hp.hpl.jena.graph.Node; -import com.hp.hpl.jena.graph.Triple; -import com.hp.hpl.jena.graph.TripleMatch; -import com.hp.hpl.jena.shared.JenaException; -import com.hp.hpl.jena.util.iterator.NiceIterator; - public class VirtResSetIter extends NiceIterator { - protected ResultSet v_resultSet; - protected Triple v_row; - protected TripleMatch v_in; - protected boolean v_finished = false; - protected boolean v_prefetched = false; - protected VirtGraph v_graph = null; - protected PreparedStatement v_stmt = null; - - public VirtResSetIter() { - v_finished = true; - } - - public VirtResSetIter(VirtGraph graph, ResultSet resultSet, TripleMatch in, - PreparedStatement stmt) { - v_resultSet = resultSet; - v_in = in; - v_graph = graph; - v_stmt = stmt; - } - - public void reset(ResultSet resultSet, PreparedStatement sourceStatement) { - v_resultSet = resultSet; - v_finished = false; - v_prefetched = false; - v_row = null; - } - - public boolean hasNext() { - if (!v_finished && !v_prefetched) - moveForward(); - return !v_finished; - } - - public Triple removeNext() { - Triple ret = next(); - remove(); - return ret; - } - - public Triple next() { - if (!v_finished && !v_prefetched) - moveForward(); - - v_prefetched = false; - - if (v_finished) - throw new NoSuchElementException(); - - return getRow(); - } - - public void remove() { - if (v_row != null && v_graph != null) { - v_graph.delete(v_row); - v_row = null; - } - } - - protected void moveForward() { - try { - if (!v_finished && v_resultSet.next()) { - extractRow(); - v_prefetched = true; - } else - close(); - } catch (Exception e) { - throw new JenaException(e); - } - } - - protected void extractRow() throws Exception { - Node NodeS, NodeP, NodeO; - - if (v_in.getMatchSubject() != null) - NodeS = v_in.getMatchSubject(); - else - NodeS = VirtGraph.Object2Node(v_resultSet.getObject("s")); - - if (v_in.getMatchPredicate() != null) - NodeP = v_in.getMatchPredicate(); - else - NodeP = VirtGraph.Object2Node(v_resultSet.getObject("p")); - - if (v_in.getMatchObject() != null) - NodeO = v_in.getMatchObject(); - else - NodeO = VirtGraph.Object2Node(v_resultSet.getObject("o")); - - v_row = new Triple(NodeS, NodeP, NodeO); - } - - protected Triple getRow() { - return v_row; - } - - public void close() { - if (!v_finished) { - if (v_resultSet != null) { - try { - v_resultSet.close(); - v_stmt.close(); - v_resultSet = null; - v_stmt = null; - } catch (SQLException e) { - throw new JenaException(e); - } - } - } - v_finished = true; - } - - protected void finalize() throws SQLException { - if (!v_finished && v_resultSet != null) - close(); - } + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtResSetIter.class); + + protected ResultSet v_resultSet; + protected Triple v_row; + protected Triple v_in; + protected boolean v_finished = false; + protected boolean v_prefetched = false; + protected VirtGraph v_graph = null; + protected PreparedStatement v_stmt = null; + + public VirtResSetIter() { + v_finished = true; + } + + public VirtResSetIter(VirtGraph graph, ResultSet resultSet, Triple in, + PreparedStatement stmt) { + v_resultSet = resultSet; + v_in = in; + v_graph = graph; + v_stmt = stmt; + } + + public void reset(ResultSet resultSet, PreparedStatement sourceStatement) { + v_resultSet = resultSet; + v_finished = false; + v_prefetched = false; + v_row = null; + } + + @Override + public boolean hasNext() { + if (!v_finished && !v_prefetched) + moveForward(); + return !v_finished; + } + + @Override + public Triple removeNext() { + Triple ret = next(); + remove(); + return ret; + } + + @Override + public Triple next() { + if (!v_finished && !v_prefetched) + moveForward(); + + v_prefetched = false; + + if (v_finished) + throw new NoSuchElementException(); + + return getRow(); + } + + @Override + public void remove() { + if (v_row != null && v_graph != null) { + v_graph.delete(v_row); + v_row = null; + } + } + + protected void moveForward() { + try { + if (!v_finished && v_resultSet.next()) { + extractRow(); + v_prefetched = true; + } else + close(); + } catch (Exception e) { + throw new JenaException(e); + } + } + + protected void extractRow() throws Exception { + Node NodeS, NodeP, NodeO; + + if (v_in.getMatchSubject() != null) + NodeS = v_in.getMatchSubject(); + else + NodeS = VirtUtilities.toNode(v_resultSet.getObject("s")); + + if (v_in.getMatchPredicate() != null) + NodeP = v_in.getMatchPredicate(); + else + NodeP = VirtUtilities.toNode(v_resultSet.getObject("p")); + + if (v_in.getMatchObject() != null) + NodeO = v_in.getMatchObject(); + else + NodeO = VirtUtilities.toNode(v_resultSet.getObject("o")); + + v_row = new Triple(NodeS, NodeP, NodeO); + } + + protected Triple getRow() { + return v_row; + } + + @Override + public void close() { + if (!v_finished) { + if (v_resultSet != null) { + try { + v_resultSet.close(); + v_stmt.close(); + v_resultSet = null; + v_stmt = null; + } catch (SQLException e) { + throw new JenaException(e); + } + } + } + v_finished = true; + } + + @Override + protected void finalize() throws Throwable { + if (!v_finished && v_resultSet != null) + super.finalize(); + close(); + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtTransactionHandler.java b/src/main/java/virtuoso/jena/driver/VirtTransactionHandler.java index 1d942ff..8c7939c 100644 --- a/src/main/java/virtuoso/jena/driver/VirtTransactionHandler.java +++ b/src/main/java/virtuoso/jena/driver/VirtTransactionHandler.java @@ -26,86 +26,93 @@ import java.sql.Connection; import java.sql.SQLException; -import com.hp.hpl.jena.graph.impl.TransactionHandlerBase; -import com.hp.hpl.jena.shared.JenaException; +import org.apache.jena.graph.impl.TransactionHandlerBase; +import org.apache.jena.shared.JenaException; public class VirtTransactionHandler extends TransactionHandlerBase { - private VirtGraph graph = null; - private Boolean m_transactionsSupported = null; + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtTransactionHandler.class); - public VirtTransactionHandler(VirtGraph _graph) { - super(); - this.graph = _graph; - } + private VirtGraph graph = null; + private Boolean m_transactionsSupported = null; - public boolean transactionsSupported() { - if (m_transactionsSupported != null) { - return (m_transactionsSupported.booleanValue()); - } + public VirtTransactionHandler(VirtGraph _graph) { + super(); + this.graph = _graph; + } - try { - Connection c = graph.getConnection(); - if (c != null) { - m_transactionsSupported = new Boolean(c.getMetaData() - .supportsMultipleTransactions()); - return (m_transactionsSupported.booleanValue()); - } - } catch (Exception e) { - throw new JenaException(e); - } - return (false); - } + @Override + public boolean transactionsSupported() { + if (m_transactionsSupported != null) { + return (m_transactionsSupported); + } - public void begin() { - if (transactionsSupported()) { - try { - Connection c = graph.getConnection(); - if (c.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - } - if (c.getAutoCommit()) { - c.setAutoCommit(false); - } - } catch (SQLException e) { - throw new JenaException("Transaction begin failed: ", e); - } - } else { - notSupported("begin transaction"); - } - } + try { + Connection c = graph.getConnection(); + if (c != null) { + m_transactionsSupported = c.getMetaData() + .supportsMultipleTransactions(); + return (m_transactionsSupported); + } + } catch (Exception e) { + throw new JenaException(e); + } + return (false); + } - public void abort() { - if (transactionsSupported()) { - try { - Connection c = graph.getConnection(); - c.rollback(); - c.commit(); - c.setAutoCommit(true); - } catch (SQLException e) { - throw new JenaException("Transaction rollback failed: ", e); - } - } else { - notSupported("abort transaction"); - } - } + @Override + public void begin() { + if (transactionsSupported()) { + try { + Connection c = graph.getConnection(); + if (c.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + } + if (c.getAutoCommit()) { + c.setAutoCommit(false); + } + } catch (SQLException e) { + throw new JenaException("Transaction begin failed: ", e); + } + } else { + notSupported("begin transaction"); + } + } - public void commit() { - if (transactionsSupported()) { - try { - Connection c = graph.getConnection(); - c.commit(); - c.setAutoCommit(true); - } catch (SQLException e) { - throw new JenaException("Transaction commit failed: ", e); - } - } else { - notSupported("commit transaction"); - } - } + @Override + public void abort() { + if (transactionsSupported()) { + try { + Connection c = graph.getConnection(); + c.rollback(); + c.commit(); + c.setAutoCommit(true); + } catch (SQLException e) { + throw new JenaException("Transaction rollback failed: ", e); + } + } else { + notSupported("abort transaction"); + } + } - private void notSupported(String opName) { - throw new UnsupportedOperationException(opName); - } + @Override + public void commit() { + if (transactionsSupported()) { + try { + Connection c = graph.getConnection(); + c.commit(); + c.setAutoCommit(true); + } catch (SQLException e) { + throw new JenaException("Transaction commit failed: ", e); + } + } else { + notSupported("commit transaction"); + } + } + + private void notSupported(String opName) { + throw new UnsupportedOperationException(opName); + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtUtilities.java b/src/main/java/virtuoso/jena/driver/VirtUtilities.java new file mode 100644 index 0000000..fa0a838 --- /dev/null +++ b/src/main/java/virtuoso/jena/driver/VirtUtilities.java @@ -0,0 +1,423 @@ +package virtuoso.jena.driver; + +import org.apache.jena.datatypes.RDFDatatype; +import org.apache.jena.datatypes.TypeMapper; +import org.apache.jena.datatypes.xsd.XSDDatatype; +import org.apache.jena.graph.BlankNodeId; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.graph.impl.LiteralLabel; +import org.apache.jena.iri.IRI; +import org.apache.jena.iri.IRIFactory; +import org.apache.jena.query.Query; +import org.apache.jena.query.QueryFactory; +import org.apache.jena.query.QuerySolution; +import org.apache.jena.rdf.model.Literal; +import org.apache.jena.rdf.model.RDFNode; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.sparql.util.NodeUtils; + +import java.util.Calendar; +import java.util.GregorianCalendar; + +/** + * Created by 4535992 on 08/01/2016. + * + * @see if you like these method you can found more on : + */ +public class VirtUtilities { + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtUtilities.class); + + /** + * Method to convert a String uri to a jena Graph Node. + * old name : createNode. + * href: http://willware.blogspot.it/2010/02/jena-node-versus-rdfnode.html + * + * @param resource any element on API Jena can be converted to a Node. + * @return the Jena Graph Node. + */ + private static Node createNodeBase(Object resource, String lang, RDFDatatype rdfDatatype, Boolean xml){ + try { + if (resource == null) { + logger.warn("Try to create a Node from a 'NULL' value"); + return null; + } else if (resource instanceof Node) { + return (Node) resource; + } else if (lang != null && rdfDatatype != null) { + return NodeFactory.createLiteral(String.valueOf(resource), lang, rdfDatatype); + } else if (rdfDatatype != null) { + return NodeFactory.createLiteral(String.valueOf(resource), rdfDatatype); + } else if (lang != null && xml != null) { + return NodeFactory.createLiteral(String.valueOf(resource), lang, xml); + } else if (lang != null) { + return NodeFactory.createLiteral(String.valueOf(resource), lang); + } else { + if (resource instanceof Literal) { + return ((Literal) resource).asNode(); + } else if (resource instanceof Resource) { + return ((Resource) resource).asNode(); + } else if (resource instanceof RDFNode) { + return ((RDFNode) resource).asNode(); + } else if (resource instanceof LiteralLabel) { + return NodeFactory.createLiteral((LiteralLabel) resource); + } else if (resource instanceof virtuoso.sql.ExtendedString) { + virtuoso.sql.ExtendedString vs = (virtuoso.sql.ExtendedString) resource; + if (vs.getIriType() == virtuoso.sql.ExtendedString.IRI + && (vs.getStrType() & 0x01) == 0x01) { + if (vs.toString().indexOf("_:") == 0) + return NodeFactory.createBlankNode(BlankNodeId.create(String.valueOf(vs) + .substring(2))); // _: + else + return NodeFactory.createURI(String.valueOf(vs)); + + } else if (vs.getIriType() == virtuoso.sql.ExtendedString.BNODE) { + return NodeFactory.createBlankNode(BlankNodeId.create(String.valueOf(vs).substring(9))); // nodeID:// + + } else { + return NodeFactory.createLiteral(String.valueOf(vs)); + } + } else if (resource instanceof virtuoso.sql.RdfBox) { + virtuoso.sql.RdfBox rb = (virtuoso.sql.RdfBox) resource; + String rb_type = rb.getType(); + if (rb_type != null) { + return NodeFactory.createLiteral(String.valueOf(rb), rb.getLang(), toRDFDatatype(rb_type)); + } else { + return NodeFactory.createLiteral(String.valueOf(rb), rb.getLang()); + } + } else if (resource instanceof java.lang.Integer) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDinteger)); + } else if (resource instanceof java.lang.Short) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDinteger)); + } else if (resource instanceof java.lang.Float) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDfloat)); + } else if (resource instanceof java.lang.Double) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDdouble)); + } else if (resource instanceof java.math.BigDecimal) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDdecimal)); + } else if (resource instanceof java.sql.Blob) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDhexBinary)); + } else if (resource instanceof java.sql.Date) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDdate)); + } else if (resource instanceof java.sql.Timestamp) { + /* return NodeFactory.createLiteral( + Timestamp2String((java.sql.Timestamp) resource), toRDFDatatype(XSDDatatype.XSDdateTime));*/ + return NodeFactory.createLiteral( + Timestamp2String((java.sql.Timestamp) resource), toRDFDatatype(XSDDatatype.XSDdateTimeStamp)); + } else if (resource instanceof java.sql.Time) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDdateTime)); + } else if (resource instanceof String) { + if (isIRI(resource)) { + return NodeUtils.asNode(String.valueOf(resource)); + /* } else if (isURI(resource) || isURL(resource)) { + return NodeFactory.createURI(String.valueOf(resource)); + } else if (isDouble(resource)) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDdouble)); + } else if (isFloat(resource)) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDfloat)); + } else if (isInt(resource)) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDinteger)); + } else if (isNumeric(resource)) { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDinteger));*/ + } else { + return NodeFactory.createLiteral(String.valueOf(resource), toRDFDatatype(XSDDatatype.XSDstring)); + } + }else{ + logger.error("The Node Datatype '" + resource.getClass().getName() + "' is not recognised"); + return null; + } + } + }catch(Exception e){ + logger.error(e.getMessage(),e); + return null; + } + } + + /** + * Method to check if a String uri is a IRI normalized. + * http://stackoverflow.com/questions/9419658/normalising-possibly-encoded-uri-strings-in-java + * + * @param uri the String to verify. + * @return if true the String is a valid IRI. + */ + private static Boolean isIRI(Object uri) { + try { + IRIFactory factory = IRIFactory.uriImplementation(); + IRI iri = factory.construct(String.valueOf(uri)); + /* ArrayList a = new ArrayList<>(); + a.add(iri.getScheme()); + a.add(iri.getRawUserinfo()); + a.add(iri.getRawHost()); + a.add(iri.getRawPath()); + a.add(iri.getRawQuery()); + a.add(iri.getRawFragment());*/ + return true; + } catch (Exception e) { + return false; + } + } + + /** + * Method to convert a {@link java.sql.Timestamp} to a {@link String} + * + * @param v the {@link java.sql.Timestamp}. + * @return the {@link String} + */ + private static String Timestamp2String(java.sql.Timestamp v) { + GregorianCalendar cal = new GregorianCalendar(); + cal.setTime(v); + + int year = cal.get(Calendar.YEAR); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DAY_OF_MONTH); + int hour = cal.get(Calendar.HOUR_OF_DAY); + int minute = cal.get(Calendar.MINUTE); + int second = cal.get(Calendar.SECOND); + int nanos = v.getNanos(); + + String yearS, monthS, dayS, hourS, minuteS, secondS, nanosS; + String zeros = "000000000"; + String yearZeros = "0000"; + StringBuffer timestampBuf; + + if (year < 1000) { + yearS = "" + year; + yearS = yearZeros.substring(0, (4 - yearS.length())) + yearS; + } else { + yearS = "" + year; + } + + if (month < 10) monthS = "0" + month; + else monthS = Integer.toString(month); + + if (day < 10) dayS = "0" + day; + else dayS = Integer.toString(day); + + if (hour < 10) hourS = "0" + hour; + else hourS = Integer.toString(hour); + + if (minute < 10) minuteS = "0" + minute; + else minuteS = Integer.toString(minute); + + if (second < 10) secondS = "0" + second; + else secondS = Integer.toString(second); + + if (nanos == 0) { + nanosS = "0"; + } else { + nanosS = Integer.toString(nanos); + + // Add leading 0 + nanosS = zeros.substring(0, (9 - nanosS.length())) + nanosS; + + // Truncate trailing 0 + char[] nanosChar = new char[nanosS.length()]; + nanosS.getChars(0, nanosS.length(), nanosChar, 0); + int truncIndex = 8; + while (nanosChar[truncIndex] == '0') { + truncIndex--; + } + nanosS = new String(nanosChar, 0, truncIndex + 1); + } + + timestampBuf = new StringBuffer(); + timestampBuf.append(yearS); + timestampBuf.append("-"); + timestampBuf.append(monthS); + timestampBuf.append("-"); + timestampBuf.append(dayS); + timestampBuf.append("T"); + timestampBuf.append(hourS); + timestampBuf.append(":"); + timestampBuf.append(minuteS); + timestampBuf.append(":"); + timestampBuf.append(secondS); + timestampBuf.append("."); + timestampBuf.append(nanosS); + return (timestampBuf.toString()); + } + + /** + * Method to convert a URI {@link String} to a correct {@link RDFDatatype} jena. + * + * @param uri the {@link String} of the uri resource. + * @return the {@link RDFDatatype} of the uri resource. + */ + public static RDFDatatype toRDFDatatype(String uri) { + return TypeMapper.getInstance().getSafeTypeByName(toXSDDatatype(uri).getURI()); + } + + /** + * Method to convert a {@link XSDDatatype} to a correct {@link RDFDatatype} jena. + * + * @param xsdDatatype the {@link XSDDatatype} of the uri resource. + * @return the {@link RDFDatatype} of the uri resource. + */ + public static RDFDatatype toRDFDatatype(XSDDatatype xsdDatatype) { + return TypeMapper.getInstance().getSafeTypeByName(xsdDatatype.getURI()); + } + + /** + * A list of com.hp.hpl.jena.datatypes.xsd.XSDDatatype. + * return all the XSDDatatype supported from jena. + */ + public static final XSDDatatype allFormatsOfXSDDataTypes[] = new XSDDatatype[]{ + XSDDatatype.XSDstring, XSDDatatype.XSDENTITY, XSDDatatype.XSDID, XSDDatatype.XSDIDREF, + XSDDatatype.XSDanyURI, XSDDatatype.XSDbase64Binary, XSDDatatype.XSDboolean, XSDDatatype.XSDbyte, + XSDDatatype.XSDdate, XSDDatatype.XSDdateTime, XSDDatatype.XSDdecimal, XSDDatatype.XSDdouble, + XSDDatatype.XSDduration, XSDDatatype.XSDfloat, XSDDatatype.XSDgDay, XSDDatatype.XSDgMonth, + XSDDatatype.XSDgMonthDay, XSDDatatype.XSDgYear, XSDDatatype.XSDgYearMonth, XSDDatatype.XSDhexBinary, + XSDDatatype.XSDint, XSDDatatype.XSDinteger, XSDDatatype.XSDlanguage, XSDDatatype.XSDlong, + XSDDatatype.XSDName, XSDDatatype.XSDNCName, XSDDatatype.XSDnegativeInteger, XSDDatatype.XSDNMTOKEN, + XSDDatatype.XSDnonNegativeInteger, XSDDatatype.XSDnonPositiveInteger, XSDDatatype.XSDnormalizedString, + XSDDatatype.XSDNOTATION, XSDDatatype.XSDpositiveInteger, XSDDatatype.XSDQName, XSDDatatype.XSDshort, + XSDDatatype.XSDtime, XSDDatatype.XSDtoken, XSDDatatype.XSDunsignedByte, XSDDatatype.XSDunsignedInt, + XSDDatatype.XSDunsignedLong, XSDDatatype.XSDunsignedShort + }; + + /** + * Method convert a {@link String} to {@link XSDDatatype}. + * + * @param uri the {@link String} uri of the XSDDatatype. + * @return the {@link XSDDatatype} of the string uri if exists. + */ + public static XSDDatatype toXSDDatatype(String uri) { + for (XSDDatatype xsdDatatype : allFormatsOfXSDDataTypes) { + if (xsdDatatype.getURI().equalsIgnoreCase(XSDDatatype.XSD + "#" + uri)) return xsdDatatype; + if (xsdDatatype.getURI().replace(XSDDatatype.XSD, "") + .toLowerCase().contains(uri.toLowerCase())) return xsdDatatype; + } + logger.error("The XSD Datatype '" + uri + "' is not recognised"); + throw new IllegalArgumentException("The XSD Datatype '" + uri + "' is not recognised"); + } + + public static Node toNode(Object resource, String lang, RDFDatatype rdfDatatype) { + return createNodeBase(resource, null, rdfDatatype, null); + } + + public static Node toNode(Object resource, String lang, boolean isXml) { + return createNodeBase(resource, null, null, isXml); + } + + public static Node toNode(Object resource) { + return createNodeBase(resource, null, null, null); + } + + public static Node toNode(Object resource, RDFDatatype rdfDatatype) { + return createNodeBase(resource, null, rdfDatatype, null); + } + + private static String escapeString(String s) { + StringBuilder buf = new StringBuilder(s.length()); + int i = 0; + char ch; + while (i < s.length()) { + ch = s.charAt(i++); + if (ch == '\'') + buf.append('\\'); + buf.append(ch); + } + return buf.toString(); + } + + // GraphBase overrides + public static String toString(Node n) { + if (n.isURI()) { + return "<" + n + ">"; + } else if (n.isBlank()) { + return "<_:" + n + ">"; + } else if (n.isLiteral()) { + String s; + StringBuilder sb = new StringBuilder(); + sb.append("'"); + sb.append(escapeString(n.getLiteralValue().toString())); + sb.append("'"); + + s = n.getLiteralLanguage(); + if (s != null && s.length() > 0) { + sb.append("@"); + sb.append(s); + } + s = n.getLiteralDatatypeURI(); + if (s != null && s.length() > 0) { + sb.append("^^<"); + sb.append(s); + sb.append(">"); + } + return sb.toString(); + } else { + return "<" + n + ">"; + } + } + + /** + * Method to substitute all Bindings on the query String. + * @param query the String of the Query. + * @param querySolution the QuerySolution with the variable to check. + * @return the content String of the Query update. + */ + public static String substituteBindings(String query, QuerySolution querySolution) { + if (querySolution == null)return query; + + StringBuilder buf = new StringBuilder(); + String delim = " ,)(;."; + int i = 0; + char ch; + int qlen = query.length(); + while (i < qlen) { + ch = query.charAt(i++); + if (ch == '\\') { + buf.append(ch); + if (i < qlen) + buf.append(query.charAt(i++)); + + } else if (ch == '"' || ch == '\'') { + char end = ch; + buf.append(ch); + while (i < qlen) { + ch = query.charAt(i++); + buf.append(ch); + if (ch == end) + break; + } + } else if (ch == '?') { // Parameter + String varData = null; + int j = i; + while (j < qlen && delim.indexOf(query.charAt(j)) < 0) + j++; + if (j != i) { + String varName = query.substring(i, j); + RDFNode val = querySolution.get(varName); + if (val != null) { + varData = toString(val.asNode()); + i = j; + } + } + if (varData != null) + buf.append(varData); + else + buf.append(ch); + } else { + buf.append(ch); + } + } + return buf.toString(); + } + + // Make query + + public static Query toQuery(String queryStr) { + return QueryFactory.create(queryStr); + } + + public static Query toQuery(Query query) { + return QueryFactory.create(query); + } + + + + + + +} diff --git a/src/main/java/virtuoso/jena/driver/VirtuosoQueryEngine.java b/src/main/java/virtuoso/jena/driver/VirtuosoQueryEngine.java index 1653666..56c7405 100644 --- a/src/main/java/virtuoso/jena/driver/VirtuosoQueryEngine.java +++ b/src/main/java/virtuoso/jena/driver/VirtuosoQueryEngine.java @@ -24,306 +24,311 @@ import org.apache.jena.atlas.io.IndentedWriter; -import com.hp.hpl.jena.graph.Node; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.shared.JenaException; -import com.hp.hpl.jena.sparql.ARQInternalErrorException; -import com.hp.hpl.jena.sparql.algebra.Op; -import com.hp.hpl.jena.sparql.algebra.Transform; -import com.hp.hpl.jena.sparql.algebra.TransformCopy; -import com.hp.hpl.jena.sparql.algebra.Transformer; -import com.hp.hpl.jena.sparql.algebra.op.OpBGP; -import com.hp.hpl.jena.sparql.core.DatasetGraph; -import com.hp.hpl.jena.sparql.core.Var; -import com.hp.hpl.jena.sparql.engine.Plan; -import com.hp.hpl.jena.sparql.engine.QueryEngineFactory; -import com.hp.hpl.jena.sparql.engine.QueryEngineRegistry; -import com.hp.hpl.jena.sparql.engine.QueryIterator; -import com.hp.hpl.jena.sparql.engine.binding.Binding; -import com.hp.hpl.jena.sparql.engine.binding.BindingHashMap; -import com.hp.hpl.jena.sparql.engine.binding.BindingMap; -import com.hp.hpl.jena.sparql.engine.iterator.QueryIteratorBase; -import com.hp.hpl.jena.sparql.engine.main.QueryEngineMain; -import com.hp.hpl.jena.sparql.serializer.SerializationContext; -import com.hp.hpl.jena.sparql.util.Context; -import com.hp.hpl.jena.sparql.util.Utils; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.query.Query; +import org.apache.jena.shared.JenaException; +import org.apache.jena.sparql.ARQInternalErrorException; +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.Transform; +import org.apache.jena.sparql.algebra.TransformCopy; +import org.apache.jena.sparql.algebra.Transformer; +import org.apache.jena.sparql.algebra.op.OpBGP; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.engine.Plan; +import org.apache.jena.sparql.engine.QueryEngineFactory; +import org.apache.jena.sparql.engine.QueryEngineRegistry; +import org.apache.jena.sparql.engine.QueryIterator; +import org.apache.jena.sparql.engine.binding.Binding; +import org.apache.jena.sparql.engine.binding.BindingHashMap; +import org.apache.jena.sparql.engine.binding.BindingMap; +import org.apache.jena.sparql.engine.iterator.QueryIteratorBase; +import org.apache.jena.sparql.engine.main.QueryEngineMain; +import org.apache.jena.sparql.serializer.SerializationContext; +import org.apache.jena.sparql.util.Context; + public class VirtuosoQueryEngine extends QueryEngineMain { - private Query eQuery = null; - - public VirtuosoQueryEngine(Query query, DatasetGraph dataset, - Binding initial, Context context) { - super(query, dataset, initial, context); - eQuery = query; - } - - public VirtuosoQueryEngine(Query query, DatasetGraph dataset) { - this(query, dataset, null, null); - } - - @Override - public QueryIterator eval(Op op, DatasetGraph dsg, Binding initial, - Context context) { - // Extension point: access possible to all the parameters for execution. - // Be careful to deal with initial bindings. - Transform transform = new VirtTransform(); - op = Transformer.transform(transform, op); - - VirtGraph vg = (VirtGraph) dsg.getDefaultGraph(); - String query = fixQuery(eQuery.toString(), initial, vg); - - try { - java.sql.Statement stmt = vg.createStatement(); - java.sql.ResultSet rs = stmt.executeQuery(query); - return (QueryIterator) new VQueryIterator(vg, rs); - } catch (Exception e) { - throw new JenaException("Can not create QueryIterator.:" + e); - } - } - - private String substBindings(String query, Binding args) { - if (args == null) - return query; - - StringBuffer buf = new StringBuffer(); - String delim = " ,)(;."; - int i = 0; - char ch; - int qlen = query.length(); - while (i < qlen) { - ch = query.charAt(i++); - if (ch == '\\') { - buf.append(ch); - if (i < qlen) - buf.append(query.charAt(i++)); - - } else if (ch == '"' || ch == '\'') { - char end = ch; - buf.append(ch); - while (i < qlen) { - ch = query.charAt(i++); - buf.append(ch); - if (ch == end) - break; - } - } else if (ch == '?') { // Parameter - String varData = null; - int j = i; - while (j < qlen && delim.indexOf(query.charAt(j)) < 0) - j++; - if (j != i) { - String varName = query.substring(i, j); - Node val = args.get(Var.alloc(varName)); - if (val != null) { - varData = VirtGraph.Node2Str(val); - i = j; - } - } - if (varData != null) - buf.append(varData); - else - buf.append(ch); - } else { - buf.append(ch); - } - } - return buf.toString(); - } - - private String fixQuery(String query, Binding args, VirtGraph vg) { - StringBuffer sb = new StringBuffer("sparql\n "); - - if (vg.getRuleSet() != null) - sb.append(" define input:inference '" + vg.getRuleSet() + "'\n "); - - if (vg.getSameAs()) - sb.append(" define input:same-as \"yes\"\n "); - - if (!vg.getReadFromAllGraphs()) - sb.append(" define input:default-graph-uri <" + vg.getGraphName() - + "> \n"); - - sb.append(substBindings(query, args)); - - return sb.toString(); - } - - @Override - protected Op modifyOp(Op op) { - // Extension point: possible place to alter the algebra expression. - // Alternative to eval(). - op = super.modifyOp(op); - return op; - } - - // ---- Registration of the factory for this query engine class. - - // Query engine factory. - // Call VirtQueryEngine.register() to add to the global query engine - // registry. - - static QueryEngineFactory factory = new VirtQueryEngineFactory(); - - static public QueryEngineFactory getFactory() { - return factory; - } - - static public void register() { - QueryEngineRegistry.addFactory(factory); - } - - static public void unregister() { - QueryEngineRegistry.removeFactory(factory); - } - - private class VirtTransform extends TransformCopy { - // Example, do nothing tranform. - @Override - public Op transform(OpBGP opBGP) { - return opBGP; - } - } - - private static class VirtQueryEngineFactory implements QueryEngineFactory { - // Accept any dataset for query execution - public boolean accept(Query query, DatasetGraph dataset, Context context) { - if (dataset instanceof VirtDataSource.VirtDataSetGraph) - return true; - if (dataset.getDefaultGraph() instanceof VirtGraph) - return true; - return false; - } - - public Plan create(Query query, DatasetGraph dataset, Binding initial, - Context context) { - if (!(dataset instanceof VirtDataSource.VirtDataSetGraph)) { - if (!(dataset.getDefaultGraph() instanceof VirtGraph)) - throw new ARQInternalErrorException( - "VirtQueryEngineFactory: only factory VirtuosoDatasetGraph is supported"); - } - // Create a query engine instance. - VirtuosoQueryEngine engine = new VirtuosoQueryEngine(query, - dataset, initial, context); - return engine.getPlan(); - } - - public boolean accept(Op op, DatasetGraph dataset, Context context) { // Refuse - // to - // accept - // algebra - // expressions - // directly. - return false; - } - - public Plan create(Op op, DatasetGraph dataset, Binding inputBinding, - Context context) { // Shodul notbe called because acceept/Op is - // false - throw new ARQInternalErrorException( - "VirtQueryEngineFactory: factory calleddirectly with an algebra expression"); - } - } - - protected class VQueryIterator extends QueryIteratorBase { - java.sql.ResultSetMetaData rsmd; - java.sql.ResultSet rs; - VirtGraph vg; - boolean v_finished = false; - boolean v_prefetched = false; - BindingMap v_row; - String virt_graph = null; - - protected VQueryIterator(VirtGraph _g, java.sql.ResultSet _rs) { - rs = _rs; - vg = _g; - virt_graph = vg.getGraphName(); - - try { - rsmd = rs.getMetaData(); - } catch (Exception e) { - throw new JenaException("VQueryIterator is FAILED.:" + e); - } - - } - - public void output(IndentedWriter out, SerializationContext sCxt) { - out.print(Utils.className(this)); - } - - protected boolean hasNextBinding() { - if (!v_finished && !v_prefetched) - moveForward(); - return !v_finished; - } - - protected Binding moveToNextBinding() { - if (!v_finished && !v_prefetched) - moveForward(); - - v_prefetched = false; - - if (v_finished) - return null; - - return v_row; - } - - protected void closeIterator() { - if (!v_finished) { - if (rs != null) { - try { - rs.close(); - rs = null; - } catch (Exception e) { - } - } - } - v_finished = true; - } - - protected void moveForward() throws JenaException { - try { - if (!v_finished && rs.next()) { - extractRow(); - v_prefetched = true; - } else - closeIterator(); - } catch (Exception e) { - throw new JenaException("Convert results are FAILED.:" + e); - } - } - - protected void extractRow() throws Exception { - v_row = new BindingHashMap(); - - try { - for (int i = 1; i <= rsmd.getColumnCount(); i++) { - Node n = VirtGraph.Object2Node(rs.getObject(i)); - if (n != null) - v_row.add(Var.alloc(rsmd.getColumnLabel(i)), n); - } - - if (virt_graph != null && !virt_graph.equals("virt:DEFAULT")) - v_row.add(Var.alloc("graph"), Node.createURI(virt_graph)); - } catch (Exception e) { - throw new JenaException("extractRow is FAILED.:" + e); - } - } - - protected void finalize() throws Throwable { - if (!v_finished) - try { - close(); - } catch (Exception e) { - } - } - - @Override - protected void requestCancel() { - // TODO Auto-generated method stub - - } - - } + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtuosoQueryEngine.class); + static QueryEngineFactory factory = new VirtQueryEngineFactory(); + private Query eQuery = null; + + public VirtuosoQueryEngine(Query query, DatasetGraph dataset, + Binding initial, Context context) { + super(query, dataset, initial, context); + eQuery = query; + } + + public VirtuosoQueryEngine(Query query, DatasetGraph dataset) { + this(query, dataset, null, null); + } + + static public QueryEngineFactory getFactory() { + return factory; + } + + static public void register() { + QueryEngineRegistry.addFactory(factory); + } + + static public void unregister() { + QueryEngineRegistry.removeFactory(factory); + } + + // ---- Registration of the factory for this query engine class. + + // Query engine factory. + // Call VirtQueryEngine.register() to add to the global query engine + // registry. + + @Override + public QueryIterator eval(Op op, DatasetGraph dsg, Binding initial, + Context context) { + // Extension point: access possible to all the parameters for execution. + // Be careful to deal with initial bindings. + Transform transform = new VirtTransform(); + Transformer.transform(transform, op); + + VirtGraph vg = (VirtGraph) dsg.getDefaultGraph(); + String query = fixQuery(eQuery.toString(), initial, vg); + + try { + java.sql.Statement stmt = vg.createStatement(); + java.sql.ResultSet rs = stmt.executeQuery(query); + return new VQueryIterator(vg, rs); + } catch (Exception e) { + throw new JenaException("Can not create QueryIterator.:" + e); + } + } + + private String substBindings(String query, Binding args) { + if (args == null) + return query; + + StringBuilder buf = new StringBuilder(); + String delim = " ,)(;."; + int i = 0; + char ch; + int qlen = query.length(); + while (i < qlen) { + ch = query.charAt(i++); + if (ch == '\\') { + buf.append(ch); + if (i < qlen) + buf.append(query.charAt(i++)); + + } else if (ch == '"' || ch == '\'') { + char end = ch; + buf.append(ch); + while (i < qlen) { + ch = query.charAt(i++); + buf.append(ch); + if (ch == end) + break; + } + } else if (ch == '?') { // Parameter + String varData = null; + int j = i; + while (j < qlen && delim.indexOf(query.charAt(j)) < 0) + j++; + if (j != i) { + String varName = query.substring(i, j); + Node val = args.get(Var.alloc(varName)); + if (val != null) { + varData = VirtUtilities.toString(val); + i = j; + } + } + if (varData != null) + buf.append(varData); + else + buf.append(ch); + } else { + buf.append(ch); + } + } + return buf.toString(); + } + + private String fixQuery(String query, Binding args, VirtGraph vg) { + StringBuilder sb = new StringBuilder("sparql\n "); + + if (vg.getRuleSet() != null) + sb.append(" define input:inference '").append(vg.getRuleSet()).append("'\n "); + + if (vg.getSameAs()) + sb.append(" define input:same-as \"yes\"\n "); + + if (!vg.getReadFromAllGraphs()) + sb.append(" define input:default-graph-uri <").append(vg.getGraphName()).append("> \n"); + + sb.append(substBindings(query, args)); + + return sb.toString(); + } + + @Override + protected Op modifyOp(Op op) { + // Extension point: possible place to alter the algebra expression. + // Alternative to eval(). + op = super.modifyOp(op); + return op; + } + + private static class VirtQueryEngineFactory implements QueryEngineFactory { + // Accept any dataset for query execution + @Override + public boolean accept(Query query, DatasetGraph dataset, Context context) { + return dataset instanceof VirtDataSource.VirtDataSetGraph || + dataset.getDefaultGraph() instanceof VirtGraph; + } + + @Override + public Plan create(Query query, DatasetGraph dataset, Binding initial, + Context context) { + if (!(dataset instanceof VirtDataSource.VirtDataSetGraph)) { + if (!(dataset.getDefaultGraph() instanceof VirtGraph)) + throw new ARQInternalErrorException( + "VirtQueryEngineFactory: only factory VirtuosoDatasetGraph is supported"); + } + // Create a query engine instance. + VirtuosoQueryEngine engine = new VirtuosoQueryEngine(query, + dataset, initial, context); + return engine.getPlan(); + } + + @Override + public boolean accept(Op op, DatasetGraph dataset, Context context) { + // Refuse to accept algebra expressions directly. + return false; + } + + @Override + public Plan create(Op op, DatasetGraph dataset, Binding inputBinding, + Context context) { // Shodul notbe called because acceept/Op is + // false + throw new ARQInternalErrorException( + "VirtQueryEngineFactory: factory calleddirectly with an algebra expression"); + } + } + + private class VirtTransform extends TransformCopy { + // Example, do nothing tranform. + @Override + public Op transform(OpBGP opBGP) { + return opBGP; + } + } + + protected class VQueryIterator extends QueryIteratorBase { + java.sql.ResultSetMetaData rsmd; + java.sql.ResultSet rs; + VirtGraph vg; + boolean v_finished = false; + boolean v_prefetched = false; + BindingMap v_row; + String virt_graph = null; + + protected VQueryIterator(VirtGraph _g, java.sql.ResultSet _rs) { + rs = _rs; + vg = _g; + virt_graph = vg.getGraphName(); + + try { + rsmd = rs.getMetaData(); + } catch (Exception e) { + throw new JenaException("VQueryIterator is FAILED.:" + e); + } + + } + + @Override + public void output(IndentedWriter out, SerializationContext sCxt) { + out.print(this.getClass().getName()); + } + + @Override + protected boolean hasNextBinding() { + if (!v_finished && !v_prefetched) + moveForward(); + return !v_finished; + } + + @Override + protected Binding moveToNextBinding() { + if (!v_finished && !v_prefetched) + moveForward(); + + v_prefetched = false; + + if (v_finished) + return null; + + return v_row; + } + + @Override + protected void closeIterator() { + if (!v_finished) { + if (rs != null) { + try { + rs.close(); + rs = null; + } catch (Exception ignored) { + } + } + } + v_finished = true; + } + + protected void moveForward() throws JenaException { + try { + if (!v_finished && rs.next()) { + extractRow(); + v_prefetched = true; + } else + closeIterator(); + } catch (Exception e) { + throw new JenaException("Convert results are FAILED.:" + e); + } + } + + protected void extractRow() throws Exception { + v_row = new BindingHashMap(); + + try { + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + Node n = VirtUtilities.toNode(rs.getObject(i)); + if (n != null) + v_row.add(Var.alloc(rsmd.getColumnLabel(i)), n); + } + + if (virt_graph != null && !virt_graph.equals("virt:DEFAULT")) + v_row.add(Var.alloc("graph"), NodeFactory.createURI(virt_graph)); + } catch (Exception e) { + throw new JenaException("extractRow is FAILED.:" + e); + } + } + + @Override + protected void finalize() throws Throwable { + if (!v_finished) + try { + super.finalize(); + close(); + } catch (Exception ignored) { + } + } + + @Override + protected void requestCancel() { + // TODO Auto-generated method stub + + } + + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecution.java b/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecution.java index 3b538b7..d7cc155 100644 --- a/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecution.java +++ b/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecution.java @@ -23,6 +23,24 @@ package virtuoso.jena.driver; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.graph.Triple; +import org.apache.jena.query.*; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.ModelFactory; +import org.apache.jena.rdf.model.Statement; +import org.apache.jena.shared.JenaException; +import org.apache.jena.sparql.core.Quad; +import org.apache.jena.sparql.core.ResultBinding; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.engine.binding.Binding; +import org.apache.jena.sparql.engine.binding.BindingHashMap; +import org.apache.jena.sparql.engine.binding.BindingMap; +import org.apache.jena.sparql.util.Context; +import org.apache.jena.sparql.util.ModelUtils; +import org.apache.jena.util.FileManager; + import java.sql.ResultSetMetaData; import java.util.Iterator; import java.util.LinkedList; @@ -30,408 +48,370 @@ import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; -import com.hp.hpl.jena.graph.Node; -import com.hp.hpl.jena.graph.Triple; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QuerySolution; -import com.hp.hpl.jena.query.ResultSet; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.rdf.model.ModelFactory; -import com.hp.hpl.jena.rdf.model.RDFNode; -import com.hp.hpl.jena.shared.JenaException; -import com.hp.hpl.jena.sparql.core.ResultBinding; -import com.hp.hpl.jena.sparql.core.Var; -import com.hp.hpl.jena.sparql.engine.binding.Binding; -import com.hp.hpl.jena.sparql.engine.binding.BindingHashMap; -import com.hp.hpl.jena.sparql.engine.binding.BindingMap; -import com.hp.hpl.jena.sparql.engine.iterator.QueryIterConcat; -import com.hp.hpl.jena.sparql.util.Context; -import com.hp.hpl.jena.sparql.util.ModelUtils; -import com.hp.hpl.jena.util.FileManager; - public class VirtuosoQueryExecution implements QueryExecution { - private QueryIterConcat output = null; - private String virt_graph = null; - private VirtGraph graph; - private String virt_query; - private QuerySolution m_arg = null; - - private java.sql.Statement stmt = null; - - public VirtuosoQueryExecution(String query, VirtGraph _graph) { - graph = _graph; - virt_graph = graph.getGraphName(); - virt_query = query; - } - - public ResultSet execSelect() { - ResultSet ret = null; - - try { - stmt = graph.createStatement(); - java.sql.ResultSet rs = stmt.executeQuery(getQueryString()); - - return new VResultSet(graph, rs); - } catch (Exception e) { - throw new JenaException("Can not create ResultSet.:" + e); - } - } - - public void setFileManager(FileManager arg) { - throw new JenaException("UnsupportedMethodException"); - } - - public void setInitialBinding(QuerySolution arg) { - m_arg = arg; - } - - public Dataset getDataset() { - return new VirtDataSource(graph); - } - - public Context getContext() { - return null; - } - - public Model execConstruct() { - return execConstruct(ModelFactory.createDefaultModel()); - } - - public Model execConstruct(Model model) { - try { - stmt = graph.createStatement(); - java.sql.ResultSet rs = stmt.executeQuery(getQueryString()); - ResultSetMetaData rsmd = rs.getMetaData(); - - while (rs.next()) { - Node s = VirtGraph.Object2Node(rs.getObject(1)); - Node p = VirtGraph.Object2Node(rs.getObject(2)); - Node o = VirtGraph.Object2Node(rs.getObject(3)); - com.hp.hpl.jena.rdf.model.Statement st = ModelUtils - .tripleToStatement(model, new Triple(s, p, o)); - if (st != null) - model.add(st); - } - rs.close(); - stmt.close(); - stmt = null; - - } catch (Exception e) { - throw new JenaException("Convert results are FAILED.:" + e); - } - return model; - } - - public Model execDescribe() { - return execDescribe(ModelFactory.createDefaultModel()); - } - - public Model execDescribe(Model model) { - try { - stmt = graph.createStatement(); - java.sql.ResultSet rs = stmt.executeQuery(getQueryString()); - ResultSetMetaData rsmd = rs.getMetaData(); - while (rs.next()) { - Node s = VirtGraph.Object2Node(rs.getObject(1)); - Node p = VirtGraph.Object2Node(rs.getObject(2)); - Node o = VirtGraph.Object2Node(rs.getObject(3)); - - com.hp.hpl.jena.rdf.model.Statement st = ModelUtils - .tripleToStatement(model, new Triple(s, p, o)); - if (st != null) - model.add(st); - } - rs.close(); - stmt.close(); - stmt = null; - - } catch (Exception e) { - throw new JenaException("Convert results are FAILED.:" + e); - } - return model; - } - - public boolean execAsk() { - boolean ret = false; - - try { - stmt = graph.createStatement(); - java.sql.ResultSet rs = stmt.executeQuery(getQueryString()); - ResultSetMetaData rsmd = rs.getMetaData(); - - while (rs.next()) { - if (rs.getInt(1) == 1) - ret = true; - } - rs.close(); - stmt.close(); - stmt = null; - - } catch (Exception e) { - throw new JenaException("Convert results are FAILED.:" + e); - } - return ret; - } - - public void abort() { - if (stmt != null) - try { - stmt.cancel(); - } catch (Exception e) { - } - } - - public void close() { - if (stmt != null) - try { - stmt.cancel(); - stmt.close(); - } catch (Exception e) { - } - } - - private String substBindings(String query) { - if (m_arg == null) - return query; - - StringBuffer buf = new StringBuffer(); - String delim = " ,)(;."; - int i = 0; - char ch; - int qlen = query.length(); - while (i < qlen) { - ch = query.charAt(i++); - if (ch == '\\') { - buf.append(ch); - if (i < qlen) - buf.append(query.charAt(i++)); - - } else if (ch == '"' || ch == '\'') { - char end = ch; - buf.append(ch); - while (i < qlen) { - ch = query.charAt(i++); - buf.append(ch); - if (ch == end) - break; - } - } else if (ch == '?') { // Parameter - String varData = null; - int j = i; - while (j < qlen && delim.indexOf(query.charAt(j)) < 0) - j++; - if (j != i) { - String varName = query.substring(i, j); - RDFNode val = m_arg.get(varName); - if (val != null) { - varData = VirtGraph.Node2Str(val.asNode()); - i = j; - } - } - if (varData != null) - buf.append(varData); - else - buf.append(ch); - } else { - buf.append(ch); - } - } - return buf.toString(); - } - - private String getQueryString() { - StringBuffer sb = new StringBuffer("sparql\n "); - - if (graph.getRuleSet() != null) - sb.append(" define input:inference '" + graph.getRuleSet() + "'\n"); - - if (graph.getSameAs()) - sb.append(" define input:same-as \"yes\"\n"); - - if (!graph.getReadFromAllGraphs()) - sb.append(" define input:default-graph-uri <" - + graph.getGraphName() + "> \n"); - - sb.append(substBindings(virt_query)); - - return sb.toString(); - } - - // /=== Inner class =========================================== - public class VResultSet implements com.hp.hpl.jena.query.ResultSet { - ResultSetMetaData rsmd; - java.sql.ResultSet rs; - boolean v_finished = false; - boolean v_prefetched = false; - VirtModel m; - BindingMap v_row; - List resVars = new LinkedList(); - int row_id = 0; - - protected VResultSet(VirtGraph _g, java.sql.ResultSet _rs) { - rs = _rs; - m = new VirtModel(_g); - - try { - rsmd = rs.getMetaData(); - for (int i = 1; i <= rsmd.getColumnCount(); i++) - resVars.add(rsmd.getColumnLabel(i)); - - if (virt_graph != null && !virt_graph.equals("virt:DEFAULT")) - resVars.add("graph"); - } catch (Exception e) { - throw new JenaException( - "ViruosoResultBindingsToJenaResults is FAILED.:" + e); - } - } - - public boolean hasNext() { - if (!v_finished && !v_prefetched) - moveForward(); - return !v_finished; - } - - public QuerySolution next() { - Binding binding = nextBinding(); - - if (v_finished) - throw new NoSuchElementException(); - - return new ResultBinding(m, binding); - } - - public QuerySolution nextSolution() { - return next(); - } - - public Binding nextBinding() { - if (!v_finished && !v_prefetched) - moveForward(); - - v_prefetched = false; - - if (v_finished) - throw new NoSuchElementException(); - - return v_row; - } - - public int getRowNumber() { - return row_id; - } - - public List getResultVars() { - return resVars; - } - - public Model getResourceModel() { - return m; - } - - protected void finalize() throws Throwable { - if (!v_finished) - try { - close(); - } catch (Exception e) { - } - } - - protected void moveForward() throws JenaException { - try { - if (!v_finished && rs.next()) { - extractRow(); - v_prefetched = true; - } else - close(); - } catch (Exception e) { - throw new JenaException("Convert results are FAILED.:" + e); - } - } - - protected void extractRow() throws Exception { - v_row = new BindingHashMap(); - row_id++; - - try { - for (int i = 1; i <= rsmd.getColumnCount(); i++) { - Node n = VirtGraph.Object2Node(rs.getObject(i)); - if (n != null) - v_row.add(Var.alloc(rsmd.getColumnLabel(i)), n); - } - - if (virt_graph != null && !virt_graph.equals("virt:DEFAULT")) - v_row.add(Var.alloc("graph"), Node.createURI(virt_graph)); - } catch (Exception e) { - throw new JenaException( - "ViruosoResultBindingsToJenaResults is FAILED.:" + e); - } - } - - public void remove() throws java.lang.UnsupportedOperationException { - throw new UnsupportedOperationException(this.getClass().getName() - + ".remove"); - } - - private void close() { - if (!v_finished) { - if (rs != null) { - try { - rs.close(); - rs = null; - } catch (Exception e) { - } - } - } - v_finished = true; - } - - } - - public Iterator execConstructTriples() { - // TODO Auto-generated method stub - return null; - } - - public Iterator execDescribeTriples() { - // TODO Auto-generated method stub - return null; - } - - public Query getQuery() { - // TODO Auto-generated method stub - return null; - } - - public void setTimeout(long arg0) { - // TODO Auto-generated method stub - - } - - public void setTimeout(long arg0, TimeUnit arg1) { - // TODO Auto-generated method stub - - } - - public void setTimeout(long arg0, long arg1) { - // TODO Auto-generated method stub - - } - - public void setTimeout(long arg0, TimeUnit arg1, long arg2, TimeUnit arg3) { - // TODO Auto-generated method stub - - } - - public long getTimeout1() { - // TODO Auto-generated method stub - return 0; - } - - public long getTimeout2() { - // TODO Auto-generated method stub - return 0; - } + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtuosoQueryExecution.class); + + private String virt_graph = null; + private final VirtGraph graph; + private final String virt_query; + private QuerySolution m_arg = null; + + private java.sql.Statement stmt = null; + + public VirtuosoQueryExecution(String query, VirtGraph _graph) { + graph = _graph; + virt_graph = graph.getGraphName(); + virt_query = query; + } + + @Override + public ResultSet execSelect() { + try { + stmt = graph.createStatement(); + java.sql.ResultSet rs = stmt.executeQuery(getQueryString()); + return new VResultSet(graph, rs); + } catch (Exception e) { + throw new JenaException("Can not create ResultSet.:" + e); + } + } + + public void setFileManager(FileManager arg) { + throw new JenaException("UnsupportedMethodException"); + } + + @Override + public void setInitialBinding(QuerySolution arg) { + m_arg = arg; + } + + @Override + public Dataset getDataset() { + return new VirtDataSource(graph); + } + + @Override + public Context getContext() { + return null; + } + + @Override + public Model execConstruct() { + return execConstruct(ModelFactory.createDefaultModel()); + } + + @Override + public Model execConstruct(Model model) { + return execQuerySparql(model); + } + + @Override + public Model execDescribe() { + return execDescribe(ModelFactory.createDefaultModel()); + } + + @Override + public Model execDescribe(Model model) { + return execQuerySparql(model); + } + + @Override + public boolean execAsk() { + boolean ret = false; + + try { + stmt = graph.createStatement(); + try (java.sql.ResultSet rs = stmt.executeQuery(getQueryString())) { + ResultSetMetaData rsmd = rs.getMetaData(); + + while (rs.next()) { + if (rs.getInt(1) == 1) + ret = true; + } + } + stmt.close(); + stmt = null; + + } catch (Exception e) { + throw new JenaException("Convert results are FAILED.:" + e); + } + return ret; + } + + private Model execQuerySparql(Model model) { + try { + stmt = graph.createStatement(); + try (java.sql.ResultSet rs = stmt.executeQuery(getQueryString())) { + ResultSetMetaData rsmd = rs.getMetaData(); + while (rs.next()) { + Node s = VirtUtilities.toNode(rs.getObject(1)); + Node p = VirtUtilities.toNode(rs.getObject(2)); + Node o = VirtUtilities.toNode(rs.getObject(3)); + + Statement st = ModelUtils + .tripleToStatement(model, new Triple(s, p, o)); + if (st != null) + model.add(st); + } + } + stmt.close(); + stmt = null; + } catch (Exception e) { + throw new JenaException("Convert results are FAILED.:" + e); + } + return model; + } + + @Override + public void abort() { + if (stmt != null) + try { + stmt.cancel(); + } catch (Exception ignored) { + } + } + + @Override + public void close() { + if (stmt != null) + try { + stmt.cancel(); + stmt.close(); + } catch (Exception ignored) { + } + } + + @Override + public boolean isClosed() { + return false; + } + + private String getQueryString() { + StringBuilder sb = new StringBuilder("sparql\n "); + + if (graph.getRuleSet() != null) + sb.append(" define input:inference '").append(graph.getRuleSet()).append("'\n"); + + if (graph.getSameAs()) + sb.append(" define input:same-as \"yes\"\n"); + + if (!graph.getReadFromAllGraphs()) + sb.append(" define input:default-graph-uri <").append(graph.getGraphName()).append("> \n"); + + sb.append(VirtUtilities.substituteBindings(virt_query,m_arg)); + + return sb.toString(); + } + + // /=== Inner class =========================================== + public class VResultSet implements ResultSet { + ResultSetMetaData rsmd; + java.sql.ResultSet rs; + boolean v_finished = false; + boolean v_prefetched = false; + VirtModel m; + BindingMap v_row; + List resVars = new LinkedList<>(); + int row_id = 0; + + protected VResultSet(VirtGraph _g, java.sql.ResultSet _rs) { + rs = _rs; + m = new VirtModel(_g); + + try { + rsmd = rs.getMetaData(); + for (int i = 1; i <= rsmd.getColumnCount(); i++) + resVars.add(rsmd.getColumnLabel(i)); + + if (virt_graph != null && !virt_graph.equals("virt:DEFAULT")) + resVars.add("graph"); + } catch (Exception e) { + throw new JenaException( + "ViruosoResultBindingsToJenaResults is FAILED.:" + e); + } + } + + @Override + public boolean hasNext() { + if (!v_finished && !v_prefetched) + moveForward(); + return !v_finished; + } + + @Override + public QuerySolution next() { + Binding binding = nextBinding(); + + if (v_finished) + throw new NoSuchElementException(); + + return new ResultBinding(m, binding); + } + + @Override + public QuerySolution nextSolution() { + return next(); + } + + @Override + public Binding nextBinding() { + if (!v_finished && !v_prefetched) + moveForward(); + + v_prefetched = false; + + if (v_finished) + throw new NoSuchElementException(); + + return v_row; + } + + @Override + public int getRowNumber() { + return row_id; + } + + @Override + public List getResultVars() { + return resVars; + } + + @Override + public Model getResourceModel() { + return m; + } + + @Override + protected void finalize() throws Throwable { + if (!v_finished) + try { + super.finalize(); + close(); + } catch (Exception ignored) { + logger.error(ignored.getMessage(), ignored); + } + } + + protected void moveForward() throws JenaException { + try { + if (!v_finished && rs.next()) { + extractRow(); + v_prefetched = true; + } else + close(); + } catch (Exception e) { + throw new JenaException("Convert results are FAILED.:" + e); + } + } + + protected void extractRow() throws Exception { + v_row = new BindingHashMap(); + row_id++; + + try { + for (int i = 1; i <= rsmd.getColumnCount(); i++) { + Node n = VirtUtilities.toNode(rs.getObject(i)); + if (n != null) + v_row.add(Var.alloc(rsmd.getColumnLabel(i)), n); + } + + if (virt_graph != null && !virt_graph.equals("virt:DEFAULT")) + v_row.add(Var.alloc("graph"), NodeFactory.createURI(virt_graph)); + } catch (Exception e) { + throw new JenaException( + "ViruosoResultBindingsToJenaResults is FAILED.:" + e); + } + } + + @Override + public void remove() throws java.lang.UnsupportedOperationException { + throw new UnsupportedOperationException(this.getClass().getName() + + ".remove"); + } + + private void close() { + if (!v_finished) { + if (rs != null) { + try { + rs.close(); + rs = null; + } catch (Exception ignored) { + } + } + } + v_finished = true; + } + + } + + @Override + public Iterator execConstructTriples() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Iterator execConstructQuads() { + return null; + } + + @Override + public Dataset execConstructDataset() { + return null; + } + + @Override + public Dataset execConstructDataset(Dataset dataset) { + return null; + } + + @Override + public Iterator execDescribeTriples() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Query getQuery() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setTimeout(long arg0) { + // TODO Auto-generated method stub + + } + + @Override + public void setTimeout(long arg0, TimeUnit arg1) { + // TODO Auto-generated method stub + + } + + @Override + public void setTimeout(long arg0, long arg1) { + // TODO Auto-generated method stub + + } + + @Override + public void setTimeout(long arg0, TimeUnit arg1, long arg2, TimeUnit arg3) { + // TODO Auto-generated method stub + + } + + @Override + public long getTimeout1() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public long getTimeout2() { + // TODO Auto-generated method stub + return 0; + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecutionFactory.java b/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecutionFactory.java index e7a9ce7..57458af 100644 --- a/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecutionFactory.java +++ b/src/main/java/virtuoso/jena/driver/VirtuosoQueryExecutionFactory.java @@ -25,204 +25,208 @@ import java.util.List; -import com.hp.hpl.jena.query.Dataset; -import com.hp.hpl.jena.query.Query; -import com.hp.hpl.jena.query.QueryExecution; -import com.hp.hpl.jena.query.QueryFactory; -import com.hp.hpl.jena.query.QuerySolution; -import com.hp.hpl.jena.rdf.model.Model; -import com.hp.hpl.jena.sparql.core.DatasetImpl; -import com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP; -import com.hp.hpl.jena.sparql.util.Context; -import com.hp.hpl.jena.util.FileManager; +import org.apache.jena.query.*; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.sparql.core.DatasetImpl; +import org.apache.jena.sparql.engine.http.QueryEngineHTTP; +import org.apache.jena.sparql.util.Context; +import org.apache.jena.util.FileManager; public class VirtuosoQueryExecutionFactory { - private VirtuosoQueryExecutionFactory() { - } + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtuosoQueryExecutionFactory.class); - static public VirtuosoQueryExecution create(Query query, VirtGraph graph) { - VirtuosoQueryExecution ret = new VirtuosoQueryExecution( - query.toString(), graph); - return ret; - } - static public VirtuosoQueryExecution create(String query, VirtGraph graph) { - VirtuosoQueryExecution ret = new VirtuosoQueryExecution(query, graph); - return ret; - } + private VirtuosoQueryExecutionFactory() { + } - /* TODO */ - - static public QueryExecution create(Query query, Dataset dataset) { - if (dataset instanceof VirtDataSource) { - VirtuosoQueryExecution ret = new VirtuosoQueryExecution( - query.toString(), (VirtGraph) dataset); - return ret; - } else { - return make(query, dataset); - } - } - - static public QueryExecution create(String queryStr, Dataset dataset) { - if (dataset instanceof VirtDataSource) { - VirtuosoQueryExecution ret = new VirtuosoQueryExecution(queryStr, - (VirtGraph) dataset); - return ret; - } else { - return make(makeQuery(queryStr), dataset); - } - } - - static public QueryExecution create(Query query, FileManager fm) { - checkArg(query); - QueryExecution qe = make(query); - if (fm != null) - qe.setFileManager(fm); - return qe; - } - - static public QueryExecution create(String queryStr, FileManager fm) { - checkArg(queryStr); - return create(makeQuery(queryStr), fm); - } + static public VirtuosoQueryExecution create(Query query, VirtGraph graph) { + return new VirtuosoQueryExecution( + query.toString(), graph); + } - // ---------------- Query + Model + static public VirtuosoQueryExecution create(String query, VirtGraph graph) { + return new VirtuosoQueryExecution(query, graph); + } - static public QueryExecution create(Query query, Model model) { - checkArg(query); - checkArg(model); - - if (model.getGraph() instanceof VirtGraph) { - VirtuosoQueryExecution ret = new VirtuosoQueryExecution( - query.toString(), (VirtGraph) model.getGraph()); - return ret; - } else { - return make(query, new DatasetImpl(model)); - } - } - - static public QueryExecution create(String queryStr, Model model) { - checkArg(queryStr); - checkArg(model); - if (model.getGraph() instanceof VirtGraph) { - VirtuosoQueryExecution ret = new VirtuosoQueryExecution(queryStr, - (VirtGraph) model.getGraph()); - return ret; - } else { - return create(makeQuery(queryStr), model); - } - } + /* TODO */ - static public QueryExecution create(Query query, - QuerySolution initialBinding) { - checkArg(query); + static public QueryExecution create(Query query, Dataset dataset) { + if (dataset instanceof VirtDataSource) { + return new VirtuosoQueryExecution( + query.toString(), (VirtGraph) dataset); + } else { + return make(query, dataset); + } + } + + static public QueryExecution create(String queryStr, Dataset dataset) { + if (dataset instanceof VirtDataSource) { + return new VirtuosoQueryExecution(queryStr, + (VirtGraph) dataset); + } else { + return make(VirtUtilities.toQuery(queryStr), dataset); + } + } + + /*static public QueryExecution create(Query query, FileManager fm) { + checkArg(query); QueryExecution qe = make(query); - if (initialBinding != null) - qe.setInitialBinding(initialBinding); - return qe; - } - - static public QueryExecution create(String queryStr, - QuerySolution initialBinding) { - checkArg(queryStr); - return create(makeQuery(queryStr), initialBinding); - } - - // ?? - static public QueryExecution create(Query query, Dataset dataset, - QuerySolution initialBinding) { - checkArg(query); - QueryExecution qe = make(query, dataset); - if (initialBinding != null) - qe.setInitialBinding(initialBinding); + if (fm != null){ + qe.setFileManager(fm); + } return qe; - } + }*/ - // ?? - static public QueryExecution create(String queryStr, Dataset dataset, - QuerySolution initialBinding) { + /*static public QueryExecution create(String queryStr, FileManager fm) { checkArg(queryStr); - return create(makeQuery(queryStr), dataset, initialBinding); - } - - // ---------------- Remote query execution - - static public QueryExecution sparqlService(String service, Query query) { - checkNotNull(service, "URL for service is null"); - checkArg(query); - return makeServiceRequest(service, query); - } - - static public QueryExecution sparqlService(String service, Query query, - String defaultGraph) { - checkNotNull(service, "URL for service is null"); - // checkNotNull(defaultGraph, "IRI for default graph is null") ; - checkArg(query); - QueryEngineHTTP qe = makeServiceRequest(service, query); - qe.addDefaultGraph(defaultGraph); - return qe; - } - - static public QueryExecution sparqlService(String service, Query query, - List defaultGraphURIs, List namedGraphURIs) { - checkNotNull(service, "URL for service is null"); - // checkNotNull(defaultGraphURIs, "List of default graph URIs is null") - // ; - // checkNotNull(namedGraphURIs, "List of named graph URIs is null") ; - checkArg(query); - - QueryEngineHTTP qe = makeServiceRequest(service, query); - - if (defaultGraphURIs != null) - qe.setDefaultGraphURIs(defaultGraphURIs); - if (namedGraphURIs != null) - qe.setNamedGraphURIs(namedGraphURIs); - return qe; - } - - // ---------------- Internal routines - - // Make query - - static private Query makeQuery(String queryStr) { - return QueryFactory.create(queryStr); - } - - // ---- Make executions - - static private QueryExecution make(Query query) { - return make(query, null); - } - - static private QueryExecution make(Query query, Dataset dataset) { - return make(query, dataset, null); - } - - static private QueryExecution make(Query query, Dataset dataset, - Context context) { - return null; - } - - static private QueryEngineHTTP makeServiceRequest(String service, - Query query) { - return new QueryEngineHTTP(service, query); - } - - static private void checkNotNull(Object obj, String msg) { - if (obj == null) - throw new IllegalArgumentException(msg); - } - - static private void checkArg(Model model) { - checkNotNull(model, "Model is a null pointer"); - } - - static private void checkArg(String queryStr) { - checkNotNull(queryStr, "Query string is null"); - } - - static private void checkArg(Query query) { - checkNotNull(query, "Query is null"); - } + return create(VirtUtilities.toQuery(queryStr), fm); + }*/ + + // ---------------- Query + Model + + static public QueryExecution create(Query query, Model model) { + checkArg(query); + checkArg(model); + + if (model.getGraph() instanceof VirtGraph) { + return new VirtuosoQueryExecution( + query.toString(), (VirtGraph) model.getGraph()); + } else { + return make(query, new DatasetImpl(model)); + } + } + + static public QueryExecution create(String queryStr, Model model) { + checkArg(queryStr); + checkArg(model); + if (model.getGraph() instanceof VirtGraph) { + return new VirtuosoQueryExecution(queryStr, + (VirtGraph) model.getGraph()); + } else { + return create(VirtUtilities.toQuery(queryStr), model); + } + } + + static public QueryExecution create(Query query, + QuerySolution initialBinding) { + checkArg(query); + QueryExecution qe = make(query); + if (initialBinding != null) + qe.setInitialBinding(initialBinding); + return qe; + } + + static public QueryExecution create(String queryStr, + QuerySolution initialBinding) { + checkArg(queryStr); + return create(VirtUtilities.toQuery(queryStr), initialBinding); + } + + // ?? + static public QueryExecution create(Query query, Dataset dataset, + QuerySolution initialBinding) { + checkArg(query); + QueryExecution qe = make(query, dataset); + if (initialBinding != null) + qe.setInitialBinding(initialBinding); + return qe; + } + + // ?? + static public QueryExecution create(String queryStr, Dataset dataset, + QuerySolution initialBinding) { + checkArg(queryStr); + return create(VirtUtilities.toQuery(queryStr), dataset, initialBinding); + } + + // ---------------- Remote query execution + + static public QueryExecution sparqlService(String service, Query query) { + checkNotNull(service, "URL for service is null"); + checkArg(query); + return makeServiceRequest(service, query); + } + + static public QueryExecution sparqlService(String service, String query) { + checkNotNull(service, "URL for service is null"); + checkArg(query); + return makeServiceRequest(service, query); + } + + static public QueryExecution sparqlService(String service, Query query, + String defaultGraph) { + checkNotNull(service, "URL for service is null"); + // checkNotNull(defaultGraph, "IRI for default graph is null") ; + checkArg(query); + QueryEngineHTTP qe = makeServiceRequest(service, query); + qe.addDefaultGraph(defaultGraph); + return qe; + } + + static public QueryExecution sparqlService(String service, Query query, + List defaultGraphURIs, List namedGraphURIs) { + checkNotNull(service, "URL for service is null"); + // checkNotNull(defaultGraphURIs, "List of default graph URIs is null") + // ; + // checkNotNull(namedGraphURIs, "List of named graph URIs is null") ; + checkArg(query); + + QueryEngineHTTP qe = makeServiceRequest(service, query); + + if (defaultGraphURIs != null) + qe.setDefaultGraphURIs(defaultGraphURIs); + if (namedGraphURIs != null) + qe.setNamedGraphURIs(namedGraphURIs); + return qe; + } + + // ---------------- Internal routines + + // ---- Make executions + + static private QueryExecution make(Query query) { + return make(query, null); + } + + static private QueryExecution make(Query query, Dataset dataset) { + return make(query, dataset, null); + } + + static private QueryExecution make(Query query, Dataset dataset, + Context context) { + if (dataset != null) { + return QueryExecutionFactory.create(query, dataset); + } else { + return QueryExecutionFactory.create(query); + } + } + + static private QueryEngineHTTP makeServiceRequest(String service, + Query query) { + return new QueryEngineHTTP(service, query); + } + + static private QueryEngineHTTP makeServiceRequest(String service, + String query) { + return new QueryEngineHTTP(service, query); + } + + static private void checkNotNull(Object obj, String msg) { + if (obj == null) + throw new IllegalArgumentException(msg); + } + + static private void checkArg(Model model) { + checkNotNull(model, "Model is a null pointer"); + } + + static private void checkArg(String queryStr) { + checkNotNull(queryStr, "Query string is null"); + } + + static private void checkArg(Query query) { + checkNotNull(query, "Query is null"); + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtuosoUpdateFactory.java b/src/main/java/virtuoso/jena/driver/VirtuosoUpdateFactory.java index 963cb92..89202f8 100644 --- a/src/main/java/virtuoso/jena/driver/VirtuosoUpdateFactory.java +++ b/src/main/java/virtuoso/jena/driver/VirtuosoUpdateFactory.java @@ -28,48 +28,57 @@ import java.io.InputStream; import java.io.Reader; -import com.hp.hpl.jena.update.UpdateException; -import com.hp.hpl.jena.util.FileUtils; +import org.apache.jena.update.UpdateException; +import org.apache.jena.util.FileUtils; public class VirtuosoUpdateFactory { - private VirtuosoUpdateFactory() { - } + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtuosoUpdateFactory.class); - /** Create an UpdateRequest by parsing the given string */ - static public VirtuosoUpdateRequest create(String query, VirtGraph graph) { - return new VirtuosoUpdateRequest(query, graph); - } + private VirtuosoUpdateFactory() { + } - /** Create an UpdateRequest by reading it from a file */ - public static VirtuosoUpdateRequest read(String fileName, VirtGraph graph) { - InputStream in = null; - if (fileName.equals("-")) - in = System.in; - else - try { - in = new FileInputStream(fileName); - } catch (FileNotFoundException ex) { - throw new UpdateException("File nout found: " + fileName); - } - return read(in, graph); - } + /** + * Create an UpdateRequest by parsing the given string * + * + * @param fileName the {@link String} to the File path. + * @param graph the {@link VirtGraph} the Graph jena. + * @return the {@link VirtuosoUpdateRequest} + */ + public static VirtuosoUpdateRequest read(String fileName, VirtGraph graph) { + InputStream in; + if (fileName.equals("-")) + in = System.in; + else + try { + in = new FileInputStream(fileName); + } catch (FileNotFoundException ex) { + throw new UpdateException("File nout found: " + fileName); + } + return read(in, graph); + } - /** - * Create an UpdateRequest by reading it from an InputStream (note that - * conversion to UTF-8 will be applied automatically) - */ - public static VirtuosoUpdateRequest read(InputStream in, VirtGraph graph) { - Reader r = FileUtils.asBufferedUTF8(in); - StringBuffer b = new StringBuffer(); - char ch; - try { - while ((ch = (char) r.read()) != -1) - b.append(ch); - } catch (Exception e) { - throw new UpdateException(e); - } - return new VirtuosoUpdateRequest(b.toString(), graph); - } + /** + * Create an UpdateRequest by reading it from an InputStream (note that + * conversion to UTF-8 will be applied automatically) + * + * @param in the {@link InputStream} to Stream of the File. + * @param graph the {@link VirtGraph} the Graph jena. + * @return the {@link VirtuosoUpdateRequest} + */ + public static VirtuosoUpdateRequest read(InputStream in, VirtGraph graph) { + Reader r = FileUtils.asBufferedUTF8(in); + StringBuilder b = new StringBuilder(); + char ch; + try { + //noinspection ConstantConditions + while ((ch = (char) r.read()) != -1) + b.append(ch); + } catch (Exception e) { + throw new UpdateException(e); + } + return new VirtuosoUpdateRequest(b.toString(), graph); + } } diff --git a/src/main/java/virtuoso/jena/driver/VirtuosoUpdateRequest.java b/src/main/java/virtuoso/jena/driver/VirtuosoUpdateRequest.java index d64498f..492e4c5 100644 --- a/src/main/java/virtuoso/jena/driver/VirtuosoUpdateRequest.java +++ b/src/main/java/virtuoso/jena/driver/VirtuosoUpdateRequest.java @@ -28,74 +28,78 @@ import java.util.List; import org.apache.jena.atlas.io.IndentedWriter; - -import com.hp.hpl.jena.update.UpdateException; +import org.apache.jena.update.UpdateException; public class VirtuosoUpdateRequest { - private List requests = new ArrayList(); - private VirtGraph graph; - private String virt_query; - - java.sql.Statement stmt = null; - - public VirtuosoUpdateRequest(VirtGraph _graph) { - graph = _graph; - } - - public VirtuosoUpdateRequest(String query, VirtGraph _graph) { - this(_graph); - virt_query = query; - requests.add((Object) query); - } - - public void exec() { - try { - stmt = graph.createStatement(); - - for (Iterator iter = requests.iterator(); iter.hasNext();) { - String query = "sparql\n " + (String) iter.next(); - stmt.execute(query); - } - - stmt.close(); - stmt = null; - } catch (Exception e) { - throw new UpdateException("Convert results are FAILED.:", e); - } - - } - - public void addUpdate(String update) { - requests.add(update); - } - - public Iterator iterator() { - return requests.iterator(); - } - - public String toString() { - StringBuffer b = new StringBuffer(); - - for (Iterator iter = requests.iterator(); iter.hasNext();) { - b.append((String) iter.next()); - b.append("\n"); - } - return b.toString(); - } - - public void output(IndentedWriter out) { - boolean first = true; - out.println(); - - for (Iterator iter = requests.iterator(); iter.hasNext();) { - if (!first) - out.println(" # ----------------"); - else - first = false; - System.out.println((String) iter.next()); - out.ensureStartOfLine(); - } - - } + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(VirtuosoUpdateRequest.class); + + private List requests = new ArrayList<>(); + private VirtGraph graph; + private String virt_query; + + java.sql.Statement stmt = null; + + public VirtuosoUpdateRequest(VirtGraph _graph) { + graph = _graph; + } + + public VirtuosoUpdateRequest(String query, VirtGraph _graph) { + this(_graph); + virt_query = query; + requests.add(query); + } + + public void exec() { + try { + stmt = graph.createStatement(); + + for (Object request : requests) { + String query = "sparql\n " + String.valueOf(request); + stmt.execute(query); + } + + stmt.close(); + stmt = null; + } catch (Exception e) { + throw new UpdateException("Convert results are FAILED.:", e); + } + + } + + public void addUpdate(String update) { + requests.add(update); + } + + public Iterator iterator() { + return requests.iterator(); + } + + @Override + public String toString() { + StringBuilder b = new StringBuilder(); + + for (Object request : requests) { + b.append((String) request); + b.append("\n"); + } + return b.toString(); + } + + public void output(IndentedWriter out) { + boolean first = true; + out.println(); + + for (Object request : requests) { + if (!first) + out.println(" # ----------------"); + else + first = false; + System.out.println((String) request); + out.ensureStartOfLine(); + } + + } }