You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@rya.apache.org by pu...@apache.org on 2018/03/09 18:20:47 UTC

[01/22] incubator-rya git commit: RYA-446 Daemonifying Query Manager

Repository: incubator-rya
Updated Branches:
  refs/heads/master b5a0164f0 -> 770bd7e4a


RYA-446 Daemonifying Query Manager


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/5b489dc0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/5b489dc0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/5b489dc0

Branch: refs/heads/master
Commit: 5b489dc0b6fb95ee9cd738cf2536c959ff09171e
Parents: b5a0164
Author: Andrew Smith <sm...@gmail.com>
Authored: Tue Jan 16 12:39:34 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:32 2018 -0500

----------------------------------------------------------------------
 extras/rya.streams/pom.xml                      |  1 +
 extras/rya.streams/query-manager/pom.xml        | 74 ++++++++++++++++++++
 .../querymanager/QueryManagerDaemon.java        | 49 +++++++++++++
 pom.xml                                         |  5 ++
 4 files changed, 129 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/5b489dc0/extras/rya.streams/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/pom.xml b/extras/rya.streams/pom.xml
index 51c7cd8..810af54 100644
--- a/extras/rya.streams/pom.xml
+++ b/extras/rya.streams/pom.xml
@@ -39,6 +39,7 @@
         <module>api</module>
         <module>client</module>
         <module>integration</module>
+        <module>query-manager</module>
     </modules>
     
     <profiles>

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/5b489dc0/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
new file mode 100644
index 0000000..3a13c6a
--- /dev/null
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+    <parent>
+        <groupId>org.apache.rya</groupId>
+        <artifactId>rya.streams.parent</artifactId>
+        <version>3.2.12-incubating-SNAPSHOT</version>
+    </parent>
+    
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>rya.streams.query-manager</artifactId>
+    
+    <name>Apache Rya Streams Query Manager</name>
+    <description>
+        This module contains the Rya Streams Query Manager.
+    </description>
+
+    <dependencies>
+        <!-- Rya dependencies -->
+        <dependency>
+            <groupId>org.apache.rya</groupId>
+            <artifactId>rya.streams.client</artifactId>
+        </dependency>
+
+        <!-- Apache Daemon dependencies -->
+        <dependency>
+            <groupId>commons-daemon</groupId>
+            <artifactId>commons-daemon</artifactId>
+            <version>1.1.0</version>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                          <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <transformers>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+                                    <mainClass>org.apache.rya.streams.querymanager.QueryManagerDaemon</mainClass>
+                                </transformer>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
+                            </transformers>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+     </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/5b489dc0/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
new file mode 100644
index 0000000..2ab0ad8
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import org.apache.commons.daemon.Daemon;
+import org.apache.commons.daemon.DaemonContext;
+import org.apache.commons.daemon.DaemonInitException;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+@DefaultAnnotation(NonNull.class)
+public class QueryManagerDaemon implements Daemon {
+    @Override
+    public void init(final DaemonContext context) throws DaemonInitException, Exception {
+        System.out.println("Initializing Query Manager Daemon.");
+    }
+
+    @Override
+    public void start() throws Exception {
+        System.out.println("Starting Query Manager Daemon.");
+    }
+
+    @Override
+    public void stop() throws Exception {
+        System.out.println("Stopping Query Manager Daemon.");
+    }
+
+    @Override
+    public void destroy() {
+        System.out.println("Query Manager Daemon Destroyed.");
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/5b489dc0/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 406bf20..532324a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -404,6 +404,11 @@ under the License.
             </dependency>
             <dependency>
                 <groupId>org.apache.rya</groupId>
+                <artifactId>rya.streams.client</artifactId>
+                <version>${project.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.rya</groupId>
                 <artifactId>rya.streams.kafka</artifactId>
                 <version>${project.version}</version>
             </dependency>


[06/22] incubator-rya git commit: RYA-448 Implement JAXB marshalling code for the Query Manager's XML configuration file.

Posted by pu...@apache.org.
RYA-448 Implement JAXB marshalling code for the Query Manager's XML configuration file.



Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/c1ccde80
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/c1ccde80
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/c1ccde80

Branch: refs/heads/master
Commit: c1ccde80bbd898f6051da8bdedacac3c53e14539
Parents: 9e8a27c
Author: kchilton2 <ke...@gmail.com>
Authored: Tue Jan 23 15:50:17 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:41 2018 -0500

----------------------------------------------------------------------
 extras/rya.streams/query-manager/pom.xml        | 52 ++++++++++++-
 .../query-manager/src/license/header.txt        | 16 ++++
 .../src/main/config/configuration.xml           | 51 ++++++++++++
 .../xml/QueryManagerConfigUnmarshaller.java     | 78 +++++++++++++++++++
 .../src/main/xsd/QueryManagerConfig.xsd         | 81 ++++++++++++++++++++
 .../xml/QueryManagerConfigMarshallerTest.java   | 78 +++++++++++++++++++
 6 files changed, 355 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/c1ccde80/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
index 3a13c6a..76e521d 100644
--- a/extras/rya.streams/query-manager/pom.xml
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -48,7 +48,57 @@ under the License.
         </dependency>
     </dependencies>
     <build>
+        <!-- Add the XSD directory as a resource so that it will be packaged in the jar. 
+           - Required so that the marshalling code is able to find the schema it is 
+           - validating XML against. -->
+        <resources>
+            <resource>
+                <directory>src/main/xsd</directory>
+            </resource>
+        </resources>
+    
         <plugins>
+            <!-- Generate the XML marshalling java code from the XSD file defining its structure. -->
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>jaxb2-maven-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>xjc</id>
+                        <goals>
+                            <goal>xjc</goal>
+                        </goals>
+                    </execution>
+                </executions>
+                <configuration>
+                    <packageName>org.apache.rya.streams.querymanager.xml</packageName>
+                </configuration>
+            </plugin>
+         
+            <!-- Ensure the generated java source contains the lisence header. -->   
+            <plugin>
+                <groupId>com.mycila</groupId>
+                <artifactId>license-maven-plugin</artifactId>
+                <configuration>
+                    <header>${project.basedir}/src/license/header.txt</header>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>update-generated-source-headers</id>
+                        <configuration>
+                            <basedir>${project.build.directory}/generated-sources/jaxb</basedir>
+                            <mapping>
+                                <sun-jaxb.episode>XML_STYLE</sun-jaxb.episode>
+                            </mapping>
+                        </configuration>
+                        <phase>process-sources</phase>
+                        <goals>
+                            <goal>format</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-shade-plugin</artifactId>
@@ -71,4 +121,4 @@ under the License.
             </plugin>
         </plugins>
      </build>
-</project>
+</project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/c1ccde80/extras/rya.streams/query-manager/src/license/header.txt
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/license/header.txt b/extras/rya.streams/query-manager/src/license/header.txt
new file mode 100644
index 0000000..90705e0
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/license/header.txt
@@ -0,0 +1,16 @@
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/c1ccde80/extras/rya.streams/query-manager/src/main/config/configuration.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/config/configuration.xml b/extras/rya.streams/query-manager/src/main/config/configuration.xml
new file mode 100644
index 0000000..b78900e
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/config/configuration.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<queryManagerConfig>
+    <!-- A list of Query Change Log Sources. A source needs to be defined for
+       - every system that is used to manage Rya Streams Query Change Logs.
+       - The query manager will manage queries for all Rya instances whose
+       - change logs are stored within those sources.
+       -->
+    <queryChangeLogSources>
+        <queryChangeLogSource>
+            <kafka>
+                <hostname>[Kafka Broker Hostname]</hostname>
+                <port>[Kafka Broker Port]</port>
+            </kafka>
+        </queryChangeLogSource>
+    </queryChangeLogSources>
+    
+    <!-- This section defines performance related tuning values. Sensible
+       - default have been provided to simplify configuration. 
+       -->
+    <performanceTunning>
+        <!-- Indicates how frequently the Query Change Logs that are defined
+           - in the sources section of this configuration file are polled for
+           - updates. This value effects how much time may pass between the 
+           - state of a query changing and that change being represented by
+           - the execution engine.
+           -->
+        <queryChanngeLogDiscoveryPeriod>
+            <value>1</value>
+            <!-- Options: {MILLISECONDS, SECONDS, MINUTES} -->
+            <units>MINUTES</units>
+        </queryChanngeLogDiscoveryPeriod>
+    </performanceTunning>
+</queryManagerConfig>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/c1ccde80/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java
new file mode 100644
index 0000000..834f0b9
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager.xml;
+
+import static java.util.Objects.requireNonNull;
+
+import java.io.Reader;
+import java.net.URL;
+
+import javax.xml.XMLConstants;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+
+import org.xml.sax.SAXException;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * Validates and unmarshalls XML into a {@link QueryManagerConfig} object.
+ */
+@DefaultAnnotation(NonNull.class)
+public class QueryManagerConfigUnmarshaller {
+
+    /**
+     * The path within the project's jar file where the XSD resides.
+     */
+    private static final String XSD_PATH = "QueryManagerConfig.xsd";
+
+    /**
+     * Validates and unmarshalls XML into a {@link QueryManagerConfig} object.
+     *
+     * @param xmlReader - Reads the XML that will be unmarshalled. (not null)
+     * @return A {@link QueryManagerConfig} loaded with the XMLs values.
+     * @throws SAXException Could not load the schema the XML will be validated against.
+     * @throws JAXBException Could not unmarshal the XML into a POJO.
+     */
+    public static QueryManagerConfig unmarshall(final Reader xmlReader) throws JAXBException, SAXException {
+        requireNonNull(xmlReader);
+
+        // Get an input stream to the XSD file that is packaged inside of the jar.
+        final URL schemaURL = ClassLoader.getSystemResource(XSD_PATH);
+        if(schemaURL == null) {
+            throw new RuntimeException("The Class Loader was unable to find the following resource: " + XSD_PATH);
+        }
+
+        // Get the schema for the object.
+        final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+        final Schema schema = sf.newSchema(schemaURL);
+
+        // Configure the unmarhsaller to validate using the schema.
+        final JAXBContext context = JAXBContext.newInstance(QueryManagerConfig.class);
+        final Unmarshaller unmarshaller = context.createUnmarshaller();
+        unmarshaller.setSchema(schema);
+
+        // Perform the unmarshal.
+        return (QueryManagerConfig) unmarshaller.unmarshal(xmlReader);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/c1ccde80/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd b/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
new file mode 100644
index 0000000..17d667f
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+  <!-- Define the Query Manager's schema. -->
+  <xs:element name="queryManagerConfig">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element name="queryChangeLogSources">
+          <xs:complexType>
+            <xs:sequence>
+              <xs:element name="queryChangeLogSource" maxOccurs="unbounded">
+                <xs:complexType>
+                  <xs:choice>
+                    <xs:element name="kafka" type="kafka"/>
+                  </xs:choice>
+                </xs:complexType>
+              </xs:element>
+            </xs:sequence>
+          </xs:complexType>
+        </xs:element>
+        <xs:element name="performanceTunning">
+          <xs:complexType>
+            <xs:sequence>
+              <xs:element name="queryChanngeLogDiscoveryPeriod">
+                <xs:complexType>
+                  <xs:sequence>
+                    <xs:element name="value" type="xs:positiveInteger"/>
+                    <xs:element name="units" type="timeUnits"/>
+                  </xs:sequence>
+                </xs:complexType>
+              </xs:element>
+            </xs:sequence>
+          </xs:complexType>
+        </xs:element>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+  
+  <!-- Defines the time units that may be specified. -->
+  <xs:simpleType name="timeUnits" final="restriction">
+    <xs:restriction base="xs:string">
+      <xs:enumeration value="MILLISECONDS"/>
+      <xs:enumeration value="SECONDS"/>
+      <xs:enumeration value="MINUTES"/>
+    </xs:restriction>
+  </xs:simpleType>
+
+  <!-- Define what kafka connection information looks like. -->  
+  <xs:complexType name="kafka">
+    <xs:sequence>
+      <xs:element name="hostname" type="xs:string"/>
+      <xs:element name="port" type="tcpPort" />
+    </xs:sequence>
+  </xs:complexType>
+  
+  <!-- Define the legal range for a TCP port. -->
+  <xs:simpleType name="tcpPort">
+    <xs:restriction base="xs:int">
+      <xs:minInclusive value="0"/>
+      <xs:maxInclusive value="65535"/>
+    </xs:restriction>
+  </xs:simpleType>
+</xs:schema>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/c1ccde80/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
new file mode 100644
index 0000000..bc8a040
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager.xml;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.io.StringReader;
+
+import javax.xml.bind.UnmarshalException;
+
+import org.junit.Test;
+
+/**
+ * Unit tests the methods of {@link QueryManagerConfigUnmarshaller}.
+ */
+public class QueryManagerConfigMarshallerTest {
+
+    @Test
+    public void unmarshal_validXml() throws Exception {
+        final String xml =
+                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
+                "<queryManagerConfig>\n" +
+                "    <queryChangeLogSources>\n" +
+                "        <queryChangeLogSource>\n" +
+                "            <kafka>\n" +
+                "                <hostname>localhost</hostname>\n" +
+                "                <port>6</port>\n" +
+                "            </kafka>\n" +
+                "        </queryChangeLogSource>\n" +
+                "    </queryChangeLogSources>\n" +
+                "    <performanceTunning>\n" +
+                "        <queryChanngeLogDiscoveryPeriod>\n" +
+                "            <value>1</value>\n" +
+                "            <units>MINUTES</units>\n" +
+                "        </queryChanngeLogDiscoveryPeriod>\n" +
+                "    </performanceTunning>\n" +
+                "</queryManagerConfig>";
+
+
+        final QueryManagerConfig config = QueryManagerConfigUnmarshaller.unmarshall(new StringReader(xml));
+        assertNotNull(config);
+    }
+
+    @Test(expected = UnmarshalException.class)
+    public void unmarshal_invalidXml() throws Exception {
+        final String xml =
+                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
+                "<queryManagerConfig>\n" +
+                "    <queryChangeLogSources>\n" +
+                "        <queryChangeLogSource>\n" +
+                "            <kafka>\n" +
+                "                <hostname>localhost</hostname>\n" +
+                "                <port>6</port>\n" +
+                "            </kafka>\n" +
+                "        </queryChangeLogSource>\n" +
+                "    </queryChangeLogSources>\n" +
+                "</queryManagerConfig>";
+
+
+        QueryManagerConfigUnmarshaller.unmarshall(new StringReader(xml));
+    }
+}
\ No newline at end of file


[17/22] incubator-rya git commit: RYA-443 Updated query-manager RPM to use Java based plugin

Posted by pu...@apache.org.
RYA-443 Updated query-manager RPM to use Java based plugin


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/8b11d74f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/8b11d74f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/8b11d74f

Branch: refs/heads/master
Commit: 8b11d74fe82a099902582b52aff7546c201d0fa3
Parents: 1cd8db3
Author: eric.white <Er...@parsons.com>
Authored: Tue Feb 27 15:58:37 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:57 2018 -0500

----------------------------------------------------------------------
 extras/rya.streams/query-manager/pom.xml | 160 ++++++++++++++++----------
 1 file changed, 100 insertions(+), 60 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/8b11d74f/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
index d2ccbf5..afb0386 100644
--- a/extras/rya.streams/query-manager/pom.xml
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -174,76 +174,116 @@ under the License.
             </plugin>
 
             <plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>rpm-maven-plugin</artifactId>
+                <groupId>de.dentrassi.maven</groupId>
+                <artifactId>rpm</artifactId>
+                <version>0.10.0</version>
                 <executions>
                     <execution>
-                        <id>set-rpm-properties</id>
-                        <goals>
-                            <goal>version</goal>
-                        </goals>
-                    </execution>
-                    <execution>
-                        <id>create-rpm-distribution</id>
+                        <id>create-rpm-properties</id>
+                        <phase>package</phase>
                         <goals>
-                            <goal>attached-rpm</goal>
+                            <goal>rpm</goal>
                         </goals>
-                        <phase>package</phase>
                         <configuration>
-                            <group>${project.groupId}</group>
-                            <name>${project.artifactId}</name>
-                            <classifier>noarch</classifier>
-                            <defaultUsername>root</defaultUsername>
-                            <defaultGroupname>root</defaultGroupname>
-                            <defaultDirmode>755</defaultDirmode>
-                            <defaultFilemode>644</defaultFilemode>
-                            
+                            <attach>false</attach> <!-- don't attach RPM -->
+                            <group>${project.groupId}/${project.artifactId}</group> <!-- set RPM group -->
+                            <architecture>noarch</architecture>
+
+                            <signature>
+                                <skip>true</skip>
+                            </signature>
+
                             <!-- (Un)Install scripts that enable/disable the daemon.-->
-                            <postinstallScriptlet>
-                                <scriptFile>${rpm.staging.path}/bin/rpm/postinstall.sh</scriptFile>
-                                <fileEncoding>utf-8</fileEncoding>
-                            </postinstallScriptlet>
-                            <preremoveScriptlet>
-                                <scriptFile>${rpm.staging.path}/bin/rpm/preremove.sh</scriptFile>
-                                <fileEncoding>utf-8</fileEncoding>
-                            </preremoveScriptlet>
-                            
-                            <!-- This project requires the Apache Commons Daemon applications. -->
+                            <afterInstallation>
+                                <file>${rpm.staging.path}/bin/rpm/postinstall.sh</file>
+                            </afterInstallation>
+                            <beforeRemoval>
+                                <file>${rpm.staging.path}/bin/rpm/preremove.sh</file>
+                            </beforeRemoval>
+
+                             <!-- This project requires the Apache Commons Daemon applications. -->
                             <requires>
                                 <require>jsvc</require>
                             </requires>
-                            
-                            <mappings>
-                                <!-- Copy everything over to the /opt directory, except for the scripts. -->
-                                <mapping>
-                                    <directory>/opt/rya-streams-query-manager-${rpm.version}</directory>
-                                    <sources>
-                                        <!-- Copy over everything exception for the executable script. -->
-                                        <source>
-                                            <location>${rpm.staging.path}</location>
-                                            <excludes>
-                                                <exclude>bin/rpm/**</exclude>
-                                                <exclude>bin/rya-streams-query-manager.sh</exclude>
-                                            </excludes>
-                                        </source>
-                                    </sources>
-                                </mapping>
 
-                                <!-- Copy over the scripts with the correct execution permissions. -->
-                                <mapping>
-                                    <directory>/opt/rya-streams-query-manager-${rpm.version}/bin</directory>
-                                    <directoryIncluded>false</directoryIncluded>
-                                    <filemode>554</filemode>
-                                    <sources>
-                                        <source>
-                                            <location>${rpm.staging.path}/bin</location>
-                                            <includes>
-                                                <include>rya-streams-query-manager.sh</include>
-                                            </includes>
-                                        </source>
-                                    </sources>
-                                </mapping>
-                            </mappings>
+                            <rulesets>
+                                <ruleset>
+                                    <id>default-ruleset</id>
+                                    <rules>
+                                        <rule>
+                                            <when>
+                                                <type>directory</type>
+                                            </when>
+                                            <mode>0755</mode>
+                                        </rule>
+                                        <rule>
+                                            <when>
+                                                <type>file</type>
+                                            </when>
+                                            <mode>0644</mode>
+                                        </rule>
+                                        <file>
+                                            <when>
+                                                <suffix>configuration.xml</suffix>
+                                            </when>
+                                            <configuration>true</configuration>
+                                        </file>
+                                        <file>
+                                            <when>
+                                                <suffix>log4j.xml</suffix>
+                                            </when>
+                                            <configuration>true</configuration>
+                                        </file>
+                                        <file>
+                                            <when>
+                                                <suffix>README.txt</suffix>
+                                            </when>
+                                            <readme>true</readme>
+                                        </file>
+                                    </rules>
+                                </ruleset>
+                            </rulesets>
+                            <entries>
+                                <!-- Copy everything over to the /opt directory, except for the scripts. -->
+                                <entry>
+                                    <name>/opt/rya-streams-query-manager-${project.version}/bin/systemd</name>
+                                    <collect>
+                                        <from>${rpm.staging.path}/bin/systemd</from>
+                                        <directories>true</directories>
+                                    </collect>
+                                    <ruleset>default-ruleset</ruleset>
+                                </entry>
+                                <entry>
+                                    <name>/opt/rya-streams-query-manager-${project.version}/config</name>
+                                    <collect>
+                                        <from>${rpm.staging.path}/config</from>
+                                        <directories>true</directories>
+                                    </collect>
+                                    <ruleset>default-ruleset</ruleset>
+                                </entry>
+                                <entry>
+                                    <name>/opt/rya-streams-query-manager-${project.version}/lib</name>
+                                    <collect>
+                                        <from>${rpm.staging.path}/lib</from>
+                                        <directories>true</directories>
+                                    </collect>
+                                    <ruleset>default-ruleset</ruleset>
+                                </entry>
+                                <entry>
+                                    <name>/opt/rya-streams-query-manager-${project.version}/README.txt</name>
+                                    <collect>
+                                        <from>${rpm.staging.path}/README.txt</from>
+                                    </collect>
+                                    <ruleset>default-ruleset</ruleset>
+                                </entry>
+                                <entry>
+                                    <name>/opt/rya-streams-query-manager-${project.version}/bin/rya-streams-query-manager.sh</name>
+                                    <collect>
+                                        <from>${rpm.staging.path}/bin/rya-streams-query-manager.sh</from>
+                                    </collect>
+                                    <mode>0544</mode>
+                                </entry>
+                            </entries>
                         </configuration>
                     </execution>
                 </executions>


[18/22] incubator-rya git commit: RYA-466 Update the Rya Streams Client to stream results to file.

Posted by pu...@apache.org.
RYA-466 Update the Rya Streams Client to stream results to file.


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/e4536943
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/e4536943
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/e4536943

Branch: refs/heads/master
Commit: e453694334244df2dc3c8768be77e173a734135a
Parents: 8b11d74
Author: kchilton2 <ke...@gmail.com>
Authored: Wed Feb 14 13:49:52 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 13:00:00 2018 -0500

----------------------------------------------------------------------
 .../apache/rya/api/utils/QueryInvestigator.java | 103 +++++++++++++
 .../rya/api/utils/QueryInvestigatorTest.java    | 150 +++++++++++++++++++
 extras/rya.streams/client/pom.xml               |   9 ++
 .../client/command/StreamResultsCommand.java    |  58 +++++--
 .../client/util/QueryResultsOutputUtil.java     | 133 ++++++++++++++++
 .../client/util/QueryResultsOutputUtilTest.java | 135 +++++++++++++++++
 6 files changed, 577 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e4536943/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
----------------------------------------------------------------------
diff --git a/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java b/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
new file mode 100644
index 0000000..2fbd09b
--- /dev/null
+++ b/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
@@ -0,0 +1,103 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.api.utils;
+
+import static java.util.Objects.requireNonNull;
+
+import org.openrdf.query.MalformedQueryException;
+import org.openrdf.query.parser.ParsedGraphQuery;
+import org.openrdf.query.parser.ParsedQuery;
+import org.openrdf.query.parser.QueryParserUtil;
+import org.openrdf.query.parser.sparql.SPARQLParser;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * A utility class that is used to glean insight into the structure of SPARQL queries.
+ */
+@DefaultAnnotation(NonNull.class)
+public class QueryInvestigator {
+
+    private static final SPARQLParser PARSER = new SPARQLParser();
+
+    private QueryInvestigator() { }
+
+    /**
+     * Determines whether a SPARQL command is a CONSTRUCT or not.
+     *
+     * @param sparql - The SPARQL to evaluate. (not null)
+     * @return {@code true} if the provided SPARQL is a CONSTRUCT query; otherwise {@code false}.
+     * @throws MalformedQueryException The SPARQL is neither a well formed query or update.
+     */
+    public static boolean isConstruct(final String sparql) throws MalformedQueryException {
+        requireNonNull(sparql);
+
+        try {
+            // Constructs are queries, so try to create a ParsedQuery.
+            final ParsedQuery parsedQuery = PARSER.parseQuery(sparql, null);
+
+            // Check to see if the SPARQL looks like a CONSTRUCT query.
+            return parsedQuery instanceof ParsedGraphQuery;
+
+        } catch(final MalformedQueryException queryE) {
+            try {
+                // Maybe it's an update.
+                PARSER.parseUpdate(sparql, null);
+
+                // It was, so return false.
+                return false;
+
+            } catch(final MalformedQueryException updateE) {
+                // It's not. Actually malformed.
+                throw queryE;
+            }
+        }
+    }
+
+    /**
+     * Determines whether a SPARQL command is an INSERT with a WHERE clause or not.
+     *
+     * @param sparql - The SPARQL to evaluate. (not null)
+     * @return {@code true} if the provided SPARQL is an INSERT update; otherwise {@code false}.
+     * @throws MalformedQueryException The SPARQL is neither a well formed query or update.
+     */
+    public static boolean isInsertWhere(final String sparql) throws MalformedQueryException {
+        requireNonNull(sparql);
+
+        try {
+            // Inserts are updated, so try to create a ParsedUpdate.
+            PARSER.parseUpdate(sparql, null);
+            final String strippedOperation = QueryParserUtil.removeSPARQLQueryProlog(sparql.toLowerCase());
+            return strippedOperation.startsWith("insert");
+        } catch(final MalformedQueryException updateE) {
+            try {
+                // Maybe it's a query.
+                PARSER.parseQuery(sparql, null);
+
+                // It was, so return false.
+                return false;
+
+            } catch(final MalformedQueryException queryE) {
+                // It's not. Actually malformed.
+                throw updateE;
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e4536943/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
----------------------------------------------------------------------
diff --git a/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java b/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
new file mode 100644
index 0000000..fbe2ebe
--- /dev/null
+++ b/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
@@ -0,0 +1,150 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.api.utils;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.openrdf.query.MalformedQueryException;
+
+/**
+ * Unit tests the methods of {@link QueryInvestigator}.
+ */
+public class QueryInvestigatorTest {
+
+    @Test
+    public void isConstruct_true() throws Exception {
+        final String sparql =
+                "PREFIX vCard: <http://www.w3.org/2001/vcard-rdf/3.0#> " +
+                "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
+                "CONSTRUCT { " +
+                    "?X vCard:FN ?name . " +
+                    "?X vCard:URL ?url . " +
+                    "?X vCard:TITLE ?title . " +
+                "} " +
+                "FROM <http://www.w3.org/People/Berners-Lee/card> " +
+                "WHERE { " +
+                    "OPTIONAL { ?X foaf:name ?name . FILTER isLiteral(?name) . } " +
+                    "OPTIONAL { ?X foaf:homepage ?url . FILTER isURI(?url) . } " +
+                    "OPTIONAL { ?X foaf:title ?title . FILTER isLiteral(?title) . } " +
+                "}";
+
+        assertTrue( QueryInvestigator.isConstruct(sparql) );
+    }
+
+    @Test
+    public void isConstruct_false_notAConstruct() throws Exception {
+        final String sparql = "SELECT * WHERE { ?a ?b ?c . }";
+        assertFalse( QueryInvestigator.isConstruct(sparql) );
+    }
+
+    @Test
+    public void isConstruct_false_notAConstructWithKeywords() throws Exception {
+        final String sparql =
+                "SELECT ?construct " +
+                "WHERE {" +
+                "   ?construct <urn:built> <urn:skyscraper> ." +
+                "}";
+        assertFalse( QueryInvestigator.isConstruct(sparql) );
+    }
+
+    @Test
+    public void isConstruct_false_notAQuery() throws Exception {
+        final String sparql =
+                "PREFIX Sensor: <http://example.com/Equipment.owl#> " +
+                "INSERT { " +
+                    "?subject Sensor:test2 ?newValue " +
+                "} WHERE {" +
+                    "values (?oldValue ?newValue) {" +
+                        "('testValue1' 'newValue1')" +
+                        "('testValue2' 'newValue2')" +
+                    "}" +
+                    "?subject Sensor:test1 ?oldValue" +
+                "}";
+
+        assertFalse( QueryInvestigator.isConstruct(sparql) );
+    }
+
+    @Test(expected = MalformedQueryException.class)
+    public void isConstruct_false_malformed() throws MalformedQueryException {
+        assertFalse( QueryInvestigator.isConstruct("not sparql") );
+    }
+
+    @Test
+    public void isInsert_true() throws Exception {
+        final String sparql =
+                "PREFIX Sensor: <http://example.com/Equipment.owl#> " +
+                "INSERT { " +
+                    "?subject Sensor:test2 ?newValue " +
+                "} WHERE {" +
+                    "values (?oldValue ?newValue) {" +
+                        "('testValue1' 'newValue1')" +
+                        "('testValue2' 'newValue2')" +
+                    "}" +
+                    "?subject Sensor:test1 ?oldValue" +
+                "}";
+
+        assertTrue( QueryInvestigator.isInsertWhere(sparql) );
+    }
+
+    @Test
+    public void isInsert_false_notAnInsert() throws Exception {
+        final String sparql =
+                "PREFIX dc:  <http://purl.org/dc/elements/1.1/> " +
+                "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
+                "DELETE { " +
+                    "?book ?p ?v " +
+                "} WHERE { " +
+                    "?book dc:date ?date . " +
+                    "FILTER ( ?date < \"2000-01-01T00:00:00\"^^xsd:dateTime ) " +
+                    "?book ?p ?v " +
+                "}";
+
+        assertFalse( QueryInvestigator.isInsertWhere(sparql) );
+    }
+
+    @Test
+    public void isInsert_false_notAnInsertWithKeywords() throws Exception {
+        final String sparql =
+                "DELETE" +
+                "{ " +
+                "    ?bookInsert ?p ?o" +
+                "}" +
+                "WHERE" +
+                "{ " +
+                "    ?bookInsert <urn:datePrinted> ?datePrinted  ." +
+                "    FILTER ( ?datePrinted < \"2018-01-01T00:00:00\"^^xsd:dateTime )" +
+                "    ?bookInsert ?p ?o" +
+                "}";
+
+        assertFalse( QueryInvestigator.isInsertWhere(sparql) );
+    }
+
+    @Test
+    public void isInsert_false_notAnUpdate() throws Exception {
+        final String sparql = "SELECT * WHERE { ?a ?b ?c . }";
+        assertFalse( QueryInvestigator.isInsertWhere(sparql) );
+    }
+
+    @Test(expected = MalformedQueryException.class)
+    public void isInsert_false_malformed() throws MalformedQueryException {
+        assertFalse( QueryInvestigator.isInsertWhere("not sparql") );
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e4536943/extras/rya.streams/client/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/pom.xml b/extras/rya.streams/client/pom.xml
index 5bd7933..38c3c86 100644
--- a/extras/rya.streams/client/pom.xml
+++ b/extras/rya.streams/client/pom.xml
@@ -69,6 +69,10 @@ under the License.
             <groupId>org.openrdf.sesame</groupId>
             <artifactId>sesame-rio-turtle</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.openrdf.sesame</groupId>
+            <artifactId>sesame-queryresultio-sparqljson</artifactId>
+        </dependency>
             
         <!-- Third Party dependencies -->
         <dependency>
@@ -92,6 +96,11 @@ under the License.
             <scope>test</scope>
         </dependency>
         <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-all</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
             <groupId>org.apache.rya</groupId>
             <artifactId>rya.test.kafka</artifactId>
             <scope>test</scope>

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e4536943/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
index 3612dd0..8ae4e08 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
@@ -1,4 +1,4 @@
-/*
+/**
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -20,11 +20,18 @@ package org.apache.rya.streams.client.command;
 
 import static java.util.Objects.requireNonNull;
 
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.Optional;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
+import org.apache.rya.api.model.VisibilityBindingSet;
+import org.apache.rya.api.model.VisibilityStatement;
+import org.apache.rya.api.utils.QueryInvestigator;
 import org.apache.rya.streams.api.entity.QueryResultStream;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.interactor.GetQueryResultStream;
@@ -32,13 +39,13 @@ import org.apache.rya.streams.api.queries.InMemoryQueryRepository;
 import org.apache.rya.streams.api.queries.QueryChangeLog;
 import org.apache.rya.streams.api.queries.QueryRepository;
 import org.apache.rya.streams.client.RyaStreamsCommand;
+import org.apache.rya.streams.client.util.QueryResultsOutputUtil;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.interactor.KafkaGetQueryResultStream;
 import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLogFactory;
 import org.apache.rya.streams.kafka.serialization.VisibilityBindingSetDeserializer;
 import org.apache.rya.streams.kafka.serialization.VisibilityStatementDeserializer;
 import org.openrdf.query.MalformedQueryException;
-import org.openrdf.query.algebra.Reduced;
 import org.openrdf.query.algebra.TupleExpr;
 import org.openrdf.query.parser.sparql.SPARQLParser;
 
@@ -65,14 +72,20 @@ public class StreamResultsCommand implements RyaStreamsCommand {
         @Parameter(names = {"--queryId", "-q"}, required = true, description = "The query whose results will be streamed to the console.")
         private String queryId;
 
+        @Parameter(names = {"--file", "-f"}, required = false, description = "If provided, the output file the results will stream into.")
+        private String outputPath;
+
         @Override
         public String toString() {
             final StringBuilder parameters = new StringBuilder();
             parameters.append(super.toString());
 
             if (!Strings.isNullOrEmpty(queryId)) {
-                parameters.append("\tQuery ID: " + queryId);
-                parameters.append("\n");
+                parameters.append("\tQuery ID: " + queryId + "\n");
+            }
+
+            if(!Strings.isNullOrEmpty(outputPath)) {
+                parameters.append("\tOutput Path: " + outputPath + "\n");
             }
 
             return parameters.toString();
@@ -160,10 +173,12 @@ public class StreamResultsCommand implements RyaStreamsCommand {
         });
 
         // Build the interactor based on the type of result the query produces.
+        boolean isStatementResults = false;
+
         final GetQueryResultStream<?> getQueryResultStream;
         try {
-            final TupleExpr tupleExpr = new SPARQLParser().parseQuery(sparql, null).getTupleExpr();
-            if(tupleExpr instanceof Reduced) {
+            isStatementResults = QueryInvestigator.isConstruct(sparql) | QueryInvestigator.isInsertWhere(sparql);
+            if(isStatementResults) {
                 getQueryResultStream = new KafkaGetQueryResultStream<>(params.kafkaIP, params.kafkaPort, VisibilityStatementDeserializer.class);
             } else {
                 getQueryResultStream = new KafkaGetQueryResultStream<>(params.kafkaIP, params.kafkaPort, VisibilityBindingSetDeserializer.class);
@@ -172,12 +187,22 @@ public class StreamResultsCommand implements RyaStreamsCommand {
             throw new ExecutionException("Could not parse the SPARQL for the query: " + sparql, e);
         }
 
-        // Iterate through the results and print them to the console until the program or the stream ends.
-        try (final QueryResultStream<?> stream = getQueryResultStream.fromStart(queryId)) {
-            while(!finished.get()) {
-                for(final Object result : stream.poll(1000)) {
-                    System.out.println(result);
+        // Iterate through the results and print them to the configured output mechanism.
+        try (final QueryResultStream<?> resultsStream = getQueryResultStream.fromStart(queryId)) {
+            final TupleExpr tupleExpr = new SPARQLParser().parseQuery(sparql, null).getTupleExpr();
+            if(params.outputPath != null) {
+                final Path file = Paths.get(params.outputPath);
+                try (final OutputStream out = Files.newOutputStream(file)) {
+                    if(isStatementResults) {
+                        final QueryResultStream<VisibilityStatement> stmtStream = (QueryResultStream<VisibilityStatement>) resultsStream;
+                        QueryResultsOutputUtil.toNtriplesFile(out, stmtStream, finished);
+                    } else {
+                        final QueryResultStream<VisibilityBindingSet> bsStream = (QueryResultStream<VisibilityBindingSet>) resultsStream;
+                        QueryResultsOutputUtil.toBindingSetJSONFile(out, tupleExpr, bsStream, finished);
+                    }
                 }
+            } else {
+                streamToSystemOut(resultsStream, finished);
             }
         } catch (final Exception e) {
             System.err.println("Error while reading the results from the stream.");
@@ -185,4 +210,15 @@ public class StreamResultsCommand implements RyaStreamsCommand {
             System.exit(1);
         }
     }
+
+    private static void streamToSystemOut(final QueryResultStream<?> stream, final AtomicBoolean shutdownSignal) throws Exception {
+        requireNonNull(stream);
+        requireNonNull(shutdownSignal);
+
+        while(!shutdownSignal.get()) {
+            for(final Object result : stream.poll(1000)) {
+                System.out.println(result);
+            }
+        }
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e4536943/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/util/QueryResultsOutputUtil.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/util/QueryResultsOutputUtil.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/util/QueryResultsOutputUtil.java
new file mode 100644
index 0000000..114a6fe
--- /dev/null
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/util/QueryResultsOutputUtil.java
@@ -0,0 +1,133 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.client.util;
+
+import static java.util.Objects.requireNonNull;
+
+import java.io.OutputStream;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.rya.api.model.VisibilityBindingSet;
+import org.apache.rya.api.model.VisibilityStatement;
+import org.apache.rya.streams.api.entity.QueryResultStream;
+import org.apache.rya.streams.api.exception.RyaStreamsException;
+import org.openrdf.query.TupleQueryResultHandlerException;
+import org.openrdf.query.algebra.TupleExpr;
+import org.openrdf.query.resultio.sparqljson.SPARQLResultsJSONWriter;
+import org.openrdf.rio.RDFFormat;
+import org.openrdf.rio.RDFHandlerException;
+import org.openrdf.rio.RDFWriter;
+import org.openrdf.rio.Rio;
+import org.openrdf.rio.WriterConfig;
+import org.openrdf.rio.helpers.BasicWriterSettings;
+
+import com.google.common.collect.Lists;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * A utility that writes {@link QueryResultStream} results to an {@link OutputStream}.
+ */
+@DefaultAnnotation(NonNull.class)
+public class QueryResultsOutputUtil {
+
+    /**
+     * Private constructor to prevent instantiation.
+     */
+    private QueryResultsOutputUtil() { }
+
+    /**
+     * Writes the results of a {@link QueryResultStream} to the output stream as NTriples until the
+     * shutdown signal is set.
+     *
+     * @param out - The stream the NTriples data will be written to. (not null)
+     * @param resultsStream - The results stream that will be polled for results to
+     *   write to {@code out}. (not null)
+     * @param shutdownSignal - Setting this signal will cause the thread that
+     *   is processing this function to finish and leave. (not null)
+     * @throws RDFHandlerException A problem was encountered while
+     *   writing the NTriples to the output stream.
+     * @throws IllegalStateException The {@code resultsStream} is closed.
+     * @throws RyaStreamsException Could not fetch the next set of results.
+     */
+    public static void toNtriplesFile(
+            final OutputStream out,
+            final QueryResultStream<VisibilityStatement> resultsStream,
+            final AtomicBoolean shutdownSignal) throws RDFHandlerException, IllegalStateException, RyaStreamsException {
+        requireNonNull(out);
+        requireNonNull(resultsStream);
+        requireNonNull(shutdownSignal);
+
+        final RDFWriter writer = Rio.createWriter(RDFFormat.NTRIPLES, out);
+        writer.startRDF();
+
+        while(!shutdownSignal.get()) {
+            final Iterable<VisibilityStatement> it = resultsStream.poll(1000);
+            for(final VisibilityStatement result : it) {
+                writer.handleStatement(result);
+            }
+        }
+
+        writer.endRDF();
+    }
+
+    /**
+     * Writes the results of a {@link QueryResultStream} to the output stream as JSON until the
+     * shutdown signal is set.
+     *
+     * @param out - The stream the JSON will be written to. (not null)
+     * @param query - The parsed SPARQL Query whose results are being output. This
+     *   object is used to figure out which bindings may appear. (not null)
+     * @param resultsStream - The results stream that will be polled for results to
+     *   write to {@code out}. (not null)
+     * @param shutdownSignal - Setting this signal will cause the thread that
+     *   is processing this function to finish and leave. (not null)
+     * @throws TupleQueryResultHandlerException A problem was encountered while
+     *   writing the JSON to the output stream.
+     * @throws IllegalStateException The {@code resultsStream} is closed.
+     * @throws RyaStreamsException Could not fetch the next set of results.
+     */
+    public static void toBindingSetJSONFile(
+            final OutputStream out,
+            final TupleExpr query,
+            final QueryResultStream<VisibilityBindingSet> resultsStream,
+            final AtomicBoolean shutdownSignal) throws TupleQueryResultHandlerException, IllegalStateException, RyaStreamsException {
+        requireNonNull(out);
+        requireNonNull(query);
+        requireNonNull(resultsStream);
+        requireNonNull(shutdownSignal);
+
+        // Create a writer that does not pretty print.
+        final SPARQLResultsJSONWriter writer = new SPARQLResultsJSONWriter(out);
+        final WriterConfig config = writer.getWriterConfig();
+        config.set(BasicWriterSettings.PRETTY_PRINT, false);
+
+        // Start the JSON and enumerate the possible binding names.
+        writer.startQueryResult( Lists.newArrayList(query.getBindingNames()) );
+
+        while(!shutdownSignal.get()) {
+            for(final VisibilityBindingSet result : resultsStream.poll(1000)) {
+                writer.handleSolution(result);
+            }
+        }
+
+        writer.endQueryResult();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e4536943/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/util/QueryResultsOutputUtilTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/util/QueryResultsOutputUtilTest.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/util/QueryResultsOutputUtilTest.java
new file mode 100644
index 0000000..b82e671
--- /dev/null
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/util/QueryResultsOutputUtilTest.java
@@ -0,0 +1,135 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.client.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.rya.api.model.VisibilityBindingSet;
+import org.apache.rya.api.model.VisibilityStatement;
+import org.apache.rya.streams.api.entity.QueryResultStream;
+import org.junit.Test;
+import org.openrdf.model.Statement;
+import org.openrdf.model.ValueFactory;
+import org.openrdf.model.impl.ValueFactoryImpl;
+import org.openrdf.query.algebra.TupleExpr;
+import org.openrdf.query.impl.MapBindingSet;
+import org.openrdf.query.parser.sparql.SPARQLParser;
+
+import com.google.common.base.Charsets;
+
+/**
+ * Unit tests the methods of {@link QueryResultsOutputUtil}.
+ */
+public class QueryResultsOutputUtilTest {
+
+    private static final ValueFactory VF = new ValueFactoryImpl();
+
+    @Test
+    public void toNtriplesFile() throws Exception {
+        // Mock a result stream that signals shutdown when it returns a set of results.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+        final QueryResultStream<VisibilityStatement> resultsStream = mock(QueryResultStream.class);
+        when(resultsStream.poll(anyLong())).thenAnswer(invocation -> {
+            shutdownSignal.set(true);
+
+            final List<VisibilityStatement> results = new ArrayList<>();
+
+            Statement stmt = VF.createStatement(VF.createURI("urn:alice"), VF.createURI("urn:age"), VF.createLiteral(23));
+            results.add( new VisibilityStatement(stmt) );
+
+            stmt = VF.createStatement(VF.createURI("urn:bob"), VF.createURI("urn:worksAt"), VF.createLiteral("Taco Shop"));
+            results.add( new VisibilityStatement(stmt) );
+            return results;
+        });
+
+        // The stream the JSON will be written to.
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+        // Invoke the test method. This will write the NTriples.
+        QueryResultsOutputUtil.toNtriplesFile(out, resultsStream, shutdownSignal);
+
+        // Show the produced NTriples matches the expected NTriples.
+        final String expected =
+                "<urn:alice> <urn:age> \"23\"^^<http://www.w3.org/2001/XMLSchema#int> .\n" +
+                "<urn:bob> <urn:worksAt> \"Taco Shop\" .\n";
+
+        final String nTriples = new String(out.toByteArray(), Charsets.UTF_8);
+        assertEquals(expected, nTriples);
+    }
+
+    @Test
+    public void toBindingSetJSONFile() throws Exception {
+        // A SPARQL query that uses OPTIONAL values.
+        final String sparql =
+                "SELECT * WHERE { " +
+                    "?name <urn:worksAt> ?company . " +
+                    "OPTIONAL{ ?name <urn:ssn> ?ssn} " +
+                "}";
+        final TupleExpr query = new SPARQLParser().parseQuery(sparql, null).getTupleExpr();
+
+        // Mock a results stream that signals shutdown when it returns a set of results.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+        final QueryResultStream<VisibilityBindingSet> resultsStream = mock(QueryResultStream.class);
+        when(resultsStream.poll(anyLong())).thenAnswer(invocation -> {
+            shutdownSignal.set(true);
+
+            final List<VisibilityBindingSet> results = new ArrayList<>();
+
+            // A result with the optional value.
+            MapBindingSet bs = new MapBindingSet();
+            bs.addBinding("name", VF.createLiteral("alice"));
+            bs.addBinding("company", VF.createLiteral("Taco Shop"));
+            bs.addBinding("ssn", VF.createURI("urn:111-11-1111"));
+            results.add(new VisibilityBindingSet(bs, ""));
+
+
+            // A result without the optional value.
+            bs = new MapBindingSet();
+            bs.addBinding("name", VF.createLiteral("bob"));
+            bs.addBinding("company", VF.createLiteral("Cafe"));
+            results.add(new VisibilityBindingSet(bs, ""));
+
+            return results;
+        });
+
+        // The stream the JSON will be written to.
+        final ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+        // Invoke the test method. This will write the json.
+        QueryResultsOutputUtil.toBindingSetJSONFile(out, query, resultsStream, shutdownSignal);
+
+        // Show the produced JSON matches the expected JSON.
+        final String expected =  "{\"head\":{\"vars\":[\"name\",\"company\",\"ssn\"]},\"results\":{" +
+                "\"bindings\":[{\"name\":{\"type\":\"literal\",\"value\":\"alice\"},\"company\":{" +
+                "\"type\":\"literal\",\"value\":\"Taco Shop\"},\"ssn\":{\"type\":\"uri\",\"value\":" +
+                "\"urn:111-11-1111\"}},{\"name\":{\"type\":\"literal\",\"value\":\"bob\"},\"company\"" +
+                ":{\"type\":\"literal\",\"value\":\"Cafe\"}}]}}";
+        final String json = new String(out.toByteArray(), Charsets.UTF_8);
+        System.out.println(json);
+        assertEquals(expected, json);
+    }
+}
\ No newline at end of file


[02/22] incubator-rya git commit: RYA-449 Create QueryChangeLogSource

Posted by pu...@apache.org.
RYA-449 Create QueryChangeLogSource


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/d6d6d04b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/d6d6d04b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/d6d6d04b

Branch: refs/heads/master
Commit: d6d6d04b3b7efe4ef6a6112e5eaa12058b4e0427
Parents: 5b489dc
Author: Andrew Smith <sm...@gmail.com>
Authored: Thu Jan 18 17:51:40 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:33 2018 -0500

----------------------------------------------------------------------
 .../querymanager/QueryChangeLogSource.java      | 76 ++++++++++++++++++++
 1 file changed, 76 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/d6d6d04b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java
new file mode 100644
index 0000000..73e5d12
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import org.apache.rya.streams.api.queries.QueryChangeLog;
+
+import com.google.common.util.concurrent.Service;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * A {@link QueryChangeLog} source represents a storage where the change logs reside, but it
+ * does not provide a way to create or remove them. Instead, subscribed {@link SourceListener}s
+ * are notified whenever a change log is created or removed from the storage.
+ */
+@DefaultAnnotation(NonNull.class)
+public interface QueryChangeLogSource extends Service {
+
+    /**
+     * Adds a {@link SourceListener} to be notified when {@link QueryChangeLog}s
+     * have been found.
+     * <p>
+     * When a new subscriber is added, it will be notified with the existing {@link QueryChangeLog}s.
+     *
+     * @param listener - The {@link SourceListener} to add. (not null)
+     */
+    public void subscribe(final SourceListener listener);
+
+    /**
+     * Removes a {@link SourceListener}.
+     *
+     * @param listener - The {@link SourceListener} to remove. (not null)
+     */
+    public void unsubscribe(final SourceListener listener);
+
+    /**
+     * A listener that is notified when a {@link QueryChangeLog} has
+     * been added or removed from a {@link QueryChangeLogSource}.
+     */
+    @DefaultAnnotation(NonNull.class)
+    public interface SourceListener {
+        /**
+         * Notifies the subscriber that there is a new {@link QueryChangeLog} in the
+         * {@link QueryChangeLogSource}.
+         *
+         * @param ryaInstanceName - The Rya Instance name the {@link QueryChangeLog} belongs to. (not null)
+         * @param log - The new {@link QueryChangeLog}. (not null)
+         */
+        public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log);
+
+        /**
+         * Notifies the subscriber that a {@link QueryChangeLog} has been deleted
+         * from the {@link QueryChangeLogSource}.
+         *
+         * @param ryaInstanceName - The rya instance whose {@link QueryChangeLog} was removed. (not null)
+         */
+        public void notifyDelete(final String ryaInstanceName);
+    }
+}


[10/22] incubator-rya git commit: Rya 451 Query manager

Posted by pu...@apache.org.
Rya 451 Query manager

QueryManager with tests
updated InMemoryQueryRepository and its tests

Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/e355f73a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/e355f73a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/e355f73a

Branch: refs/heads/master
Commit: e355f73ae6c56eb439e1d56722cd20c5287cbe04
Parents: a11ca4a
Author: Andrew Smith <sm...@gmail.com>
Authored: Tue Jan 30 14:01:54 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:47 2018 -0500

----------------------------------------------------------------------
 .../rya/streams/api/entity/StreamsQuery.java    |  15 ++
 .../api/queries/InMemoryQueryRepository.java    |   7 +-
 .../api/queries/QueryChangeLogListener.java     |   8 +-
 .../queries/InMemoryQueryRepositoryTest.java    |  55 ++--
 extras/rya.streams/query-manager/pom.xml        |   2 +-
 .../rya/streams/querymanager/QueryManager.java  | 255 +++++++++++++++++++
 .../streams/querymanager/QueryManagerTest.java  | 195 ++++++++++++++
 7 files changed, 504 insertions(+), 33 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e355f73a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
index bd750a6..7194834 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
@@ -85,4 +85,19 @@ public class StreamsQuery {
         }
         return false;
     }
+    
+    @Override
+    public String toString() {
+        final StringBuilder sb = new StringBuilder();
+        sb.append("ID: ");
+        sb.append(getQueryId().toString() + "\n");
+        sb.append("Query: ");
+        sb.append(getSparql() + "\n");
+        sb.append("Is ");
+        if (!isActive) {
+            sb.append(" Not ");
+        }
+        sb.append("Running.\n");
+        return sb.toString();
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e355f73a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
index dca040f..5fb0297 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
@@ -188,8 +188,8 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
 
             // Our internal cache is already up to date, so just return its values.
             return queriesCache.values()
-                        .stream()
-                        .collect(Collectors.toSet());
+                    .stream()
+                    .collect(Collectors.toSet());
 
         } finally {
             lock.unlock();
@@ -253,7 +253,8 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
                         break;
                 }
 
-                listeners.forEach(listener -> listener.notify(entry));
+                final Optional<StreamsQuery> newQueryState = Optional.ofNullable(queriesCache.get(queryId));
+                listeners.forEach(listener -> listener.notify(entry, newQueryState));
 
                 cachePosition = Optional.of( entry.getPosition() );
             }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e355f73a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java
index 2b61227..2f0bcc3 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java
@@ -18,6 +18,10 @@
  */
 package org.apache.rya.streams.api.queries;
 
+import java.util.Optional;
+
+import org.apache.rya.streams.api.entity.StreamsQuery;
+
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
 
@@ -36,6 +40,8 @@ public interface QueryChangeLogListener {
      * on the repository.
      *
      * @param queryChangeEvent - The event that occurred. (not null)
+     * @param newQueryState - The new state of the query after the query change event, this will be
+     *     absent if the change type is DELETE. (not null)
      */
-    public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent);
+    public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent, final Optional<StreamsQuery> newQueryState);
 }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e355f73a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
index 76c3216..3b3d48a 100644
--- a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
+++ b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
@@ -165,13 +165,14 @@ public class InMemoryQueryRepositoryTest {
             // Add a query to it.
             final StreamsQuery query = queries.add("query 1", true);
 
-            final Set<StreamsQuery> existing = queries.subscribe(new QueryChangeLogListener() {
-                @Override
-                public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {
-                    final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(1L,
-                            QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
-                    assertEquals(expected, queryChangeEvent);
-                }
+            final Set<StreamsQuery> existing = queries.subscribe((queryChangeEvent, newQueryState) -> {
+                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(1L,
+                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                final Optional<StreamsQuery> expectedQueryState = Optional.of(
+                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+
+                assertEquals(expected, queryChangeEvent);
+                assertEquals(expectedQueryState, newQueryState);
             });
 
             assertEquals(Sets.newHashSet(query), existing);
@@ -195,26 +196,28 @@ public class InMemoryQueryRepositoryTest {
 
             //show listener on repo that query was added to is being notified of the new query.
             final CountDownLatch repo1Latch = new CountDownLatch(1);
-            queries.subscribe(new QueryChangeLogListener() {
-                @Override
-                public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {
-                    final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
-                            QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
-                    assertEquals(expected, queryChangeEvent);
-                    repo1Latch.countDown();
-                }
+            queries.subscribe((queryChangeEvent, newQueryState) -> {
+                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
+                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                final Optional<StreamsQuery> expectedQueryState = Optional.of(
+                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+
+                assertEquals(expected, queryChangeEvent);
+                assertEquals(expectedQueryState, newQueryState);
+                repo1Latch.countDown();
             });
 
             //show listener not on the repo that query was added to is being notified as well.
             final CountDownLatch repo2Latch = new CountDownLatch(1);
-            queries2.subscribe(new QueryChangeLogListener() {
-                @Override
-                public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {
-                    final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
-                            QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
-                    assertEquals(expected, queryChangeEvent);
-                    repo2Latch.countDown();
-                }
+            queries2.subscribe((queryChangeEvent, newQueryState) -> {
+                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
+                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                final Optional<StreamsQuery> expectedQueryState = Optional.of(
+                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+
+                assertEquals(expected, queryChangeEvent);
+                assertEquals(expectedQueryState, newQueryState);
+                repo2Latch.countDown();
             });
 
             queries.add("query 2", true);
@@ -222,7 +225,6 @@ public class InMemoryQueryRepositoryTest {
             assertTrue(repo1Latch.await(5, TimeUnit.SECONDS));
             assertTrue(repo2Latch.await(5, TimeUnit.SECONDS));
         } catch(final InterruptedException e ) {
-            System.out.println("PING");
         } finally {
             queries.stop();
             queries2.stop();
@@ -233,10 +235,7 @@ public class InMemoryQueryRepositoryTest {
     public void subscribe_notStarted() throws Exception {
         // Setup a totally in memory QueryRepository.
         final QueryRepository queries = new InMemoryQueryRepository(new InMemoryQueryChangeLog(), SCHEDULE);
-        queries.subscribe(new QueryChangeLogListener() {
-            @Override
-            public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {}
-        });
+        queries.subscribe((queryChangeEvent, newQueryState) -> {});
 
         queries.add("query 2", true);
     }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e355f73a/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
index d321ab5..2141a3a 100644
--- a/extras/rya.streams/query-manager/pom.xml
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -39,7 +39,7 @@ under the License.
             <groupId>org.apache.rya</groupId>
             <artifactId>rya.streams.kafka</artifactId>
         </dependency>
-        
+
         <!-- Apache Daemon dependencies -->
         <dependency>
             <groupId>commons-daemon</groupId>

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e355f73a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java
new file mode 100644
index 0000000..30b4538
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java
@@ -0,0 +1,255 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import static java.util.Objects.requireNonNull;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.api.queries.ChangeLogEntry;
+import org.apache.rya.streams.api.queries.InMemoryQueryRepository;
+import org.apache.rya.streams.api.queries.QueryChange;
+import org.apache.rya.streams.api.queries.QueryChange.ChangeType;
+import org.apache.rya.streams.api.queries.QueryChangeLog;
+import org.apache.rya.streams.api.queries.QueryChangeLogListener;
+import org.apache.rya.streams.api.queries.QueryRepository;
+import org.apache.rya.streams.querymanager.QueryChangeLogSource.SourceListener;
+import org.apache.rya.streams.querymanager.QueryExecutor.QueryExecutorException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.util.concurrent.AbstractIdleService;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * A service for managing {@link StreamsQuery} running on a Rya Streams system.
+ * <p>
+ * Only one QueryManager needs to be running to manage any number of rya
+ * instances/rya streams instances.
+ */
+@DefaultAnnotation(NonNull.class)
+public class QueryManager extends AbstractIdleService {
+    private static final Logger LOG = LoggerFactory.getLogger(QueryManager.class);
+
+    private final QueryExecutor queryExecutor;
+    private final Scheduler scheduler;
+
+    /**
+     * Map of Rya Instance name to {@link QueryRepository}.
+     */
+    private final Map<String, QueryRepository> queryRepos = new HashMap<>();
+
+    private final ReentrantLock lock = new ReentrantLock();
+
+    private final QueryChangeLogSource source;
+
+    /**
+     * Creates a new {@link QueryManager}.
+     *
+     * @param queryExecutor - Runs the active {@link StreamsQuery}s. (not null)
+     * @param source - The {@link QueryChangeLogSource} of QueryChangeLogs. (not null)
+     * @param scheduler - The {@link Scheduler} used to discover query changes
+     *      within the {@link QueryChangeLog}s (not null)
+     */
+    public QueryManager(final QueryExecutor queryExecutor, final QueryChangeLogSource source, final Scheduler scheduler) {
+        this.source = requireNonNull(source);
+        this.queryExecutor = requireNonNull(queryExecutor);
+        this.scheduler = requireNonNull(scheduler);
+    }
+
+    /**
+     * Starts running a query.
+     *
+     * @param ryaInstanceName - The Rya instance the query belongs to. (not null)
+     * @param query - The query to run.(not null)
+     */
+    private void runQuery(final String ryaInstanceName, final StreamsQuery query) {
+        requireNonNull(ryaInstanceName);
+        requireNonNull(query);
+        LOG.info("Starting Query: " + query.toString() + " on the rya instance: " + ryaInstanceName);
+
+        try {
+            queryExecutor.startQuery(ryaInstanceName, query);
+        } catch (final QueryExecutorException e) {
+            LOG.error("Failed to start query.", e);
+        }
+    }
+
+    /**
+     * Stops the specified query from running.
+     *
+     * @param queryId - The ID of the query to stop running. (not null)
+     */
+    private void stopQuery(final UUID queryId) {
+        requireNonNull(queryId);
+
+        LOG.info("Stopping query: " + queryId.toString());
+
+        try {
+            queryExecutor.stopQuery(queryId);
+        } catch (final QueryExecutorException e) {
+            LOG.error("Failed to stop query.", e);
+        }
+    }
+
+    @Override
+    protected void startUp() throws Exception {
+        lock.lock();
+        try {
+            LOG.info("Starting Query Manager.");
+            queryExecutor.startAndWait();
+            source.startAndWait();
+
+            // subscribe to the sources to be notified of changes.
+            source.subscribe(new QueryManagerSourceListener());
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    protected void shutDown() throws Exception {
+        lock.lock();
+        try {
+            LOG.info("Stopping Query Manager.");
+            source.stopAndWait();
+            queryExecutor.stopAndWait();
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * An implementation of {@link QueryChangeLogListener} for the
+     * {@link QueryManager}.
+     * <p>
+     * When notified of a {@link ChangeType} performs one of the following:
+     * <li>{@link ChangeType#CREATE}: Creates a new query using the
+     * {@link QueryExecutor} provided to the {@link QueryManager}</li>
+     * <li>{@link ChangeType#DELETE}: Deletes a running query by stopping the
+     * {@link QueryExecutor} service of the queryID in the event</li>
+     * <li>{@link ChangeType#UPDATE}: If the query is running and the update is
+     * to stop the query, stops the query. Otherwise, if the query is not
+     * running, it is removed.</li>
+     */
+    private class QueryExecutionForwardingListener implements QueryChangeLogListener {
+        private final String ryaInstanceName;
+
+        /**
+         * Creates a new {@link QueryExecutionForwardingListener}.
+         *
+         * @param ryaInstanceName - The rya instance the query change is
+         *        performed on. (not null)
+         */
+        public QueryExecutionForwardingListener(final String ryaInstanceName) {
+            this.ryaInstanceName = requireNonNull(ryaInstanceName);
+        }
+
+        @Override
+        public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent, final Optional<StreamsQuery> newQueryState) {
+            LOG.debug("New query change event.");
+            final QueryChange entry = queryChangeEvent.getEntry();
+
+            lock.lock();
+            try {
+
+                switch (entry.getChangeType()) {
+                    case CREATE:
+                        if(!newQueryState.isPresent()) {
+                            LOG.error("The query with ID: " + entry.getQueryId() + " must be present with the change to be created.");
+                            LOG.debug("newQueryState is not allowed to be absent with a CREATE QueryChange, there might be a bug in the QueryRepository.");
+                        } else {
+                            runQuery(ryaInstanceName, newQueryState.get());
+                        }
+                        break;
+                    case DELETE:
+                        stopQuery(entry.getQueryId());
+                        break;
+                    case UPDATE:
+                        if (!newQueryState.isPresent()) {
+                            LOG.error("The query with ID: " + entry.getQueryId() + " must be provided with the update, cannot perform update.");
+                            LOG.debug("newQueryState is not allowed to be absent with a UPDATE QueryChange, there might be a bug in the QueryRepository.");
+                        } else {
+                            final StreamsQuery updatedQuery = newQueryState.get();
+                            if (updatedQuery.isActive()) {
+                                runQuery(ryaInstanceName, updatedQuery);
+                                LOG.info("Starting query: " + updatedQuery.toString());
+                            } else {
+                                stopQuery(updatedQuery.getQueryId());
+                                LOG.info("Stopping query: " + updatedQuery.toString());
+                            }
+                        }
+                        break;
+                }
+            } finally {
+                lock.unlock();
+            }
+        }
+    }
+
+    /**
+     * Listener used by the {@link QueryManager} to be notified when
+     * {@link QueryChangeLog}s are created or deleted.
+     */
+    private class QueryManagerSourceListener implements SourceListener {
+        @Override
+        public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
+            lock.lock();
+            try {
+                LOG.info("Discovered new Query Change Log for Rya Instance " + ryaInstanceName + ".");
+                final QueryRepository repo = new InMemoryQueryRepository(log, scheduler);
+                repo.startAndWait();
+                final Set<StreamsQuery> queries = repo.subscribe(new QueryExecutionForwardingListener(ryaInstanceName));
+                queries.forEach(query -> {
+                    if (query.isActive()) {
+                        try {
+                            queryExecutor.startQuery(ryaInstanceName, query);
+                        } catch (IllegalStateException | QueryExecutorException e) {
+                            LOG.error("Unable to start query for rya instance " + ryaInstanceName, e);
+                        }
+                    }
+                });
+                queryRepos.put(ryaInstanceName, repo);
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        @Override
+        public void notifyDelete(final String ryaInstanceName) {
+            lock.lock();
+            try {
+                LOG.info("Notified of deleting QueryChangeLog, stopping all queries belonging to the change log for "
+                        + ryaInstanceName + ".");
+                queryExecutor.stopAll(ryaInstanceName);
+            } catch (final QueryExecutorException e) {
+                LOG.error("Failed to stop all queries belonging to: " + ryaInstanceName, e);
+            } finally {
+                lock.unlock();
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e355f73a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
new file mode 100644
index 0000000..a1203a0
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.api.queries.InMemoryQueryChangeLog;
+import org.apache.rya.streams.api.queries.QueryChange;
+import org.apache.rya.streams.api.queries.QueryChangeLog;
+import org.apache.rya.streams.querymanager.QueryChangeLogSource.SourceListener;
+import org.junit.Test;
+
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
+/**
+ * Test for the {@link QueryManager}
+ */
+public class QueryManagerTest {
+    private static final Scheduler TEST_SCHEDULER = Scheduler.newFixedRateSchedule(0, 100, TimeUnit.MILLISECONDS);
+
+    /**
+     * Tests when the query manager is notified to create a new query, the query
+     * is created and started.
+     */
+    @Test
+    public void testCreateQuery() throws Exception {
+        //The new QueryChangeLog
+        final QueryChangeLog newChangeLog = new InMemoryQueryChangeLog();
+        final String ryaInstance = "ryaTestInstance";
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true);
+
+        // when the query executor is told to start the test query on the test
+        // rya instance, count down on the countdown latch
+        final QueryExecutor qe = mock(QueryExecutor.class);
+        when(qe.isRunning()).thenReturn(true);
+
+        final CountDownLatch queryStarted = new CountDownLatch(1);
+        doAnswer(invocation -> {
+            queryStarted.countDown();
+            return null;
+        }).when(qe).startQuery(eq(ryaInstance), eq(query));
+        final QueryChangeLogSource source = mock(QueryChangeLogSource.class);
+
+        //When the QueryChangeLogSource is subscribed to in the QueryManager, mock notify of a new QueryChangeLog
+        doAnswer(invocation -> {
+            //The listener created by the Query Manager
+            final SourceListener listener = (SourceListener) invocation.getArguments()[0];
+            listener.notifyCreate(ryaInstance, newChangeLog);
+            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive()));
+            return null;
+        }).when(source).subscribe(any(SourceListener.class));
+
+        final QueryManager qm = new QueryManager(qe, source, TEST_SCHEDULER);
+        try {
+            qm.startAndWait();
+            queryStarted.await(5, TimeUnit.SECONDS);
+            verify(qe).startQuery(ryaInstance, query);
+        } finally {
+            qm.stopAndWait();
+        }
+    }
+
+    /**
+     * Tests when the query manager is notified to delete a new query, the query
+     * is stopped and deleted.
+     */
+    @Test
+    public void testDeleteQuery() throws Exception {
+        //The new QueryChangeLog
+        final QueryChangeLog newChangeLog = new InMemoryQueryChangeLog();
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true);
+        final String ryaInstance = "ryaTestInstance";
+
+        // when the query executor is told to start the test query on the test
+        // rya instance, count down on the countdown latch
+        final QueryExecutor qe = mock(QueryExecutor.class);
+        when(qe.isRunning()).thenReturn(true);
+
+        final CountDownLatch queryStarted = new CountDownLatch(1);
+        final CountDownLatch queryDeleted = new CountDownLatch(1);
+        doAnswer(invocation -> {
+            queryDeleted.countDown();
+            return null;
+        }).when(qe).stopQuery(query.getQueryId());
+        final QueryChangeLogSource source = mock(QueryChangeLogSource.class);
+
+        // when the query executor is told to start the test query on the test
+        // rya instance, count down on the countdown latch
+        doAnswer(invocation -> {
+            queryStarted.countDown();
+            return null;
+        }).when(qe).startQuery(eq(ryaInstance), eq(query));
+
+        //When the QueryChangeLogSource is subscribed to in the QueryManager, mock notify of a new QueryChangeLog
+        // add the query, so it can be removed
+        doAnswer(invocation -> {
+            //The listener created by the Query Manager
+            final SourceListener listener = (SourceListener) invocation.getArguments()[0];
+            listener.notifyCreate(ryaInstance, newChangeLog);
+            Thread.sleep(1000);
+            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive()));
+            queryStarted.await(5, TimeUnit.SECONDS);
+            newChangeLog.write(QueryChange.delete(query.getQueryId()));
+            return null;
+        }).when(source).subscribe(any(SourceListener.class));
+
+        final QueryManager qm = new QueryManager(qe, source, TEST_SCHEDULER);
+        try {
+            qm.startAndWait();
+            queryDeleted.await(5, TimeUnit.SECONDS);
+            verify(qe).stopQuery(query.getQueryId());
+        } finally {
+            qm.stopAndWait();
+        }
+    }
+
+    /**
+     * Tests when the query manager is notified to update an existing query, the
+     * query is stopped.
+     */
+    @Test
+    public void testUpdateQuery() throws Exception {
+        // The new QueryChangeLog
+        final QueryChangeLog newChangeLog = new InMemoryQueryChangeLog();
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true);
+        final String ryaInstance = "ryaTestInstance";
+
+        // when the query executor is told to start the test query on the test
+        // rya instance, count down on the countdown latch
+        final QueryExecutor qe = mock(QueryExecutor.class);
+        when(qe.isRunning()).thenReturn(true);
+
+        final CountDownLatch queryStarted = new CountDownLatch(1);
+        final CountDownLatch queryDeleted = new CountDownLatch(1);
+        doAnswer(invocation -> {
+            queryDeleted.countDown();
+            return null;
+        }).when(qe).stopQuery(query.getQueryId());
+        final QueryChangeLogSource source = mock(QueryChangeLogSource.class);
+
+        // when the query executor is told to start the test query on the test
+        // rya instance, count down on the countdown latch
+        doAnswer(invocation -> {
+            queryStarted.countDown();
+            return null;
+        }).when(qe).startQuery(eq(ryaInstance), eq(query));
+
+        // When the QueryChangeLogSource is subscribed to in the QueryManager,
+        // mock notify of a new QueryChangeLog
+        // add the query, so it can be removed
+        doAnswer(invocation -> {
+            // The listener created by the Query Manager
+            final SourceListener listener = (SourceListener) invocation.getArguments()[0];
+            listener.notifyCreate(ryaInstance, newChangeLog);
+            Thread.sleep(1000);
+            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive()));
+            queryStarted.await(5, TimeUnit.SECONDS);
+            newChangeLog.write(QueryChange.update(query.getQueryId(), false));
+            return null;
+        }).when(source).subscribe(any(SourceListener.class));
+
+        final QueryManager qm = new QueryManager(qe, source, TEST_SCHEDULER);
+        try {
+            qm.startAndWait();
+            queryDeleted.await(10, TimeUnit.SECONDS);
+            verify(qe).stopQuery(query.getQueryId());
+        } finally {
+            qm.stopAndWait();
+        }
+    }
+}


[20/22] incubator-rya git commit: RYA-463 RYA-464 Added an isInsert flag to StreamsQuery to indicate when the results of a query need to be inserted back into Rya.

Posted by pu...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/shell/src/test/java/org/apache/rya/shell/RyaStreamsCommandsTest.java
----------------------------------------------------------------------
diff --git a/extras/shell/src/test/java/org/apache/rya/shell/RyaStreamsCommandsTest.java b/extras/shell/src/test/java/org/apache/rya/shell/RyaStreamsCommandsTest.java
index 9f5a794..2759c33 100644
--- a/extras/shell/src/test/java/org/apache/rya/shell/RyaStreamsCommandsTest.java
+++ b/extras/shell/src/test/java/org/apache/rya/shell/RyaStreamsCommandsTest.java
@@ -36,6 +36,7 @@ import org.apache.rya.api.client.SetRyaStreamsConfiguration;
 import org.apache.rya.api.client.accumulo.AccumuloConnectionDetails;
 import org.apache.rya.api.instance.RyaDetails;
 import org.apache.rya.api.instance.RyaDetails.RyaStreamsDetails;
+import org.apache.rya.shell.util.ConsolePrinter;
 import org.apache.rya.shell.util.SparqlPrompt;
 import org.apache.rya.streams.api.RyaStreamsClient;
 import org.apache.rya.streams.api.entity.StreamsQuery;
@@ -72,7 +73,7 @@ public class RyaStreamsCommandsTest {
 
         try {
             // Execute the command.
-            final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+            final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
             final String message = commands.configureRyaStreams("localhost", 6);
 
             // Verify the request was forwarded to the mocked interactor.
@@ -107,7 +108,7 @@ public class RyaStreamsCommandsTest {
         state.connectedToInstance("unitTest");
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.printRyaStreamsDetails();
         final String expected = "This instance does not have any Rya Details, so it is unable to be connected to the Rya Streams subsystem.";
         assertEquals(expected, message);
@@ -131,7 +132,7 @@ public class RyaStreamsCommandsTest {
         state.connectedToInstance("unitTest");
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.printRyaStreamsDetails();
         final String expected = "This instance of Rya has not been configured to use a Rya Streams subsystem.";
         assertEquals(expected, message);
@@ -155,7 +156,7 @@ public class RyaStreamsCommandsTest {
         state.connectedToInstance("unitTest");
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.printRyaStreamsDetails();
         final String expected = "Kafka Hostname: localhost, Kafka Port: 6";
         assertEquals(expected, message);
@@ -179,26 +180,119 @@ public class RyaStreamsCommandsTest {
         state.connectedToRyaStreams(mockClient);
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt);
-        final String message = commands.addQuery(false);
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
+        final String message = commands.addQuery(false, false);
 
         // Verify a message is printed to the user.
         assertEquals("", message);
     }
 
     @Test
-    public void addQuery() throws Exception {
+    public void addQuery_doNotInsertQuery() throws Exception {
         // Mock the object that performs the rya streams operation.
         final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
         final AddQuery addQuery = mock(AddQuery.class);
         when(mockClient.getAddQuery()).thenReturn(addQuery);
 
-        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), "query", true);
-        when(addQuery.addQuery(eq("query"), eq(true))).thenReturn(addedQuery);
+        final String sparql = "SELECT * WHERE { ?a ?b ?c }";
+
+        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, false);
+        when(addQuery.addQuery(eq(sparql), eq(true), eq(false))).thenReturn(addedQuery);
+
+        // Mock a SPARQL prompt that a user entered a query through.
+        final SparqlPrompt prompt = mock(SparqlPrompt.class);
+        when(prompt.getSparql()).thenReturn(Optional.of(sparql));
+
+        // Mock a shell state and connect it to a Rya instance.
+        final SharedShellState state = new SharedShellState();
+        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
+        state.connectedToInstance("unitTest");
+        state.connectedToRyaStreams(mockClient);
+
+        // Execute the command.
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
+        final String message = commands.addQuery(false, false);
+
+        // Verify the interactor was invoked with the provided input.
+        verify(addQuery).addQuery(sparql, true, false);
+
+        // Verify a message is printed to the user.
+        final String expected = "The added query's ID is " + addedQuery.getQueryId();
+        assertEquals(expected, message);
+    }
+
+    @Test
+    public void addQuery_insertConstructQuery() throws Exception {
+        // Mock the object that performs the rya streams operation.
+        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
+        final AddQuery addQuery = mock(AddQuery.class);
+        when(mockClient.getAddQuery()).thenReturn(addQuery);
+
+        final String sparql =
+                "PREFIX vCard: <http://www.w3.org/2001/vcard-rdf/3.0#> " +
+                "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
+                "CONSTRUCT { " +
+                    "?X vCard:FN ?name . " +
+                    "?X vCard:URL ?url . " +
+                    "?X vCard:TITLE ?title . " +
+                "} " +
+                "FROM <http://www.w3.org/People/Berners-Lee/card> " +
+                "WHERE { " +
+                    "OPTIONAL { ?X foaf:name ?name . FILTER isLiteral(?name) . } " +
+                    "OPTIONAL { ?X foaf:homepage ?url . FILTER isURI(?url) . } " +
+                    "OPTIONAL { ?X foaf:title ?title . FILTER isLiteral(?title) . } " +
+                "}";
+
+        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, true);
+        when(addQuery.addQuery(eq(sparql), eq(false), eq(true))).thenReturn(addedQuery);
+
+        // Mock a SPARQL prompt that a user entered a query through.
+        final SparqlPrompt prompt = mock(SparqlPrompt.class);
+        when(prompt.getSparql()).thenReturn(Optional.of(sparql));
+
+        // Mock a shell state and connect it to a Rya instance.
+        final SharedShellState state = new SharedShellState();
+        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
+        state.connectedToInstance("unitTest");
+        state.connectedToRyaStreams(mockClient);
+
+        // Execute the command.
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
+        final String message = commands.addQuery(true, true);
+
+        // Verify the interactor was invoked with the provided input.
+        verify(addQuery).addQuery(sparql, false, true);
+
+        // Verify a message is printed to the user.
+        final String expected = "The added query's ID is " + addedQuery.getQueryId();
+        assertEquals(expected, message);
+    }
+
+    @Test
+    public void addQuery_doNotInsertInsertUpdate() throws Exception {
+        // Mock the object that performs the rya streams operation.
+        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
+        final AddQuery addQuery = mock(AddQuery.class);
+        when(mockClient.getAddQuery()).thenReturn(addQuery);
+
+        final String sparql =
+                "PREFIX Sensor: <http://example.com/Equipment.owl#> " +
+                "INSERT { " +
+                    "?subject Sensor:test2 ?newValue " +
+                "} WHERE {" +
+                    "values (?oldValue ?newValue) {" +
+                        "('testValue1' 'newValue1')" +
+                        "('testValue2' 'newValue2')" +
+                    "}" +
+                    "?subject Sensor:test1 ?oldValue" +
+                "}";
+
+        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, false);
+        when(addQuery.addQuery(eq(sparql), eq(false), eq(false))).thenReturn(addedQuery);
 
         // Mock a SPARQL prompt that a user entered a query through.
         final SparqlPrompt prompt = mock(SparqlPrompt.class);
-        when(prompt.getSparql()).thenReturn(Optional.of("query"));
+        when(prompt.getSparql()).thenReturn(Optional.of(sparql));
 
         // Mock a shell state and connect it to a Rya instance.
         final SharedShellState state = new SharedShellState();
@@ -207,17 +301,44 @@ public class RyaStreamsCommandsTest {
         state.connectedToRyaStreams(mockClient);
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt);
-        final String message = commands.addQuery(false);
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
+        final String message = commands.addQuery(true, false);
 
         // Verify the interactor was invoked with the provided input.
-        verify(addQuery).addQuery("query", true);
+        verify(addQuery).addQuery(sparql, false, false);
 
         // Verify a message is printed to the user.
         final String expected = "The added query's ID is " + addedQuery.getQueryId();
         assertEquals(expected, message);
     }
 
+    @Test(expected = RuntimeException.class)
+    public void addQuery_insertQueryNotCorrectType() throws Exception {
+        // Mock the object that performs the rya streams operation.
+        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
+        final AddQuery addQuery = mock(AddQuery.class);
+        when(mockClient.getAddQuery()).thenReturn(addQuery);
+
+        final String sparql = "SELECT * WHERE { ?a ?b ?c }";
+
+        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, true);
+        when(addQuery.addQuery(eq(sparql), eq(false), eq(true))).thenReturn(addedQuery);
+
+        // Mock a SPARQL prompt that a user entered a query through.
+        final SparqlPrompt prompt = mock(SparqlPrompt.class);
+        when(prompt.getSparql()).thenReturn(Optional.of(sparql));
+
+        // Mock a shell state and connect it to a Rya instance.
+        final SharedShellState state = new SharedShellState();
+        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
+        state.connectedToInstance("unitTest");
+        state.connectedToRyaStreams(mockClient);
+
+        // Execute the command.
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
+        commands.addQuery(true, true);
+    }
+
     @Test
     public void deleteQuery() throws Exception {
         // Mock the object that performs the rya streams operation.
@@ -232,7 +353,7 @@ public class RyaStreamsCommandsTest {
         state.connectedToRyaStreams(mockClient);
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final UUID queryId = UUID.randomUUID();
         final String message = commands.deleteQuery(queryId.toString());
 
@@ -261,10 +382,10 @@ public class RyaStreamsCommandsTest {
 
         // Report the query as not running.
         final UUID queryId = UUID.randomUUID();
-        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", false)));
+        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", false, false)));
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.startQuery(queryId.toString());
 
         // Verify the interactor was invoked with the provided parameters.
@@ -292,10 +413,10 @@ public class RyaStreamsCommandsTest {
 
         // Report the query as running.
         final UUID queryId = UUID.randomUUID();
-        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", true)));
+        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", true, false)));
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.startQuery(queryId.toString());
 
         // Verify the interactor was not invoked.
@@ -323,10 +444,10 @@ public class RyaStreamsCommandsTest {
 
         // Report the query as running.
         final UUID queryId = UUID.randomUUID();
-        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", true)));
+        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", true, false)));
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.stopQuery(queryId.toString());
 
         // Verify the interactor was invoked with the provided parameters.
@@ -354,10 +475,10 @@ public class RyaStreamsCommandsTest {
 
         // Report the query as not running.
         final UUID queryId = UUID.randomUUID();
-        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", false)));
+        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", false, false)));
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.stopQuery(queryId.toString());
 
         // Verify the interactor was not invoked with the provided parameters.
@@ -379,15 +500,15 @@ public class RyaStreamsCommandsTest {
                 new StreamsQuery(
                         UUID.fromString("33333333-3333-3333-3333-333333333333"),
                         "SELECT * WHERE { ?person <urn:worksAt> ?business . }",
-                        true),
+                        true, false),
                 new StreamsQuery(
                         UUID.fromString("11111111-1111-1111-1111-111111111111"),
                         "SELECT * WHERE { ?a ?b ?c . }",
-                        true),
+                        true, false),
                 new StreamsQuery(
                         UUID.fromString("22222222-2222-2222-2222-222222222222"),
                         "SELECT * WHERE { ?d ?e ?f . }",
-                        false));
+                        false, false));
         when(listQueries.all()).thenReturn(queries);
 
         // Mock a shell state and connect it to a Rya instance.
@@ -397,7 +518,7 @@ public class RyaStreamsCommandsTest {
         state.connectedToRyaStreams(mockClient);
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.listQueries();
 
         // Verify the correct report is returned.
@@ -405,6 +526,7 @@ public class RyaStreamsCommandsTest {
                 "-----------------------------------------------\n" +
                 " Query ID: 11111111-1111-1111-1111-111111111111\n" +
                 "Is Active: true\n" +
+                "Is Insert: false\n" +
                 "   SPARQL: select ?a ?b ?c\n" +
                 "           where {\n" +
                 "             ?a ?b ?c.\n" +
@@ -412,6 +534,7 @@ public class RyaStreamsCommandsTest {
                 "-----------------------------------------------\n" +
                 " Query ID: 22222222-2222-2222-2222-222222222222\n" +
                 "Is Active: false\n" +
+                "Is Insert: false\n" +
                 "   SPARQL: select ?d ?e ?f\n" +
                 "           where {\n" +
                 "             ?d ?e ?f.\n" +
@@ -419,6 +542,7 @@ public class RyaStreamsCommandsTest {
                 "-----------------------------------------------\n" +
                 " Query ID: 33333333-3333-3333-3333-333333333333\n" +
                 "Is Active: true\n" +
+                "Is Insert: false\n" +
                 "   SPARQL: select ?person ?business\n" +
                 "           where {\n" +
                 "             ?person <urn:worksAt> ?business.\n" +
@@ -435,7 +559,7 @@ public class RyaStreamsCommandsTest {
         when(mockClient.getGetQuery()).thenReturn(getQuery);
 
         final UUID queryId = UUID.fromString("da55cea5-c21c-46a5-ab79-5433eef4efaa");
-        final StreamsQuery query = new StreamsQuery(queryId, "SELECT * WHERE { ?a ?b ?c . }", true);
+        final StreamsQuery query = new StreamsQuery(queryId, "SELECT * WHERE { ?a ?b ?c . }", true, false);
         when(getQuery.getQuery(queryId)).thenReturn(java.util.Optional.of(query));
 
         // Mock a shell state and connect it to a Rya instance.
@@ -445,13 +569,14 @@ public class RyaStreamsCommandsTest {
         state.connectedToRyaStreams(mockClient);
 
         // Execute the command.
-        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class));
+        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
         final String message = commands.printQueryDetails(queryId.toString());
 
         // Verify the correct report is returned.
         final String expected =
                 " Query ID: da55cea5-c21c-46a5-ab79-5433eef4efaa\n" +
                 "Is Active: true\n" +
+                "Is Insert: false\n" +
                 "   SPARQL: select ?a ?b ?c\n" +
                 "           where {\n" +
                 "             ?a ?b ?c.\n" +

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/shell/src/test/java/org/apache/rya/shell/util/StreamsQueryFormatterTest.java
----------------------------------------------------------------------
diff --git a/extras/shell/src/test/java/org/apache/rya/shell/util/StreamsQueryFormatterTest.java b/extras/shell/src/test/java/org/apache/rya/shell/util/StreamsQueryFormatterTest.java
index 8e5d251..594a002 100644
--- a/extras/shell/src/test/java/org/apache/rya/shell/util/StreamsQueryFormatterTest.java
+++ b/extras/shell/src/test/java/org/apache/rya/shell/util/StreamsQueryFormatterTest.java
@@ -39,13 +39,14 @@ public class StreamsQueryFormatterTest {
         final StreamsQuery query = new StreamsQuery(
                 UUID.fromString("da55cea5-c21c-46a5-ab79-5433eef4efaa"),
                 "SELECT * WHERE { ?a ?b ?c . }",
-                true);
+                true, false);
         final String formatted = StreamsQueryFormatter.format(query);
 
         // Ensure it has the expected format.
         final String expected =
                 " Query ID: da55cea5-c21c-46a5-ab79-5433eef4efaa\n" +
                 "Is Active: true\n" +
+                "Is Insert: false\n" +
                 "   SPARQL: select ?a ?b ?c\n" +
                 "           where {\n" +
                 "             ?a ?b ?c.\n" +
@@ -61,15 +62,15 @@ public class StreamsQueryFormatterTest {
                 new StreamsQuery(
                         UUID.fromString("33333333-3333-3333-3333-333333333333"),
                         "SELECT * WHERE { ?person <urn:worksAt> ?business . }",
-                        true),
+                        true, true),
                 new StreamsQuery(
                         UUID.fromString("11111111-1111-1111-1111-111111111111"),
                         "SELECT * WHERE { ?a ?b ?c . }",
-                        true),
+                        true, false),
                 new StreamsQuery(
                         UUID.fromString("22222222-2222-2222-2222-222222222222"),
                         "SELECT * WHERE { ?d ?e ?f . }",
-                        false));
+                        false, true));
 
         final String formatted = StreamsQueryFormatter.format(queries);
 
@@ -78,6 +79,7 @@ public class StreamsQueryFormatterTest {
                 "-----------------------------------------------\n" +
                 " Query ID: 11111111-1111-1111-1111-111111111111\n" +
                 "Is Active: true\n" +
+                "Is Insert: false\n" +
                 "   SPARQL: select ?a ?b ?c\n" +
                 "           where {\n" +
                 "             ?a ?b ?c.\n" +
@@ -85,6 +87,7 @@ public class StreamsQueryFormatterTest {
                 "-----------------------------------------------\n" +
                 " Query ID: 22222222-2222-2222-2222-222222222222\n" +
                 "Is Active: false\n" +
+                "Is Insert: true\n" +
                 "   SPARQL: select ?d ?e ?f\n" +
                 "           where {\n" +
                 "             ?d ?e ?f.\n" +
@@ -92,6 +95,7 @@ public class StreamsQueryFormatterTest {
                 "-----------------------------------------------\n" +
                 " Query ID: 33333333-3333-3333-3333-333333333333\n" +
                 "Is Active: true\n" +
+                "Is Insert: true\n" +
                 "   SPARQL: select ?person ?business\n" +
                 "           where {\n" +
                 "             ?person <urn:worksAt> ?business.\n" +


[21/22] incubator-rya git commit: RYA-463 RYA-464 Added an isInsert flag to StreamsQuery to indicate when the results of a query need to be inserted back into Rya.

Posted by pu...@apache.org.
RYA-463 RYA-464 Added an isInsert flag to StreamsQuery to indicate when the results of a query need to be inserted back into Rya.

Conflicts:
	common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
	common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
	extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
	extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
	extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/010c6927
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/010c6927
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/010c6927

Branch: refs/heads/master
Commit: 010c6927647efccc9b19485ef0a931ea20846d8a
Parents: e07390d
Author: kchilton2 <ke...@gmail.com>
Authored: Thu Feb 8 17:53:41 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 13:00:05 2018 -0500

----------------------------------------------------------------------
 .../apache/rya/api/utils/QueryInvestigator.java |   2 +-
 .../rya/api/utils/QueryInvestigatorTest.java    |   2 +-
 .../rya/streams/api/entity/StreamsQuery.java    |  40 ++--
 .../rya/streams/api/interactor/AddQuery.java    |   4 +-
 .../interactor/defaults/DefaultAddQuery.java    |   4 +-
 .../api/queries/InMemoryQueryRepository.java    |  10 +-
 .../rya/streams/api/queries/QueryChange.java    |  35 +++-
 .../streams/api/queries/QueryRepository.java    |   6 +-
 .../defaults/DefaultAddQueryTest.java           |   6 +-
 .../queries/InMemoryQueryRepositoryTest.java    |  56 +++---
 .../streams/client/command/AddQueryCommand.java |  38 +++-
 .../client/command/ListQueriesCommand.java      |   7 +-
 .../client/command/AddQueryCommandIT.java       |  25 ++-
 .../client/command/DeleteQueryCommandIT.java    |  12 +-
 .../client/command/ListQueryCommandIT.java      |  12 +-
 .../client/command/RunQueryCommandIT.java       |   2 +-
 .../kafka/interactor/KafkaRunQueryIT.java       |   2 +-
 .../kafka/queries/KafkaQueryChangeLogIT.java    |   8 +-
 .../querymanager/LogEventWorkerTest.java        |  10 +-
 .../QueryEventWorkGeneratorTest.java            |  18 +-
 .../querymanager/QueryEventWorkerTest.java      |   2 +-
 .../streams/querymanager/QueryManagerTest.java  |  12 +-
 .../kafka/LocalQueryExecutorIT.java             |   2 +-
 .../kafka/LocalQueryExecutorTest.java           |  26 +--
 .../apache/rya/shell/RyaStreamsCommands.java    |  40 +++-
 .../rya/shell/util/StreamsQueryFormatter.java   |   1 +
 .../rya/shell/RyaStreamsCommandsTest.java       | 181 ++++++++++++++++---
 .../shell/util/StreamsQueryFormatterTest.java   |  12 +-
 28 files changed, 409 insertions(+), 166 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
----------------------------------------------------------------------
diff --git a/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java b/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
index 2fbd09b..a6c93e9 100644
--- a/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
+++ b/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
@@ -100,4 +100,4 @@ public class QueryInvestigator {
             }
         }
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
----------------------------------------------------------------------
diff --git a/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java b/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
index fbe2ebe..bedc59a 100644
--- a/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
+++ b/common/rya.api/src/test/java/org/apache/rya/api/utils/QueryInvestigatorTest.java
@@ -147,4 +147,4 @@ public class QueryInvestigatorTest {
     public void isInsert_false_malformed() throws MalformedQueryException {
         assertFalse( QueryInvestigator.isInsertWhere("not sparql") );
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
index 11423bd..76cf6af 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
@@ -35,6 +35,7 @@ public class StreamsQuery {
     private final UUID queryId;
     private final String sparql;
     private final boolean isActive;
+    private final boolean isInsert;
 
     /**
      * Constructs an instance of {@link StreamsQuery}.
@@ -42,11 +43,18 @@ public class StreamsQuery {
      * @param queryId - Uniquely identifies the query within Rya Streams. (not null)
      * @param sparql - The SPARQL query that defines how statements will be processed. (not null)
      * @param isActive - {@code true} if Rya Streams should process this query; otherwise {@code false}.
+     * @param isInsert - {@code true} if Rya Streams should insert the results of the query back into
+     *   the Rya instance the statements originated from; otherwise {@code false}.
      */
-    public StreamsQuery(final UUID queryId, final String sparql, final boolean isActive) {
+    public StreamsQuery(
+            final UUID queryId,
+            final String sparql,
+            final boolean isActive,
+            final boolean isInsert) {
         this.queryId = requireNonNull(queryId);
         this.sparql = requireNonNull(sparql);
         this.isActive = isActive;
+        this.isInsert = isInsert;
     }
 
     /**
@@ -70,9 +78,17 @@ public class StreamsQuery {
         return isActive;
     }
 
+    /**
+     * @return {@code true} if Rya Streams should insert the results of the query back into
+     *   the Rya instance the statements originated from; otherwise {@code false}.
+     */
+    public boolean isInsert() {
+        return isInsert;
+    }
+
     @Override
     public int hashCode() {
-        return Objects.hash(queryId, sparql, isActive);
+        return Objects.hash(queryId, sparql, isActive, isInsert);
     }
 
     @Override
@@ -81,23 +97,17 @@ public class StreamsQuery {
             final StreamsQuery other = (StreamsQuery) o;
             return Objects.equals(queryId, other.queryId) &&
                     Objects.equals(sparql, other.sparql) &&
-                    isActive == other.isActive;
+                    isActive == other.isActive &&
+                    isInsert == other.isInsert;
         }
         return false;
     }
 
     @Override
     public String toString() {
-        final StringBuilder sb = new StringBuilder();
-        sb.append("ID: ");
-        sb.append(getQueryId().toString() + "\n");
-        sb.append("Query: ");
-        sb.append(getSparql() + "\n");
-        sb.append("Is ");
-        if (!isActive) {
-            sb.append("Not ");
-        }
-        sb.append("Running.\n");
-        return sb.toString();
+        return "ID: " + queryId + "\n" +
+                "Query: " + sparql + "\n" +
+                "Is Active: " + isActive + "\n" +
+                "Is Insert: " + isInsert + "\n";
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/AddQuery.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/AddQuery.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/AddQuery.java
index 9889fd0..842399f 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/AddQuery.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/AddQuery.java
@@ -36,8 +36,10 @@ public interface AddQuery {
      * @param query - The SPARQL query that will be added. (not null)
      * @param isActive - {@code true} if the query needs to be maintained by
      *   Rya Streams; otherwise {@code false}.
+     * @param isInsert - {@code true} if the query's reuslts need to be inserted into
+     *   the Rya instance that originated the statements; otherwise {@code false}.
      * @return The {@link StreamsQuery} used by Rya Streams for this query.
      * @throws RyaStreamsException The query could not be added to Rya Streams.
      */
-    public StreamsQuery addQuery(final String query, boolean isActive) throws RyaStreamsException;
+    public StreamsQuery addQuery(final String query, boolean isActive, boolean isInsert) throws RyaStreamsException;
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQuery.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQuery.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQuery.java
index edd90fd..67edec0 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQuery.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQuery.java
@@ -49,7 +49,7 @@ public class DefaultAddQuery implements AddQuery {
     }
 
     @Override
-    public StreamsQuery addQuery(final String query, final boolean isActive) throws RyaStreamsException {
+    public StreamsQuery addQuery(final String query, final boolean isActive, final boolean isInsert) throws RyaStreamsException {
         requireNonNull(query);
 
         // Make sure the SPARQL is valid.
@@ -60,6 +60,6 @@ public class DefaultAddQuery implements AddQuery {
         }
 
         // If it is, then store it in the repository.
-        return repository.add(query, isActive);
+        return repository.add(query, isActive, isInsert);
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
index 95c1922..c71f0f8 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
@@ -92,7 +92,7 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
     }
 
     @Override
-    public StreamsQuery add(final String query, final boolean isActive)
+    public StreamsQuery add(final String query, final boolean isActive, final boolean isInsert)
             throws QueryRepositoryException, IllegalStateException {
         requireNonNull(query);
 
@@ -101,7 +101,7 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
             checkState();
             // First record the change to the log.
             final UUID queryId = UUID.randomUUID();
-            final QueryChange change = QueryChange.create(queryId, query, isActive);
+            final QueryChange change = QueryChange.create(queryId, query, isActive, isInsert);
             changeLog.write(change);
 
             // Update the cache to represent what is currently in the log.
@@ -235,7 +235,8 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
                         final StreamsQuery query = new StreamsQuery(
                                 queryId,
                                 change.getSparql().get(),
-                                change.getIsActive().get());
+                                change.getIsActive().get(),
+                                change.getIsInsert().get());
                         queriesCache.put(queryId, query);
                         break;
 
@@ -245,7 +246,8 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
                             final StreamsQuery updated = new StreamsQuery(
                                     old.getQueryId(),
                                     old.getSparql(),
-                                    change.getIsActive().get());
+                                    change.getIsActive().get(),
+                                    old.isInsert());
                             queriesCache.put(queryId, updated);
                         }
                         break;

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
index d34a394..fb58844 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
@@ -42,6 +42,7 @@ public final class QueryChange implements Serializable {
     private final ChangeType changeType;
     private final Optional<String> sparql;
     private final Optional<Boolean> isActive;
+    private final Optional<Boolean> isInsert;
 
     /**
      * Constructs an instance of {@link QueryChange}. Use the {@link #create(UUID, String)} or {@link #delete(UUID)}
@@ -52,16 +53,20 @@ public final class QueryChange implements Serializable {
      * @param sparql - If this is a create change, then the SPARQL query that will be evaluated within Rya Streams. (not null)
      * @param isActive - If this is a create or update change, then the active state that defines if the
      *   query will be evaluated by RyaStreams. (not null)
+     * @param isInsert - If this is a create change, then the insert state that defines if the
+     *   results of the query will be inserted back into the originating Rya store. (not null)
      */
     private QueryChange(
             final UUID queryId,
             final ChangeType changeType,
             final Optional<String> sparql,
-            final Optional<Boolean> isActive) {
+            final Optional<Boolean> isActive,
+            final Optional<Boolean> isInsert) {
         this.queryId = requireNonNull(queryId);
         this.changeType = requireNonNull(changeType);
         this.sparql = requireNonNull(sparql);
         this.isActive = requireNonNull(isActive);
+        this.isInsert = requireNonNull(isInsert);
     }
 
     /**
@@ -93,9 +98,17 @@ public final class QueryChange implements Serializable {
         return isActive;
     }
 
+    /**
+     * @return If this is a create change, then the insert state that defines if the
+     *   results of the query will be inserted back into the originating Rya store.
+     */
+    public Optional<Boolean> getIsInsert() {
+        return isInsert;
+    }
+
     @Override
     public int hashCode() {
-        return Objects.hash(queryId, changeType, sparql, isActive);
+        return Objects.hash(queryId, changeType, sparql, isActive, isInsert);
     }
 
     @Override
@@ -105,7 +118,8 @@ public final class QueryChange implements Serializable {
             return Objects.equals(queryId, change.queryId) &&
                     Objects.equals(changeType, change.changeType) &&
                     Objects.equals(sparql, change.sparql) &&
-                    Objects.equals(isActive, change.isActive);
+                    Objects.equals(isActive, change.isActive) &&
+                    Objects.equals(isInsert, change.isInsert);
         }
         return false;
     }
@@ -116,6 +130,7 @@ public final class QueryChange implements Serializable {
                "    Query ID: " + queryId + ",\n" +
                "    Change Type: " + changeType + ",\n" +
                "    Is Active: " + isActive + ",\n" +
+               "    Is Insert: " + isInsert + ",\n" +
                "    SPARQL: " + sparql + "\n" +
                "}";
     }
@@ -125,22 +140,24 @@ public final class QueryChange implements Serializable {
      *
      * @param queryId - Uniquely identifies the query within the streaming system. (not null)
      * @param sparql - The query that will be evaluated. (not null)
-     * @param isActive - The active state that defines if the query will be evaluated by RyaStreams. (not null)
+     * @param isActive - The active state that defines if the query will be evaluated by RyaStreams.
+     * @param isInsert - The insert state that defines if the query's results will be inserted back
+     *   into the Rya instance the originating statements came from.
      * @return A {@link QueryChange} built using the provided values.
      */
-    public static QueryChange create(final UUID queryId, final String sparql, final boolean isActive) {
-        return new QueryChange(queryId, ChangeType.CREATE, Optional.of(sparql), Optional.of(isActive));
+    public static QueryChange create(final UUID queryId, final String sparql, final boolean isActive, final boolean isInsert) {
+        return new QueryChange(queryId, ChangeType.CREATE, Optional.of(sparql), Optional.of(isActive), Optional.of(isInsert));
     }
 
     /**
      * Create a {@link QueryChange} that represents a query in Rya Streams whose active state has changed.
      *
      * @param queryId - Uniquely identifies the query within the streaming system. (not null)
-     * @param isActive - The active state that defines if the query will be evaluated by RyaStreams. (not null)
+     * @param isActive - The active state that defines if the query will be evaluated by RyaStreams.
      * @return A {@link QueryChange} built using the provided values.
      */
     public static QueryChange update(final UUID queryId, final boolean isActive) {
-        return new QueryChange(queryId, ChangeType.UPDATE, Optional.absent(), Optional.of(isActive));
+        return new QueryChange(queryId, ChangeType.UPDATE, Optional.absent(), Optional.of(isActive), Optional.absent());
     }
 
     /**
@@ -150,7 +167,7 @@ public final class QueryChange implements Serializable {
      * @return A {@link QueryChange} built using the provided values.
      */
     public static QueryChange delete(final UUID queryId) {
-        return new QueryChange(queryId, ChangeType.DELETE, Optional.absent(), Optional.absent());
+        return new QueryChange(queryId, ChangeType.DELETE, Optional.absent(), Optional.absent(), Optional.absent());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
index 4d8b2db..e4bcd7f 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
@@ -1,4 +1,4 @@
-/*
+/**
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -46,11 +46,13 @@ public interface QueryRepository extends Service {
      * @param query - The SPARQL query to add. (not null)
      * @param isActive - {@code true} if the query should be processed after it is added
      *   otherwise {@code false}.
+     * @param isInsert - {@code true} if the query's results should be inserted back into
+     *   the Rya instance the originating statements came from; otherwise {@code false}.
      * @return The {@link StreamsQuery} used in Rya Streams.
      * @throws QueryRepositoryException Could not add the query.
      * @throws IllegalStateException The Service has not been started, but has been subscribed to.
      */
-    public StreamsQuery add(final String query, boolean isActive) throws QueryRepositoryException, IllegalStateException;
+    public StreamsQuery add(final String query, boolean isActive, boolean isInsert) throws QueryRepositoryException, IllegalStateException;
 
     /**
      * Updates the isActive state of a {@link StreamsQuery}. Setting this value to {@code true}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQueryTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQueryTest.java b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQueryTest.java
index 77a0a15..1a6ea88 100644
--- a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQueryTest.java
+++ b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/interactor/defaults/DefaultAddQueryTest.java
@@ -43,10 +43,10 @@ public class DefaultAddQueryTest {
         final AddQuery addQuery = new DefaultAddQuery(repo);
 
         // Add the query.
-        addQuery.addQuery(sparql, true);
+        addQuery.addQuery(sparql, true, true);
 
         // Verify the call was forwarded to the repository.
-        verify(repo, times(1)).add(eq(sparql), eq(true));
+        verify(repo, times(1)).add(eq(sparql), eq(true), eq(true));
     }
 
     @Test(expected = RyaStreamsException.class)
@@ -59,6 +59,6 @@ public class DefaultAddQueryTest {
         final AddQuery addQuery = new DefaultAddQuery(repo);
 
         // Add the query.
-        addQuery.addQuery(sparql, true);
+        addQuery.addQuery(sparql, true, true);
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
index d7e116b..5a16e79 100644
--- a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
+++ b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
@@ -50,9 +50,9 @@ public class InMemoryQueryRepositoryTest {
         final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
         // Add some queries to it.
         final Set<StreamsQuery> expected = new HashSet<>();
-        expected.add( queries.add("query 1", true) );
-        expected.add( queries.add("query 2", false) );
-        expected.add( queries.add("query 3", true) );
+        expected.add( queries.add("query 1", true, true) );
+        expected.add( queries.add("query 2", false, true) );
+        expected.add( queries.add("query 3", true, false) );
 
         // Show they are in the list of all queries.
         final Set<StreamsQuery> stored = queries.list();
@@ -65,9 +65,9 @@ public class InMemoryQueryRepositoryTest {
         final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
         // Add some queries to it. The second one we will delete.
         final Set<StreamsQuery> expected = new HashSet<>();
-        expected.add( queries.add("query 1", true) );
-        final UUID deletedMeId = queries.add("query 2", false).getQueryId();
-        expected.add( queries.add("query 3", true) );
+        expected.add( queries.add("query 1", true, true) );
+        final UUID deletedMeId = queries.add("query 2", false, true).getQueryId();
+        expected.add( queries.add("query 3", true, false) );
 
         // Delete the second query.
         queries.delete( deletedMeId );
@@ -86,16 +86,20 @@ public class InMemoryQueryRepositoryTest {
             queries.startAndWait();
             // Add some queries and deletes to it.
             final Set<StreamsQuery> expected = new HashSet<>();
-            expected.add( queries.add("query 1", true) );
-            final UUID deletedMeId = queries.add("query 2", false).getQueryId();
-            expected.add( queries.add("query 3", true) );
+            expected.add( queries.add("query 1", true, true) );
+            final UUID deletedMeId = queries.add("query 2", false, true).getQueryId();
+            expected.add( queries.add("query 3", true, false) );
             queries.delete( deletedMeId );
 
             // Create a new totally in memory QueryRepository.
             final QueryRepository initializedQueries = new InMemoryQueryRepository( changeLog, SCHEDULE );
-            // Listing the queries should work using an initialized change log.
-            final Set<StreamsQuery> stored = initializedQueries.list();
-            assertEquals(expected, stored);
+            try {
+                // Listing the queries should work using an initialized change log.
+                final Set<StreamsQuery> stored = initializedQueries.list();
+                assertEquals(expected, stored);
+            } finally {
+                queries.stop();
+            }
         } finally {
             queries.stop();
         }
@@ -117,7 +121,7 @@ public class InMemoryQueryRepositoryTest {
         // Setup a totally in memory QueryRepository.
         final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
         // Add a query to it.
-        final StreamsQuery query = queries.add("query 1", true);
+        final StreamsQuery query = queries.add("query 1", true, false);
 
         // Show the fetched query matches the expected ones.
         final Optional<StreamsQuery> fetched = queries.get(query.getQueryId());
@@ -140,14 +144,14 @@ public class InMemoryQueryRepositoryTest {
         // Setup a totally in memory QueryRepository.
         final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
         // Add a query to it.
-        final StreamsQuery query = queries.add("query 1", true);
+        final StreamsQuery query = queries.add("query 1", true, false);
 
         // Change the isActive state of that query.
         queries.updateIsActive(query.getQueryId(), false);
 
         // Show the fetched query matches the expected one.
         final Optional<StreamsQuery> fetched = queries.get(query.getQueryId());
-        final StreamsQuery expected = new StreamsQuery(query.getQueryId(), query.getSparql(), false);
+        final StreamsQuery expected = new StreamsQuery(query.getQueryId(), query.getSparql(), false, false);
         assertEquals(expected, fetched.get());
     }
 
@@ -159,13 +163,13 @@ public class InMemoryQueryRepositoryTest {
             queries.startAndWait();
 
             // Add a query to it.
-            final StreamsQuery query = queries.add("query 1", true);
+            final StreamsQuery query = queries.add("query 1", true, false);
 
             final Set<StreamsQuery> existing = queries.subscribe((queryChangeEvent, newQueryState) -> {
                 final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<>(1L,
-                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true, false));
                 final Optional<StreamsQuery> expectedQueryState = Optional.of(
-                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true, false));
 
                 assertEquals(expected, queryChangeEvent);
                 assertEquals(expectedQueryState, newQueryState);
@@ -173,7 +177,7 @@ public class InMemoryQueryRepositoryTest {
 
             assertEquals(Sets.newHashSet(query), existing);
 
-            queries.add("query 2", true);
+            queries.add("query 2", true, false);
         } finally {
             queries.stop();
         }
@@ -194,9 +198,9 @@ public class InMemoryQueryRepositoryTest {
             final CountDownLatch repo1Latch = new CountDownLatch(1);
             queries.subscribe((queryChangeEvent, newQueryState) -> {
                 final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<>(0L,
-                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true, false));
                 final Optional<StreamsQuery> expectedQueryState = Optional.of(
-                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true, false));
 
                 assertEquals(expected, queryChangeEvent);
                 assertEquals(expectedQueryState, newQueryState);
@@ -207,16 +211,16 @@ public class InMemoryQueryRepositoryTest {
             final CountDownLatch repo2Latch = new CountDownLatch(1);
             queries2.subscribe((queryChangeEvent, newQueryState) -> {
                 final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<>(0L,
-                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                        QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true, false));
                 final Optional<StreamsQuery> expectedQueryState = Optional.of(
-                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                        new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true, false));
 
                 assertEquals(expected, queryChangeEvent);
                 assertEquals(expectedQueryState, newQueryState);
                 repo2Latch.countDown();
             });
 
-            queries.add("query 2", true);
+            queries.add("query 2", true, false);
 
             assertTrue(repo1Latch.await(5, TimeUnit.SECONDS));
             assertTrue(repo2Latch.await(5, TimeUnit.SECONDS));
@@ -233,6 +237,6 @@ public class InMemoryQueryRepositoryTest {
         final QueryRepository queries = new InMemoryQueryRepository(new InMemoryQueryChangeLog(), SCHEDULE);
         queries.subscribe((queryChangeEvent, newQueryState) -> {});
 
-        queries.add("query 2", true);
+        queries.add("query 2", true, false);
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
index 9273c33..3886a95 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
@@ -22,6 +22,7 @@ import static java.util.Objects.requireNonNull;
 
 import java.util.concurrent.TimeUnit;
 
+import org.apache.rya.api.utils.QueryInvestigator;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.exception.RyaStreamsException;
 import org.apache.rya.streams.api.interactor.AddQuery;
@@ -32,6 +33,7 @@ import org.apache.rya.streams.api.queries.QueryRepository;
 import org.apache.rya.streams.client.RyaStreamsCommand;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLogFactory;
+import org.openrdf.query.MalformedQueryException;
 
 import com.beust.jcommander.JCommander;
 import com.beust.jcommander.Parameter;
@@ -58,6 +60,9 @@ public class AddQueryCommand implements RyaStreamsCommand {
         @Parameter(names = {"--isActive", "-a"}, required = false, description = "True if the added query will be started.")
         private String isActive;
 
+        @Parameter(names = {"--isInsert", "-n"}, required = false, description = "True if the reuslts of the query will be written back to Rya.")
+        private String isInsert;
+
         @Override
         public String toString() {
             final StringBuilder parameters = new StringBuilder();
@@ -67,6 +72,7 @@ public class AddQueryCommand implements RyaStreamsCommand {
                 parameters.append("\tQuery: " + query + "\n");
             }
             parameters.append("\tIs Active: " + isActive + "\n");
+            parameters.append("\tis Insert: " + isInsert + "\n");
             return parameters.toString();
         }
     }
@@ -125,17 +131,33 @@ public class AddQueryCommand implements RyaStreamsCommand {
         try {
             final AddQuery addQuery = new DefaultAddQuery(queryRepo);
             try {
-                final StreamsQuery query = addQuery.addQuery(params.query, Boolean.parseBoolean(params.isActive));
+                final Boolean isActive = Boolean.parseBoolean(params.isActive);
+                final Boolean isInsert = Boolean.parseBoolean(params.isInsert);
+
+                // If the query's results are meant to be written back to Rya, make sure it creates statements.
+                if(isInsert) {
+                    final boolean isConstructQuery = QueryInvestigator.isConstruct(params.query);
+                    final boolean isInsertQuery = QueryInvestigator.isInsertWhere(params.query);
+
+                    if(isConstructQuery) {
+                        System.out.println(
+                                "WARNING: CONSTRUCT is part of the SPARQL Query API, so they do not normally\n" +
+                                "get written back to the triple store. Consider using an INSERT, which is\n" +
+                                "part of the SPARQL Update API, in the future.");
+                    }
+
+                    if(!(isConstructQuery || isInsertQuery)) {
+                        throw new ArgumentsException("Only CONSTRUCT queries and INSERT updates may be inserted back to the triple store.");
+                    }
+                }
+
+                final StreamsQuery query = addQuery.addQuery(params.query, isActive, isInsert);
                 System.out.println("Added query: " + query.getSparql());
             } catch (final RyaStreamsException e) {
-                System.err.println("Unable to parse query: " + params.query);
-                e.printStackTrace();
-                System.exit(1);
+                throw new ExecutionException("Unable to add the query to Rya Streams.", e);
             }
-        } catch (final Exception e) {
-            System.err.println("Problem encountered while closing the QueryRepository.");
-            e.printStackTrace();
-            System.exit(1);
+        } catch(final MalformedQueryException e) {
+            throw new ArgumentsException("Could not parse the provided query.", e);
         }
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
index a5507a6..3639aa9 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
@@ -23,7 +23,6 @@ import static java.util.Objects.requireNonNull;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
-import org.apache.commons.lang.StringUtils;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.exception.RyaStreamsException;
 import org.apache.rya.streams.api.interactor.ListQueries;
@@ -116,9 +115,11 @@ public class ListQueriesCommand implements RyaStreamsCommand {
             sb.append("ID: ").append(query.getQueryId())
                 .append("    ")
                 .append("Is Active: ").append(query.isActive())
-                .append(StringUtils.rightPad("" + query.isActive(), 9))
+                .append( query.isActive() ? "     " : "    " )
+                .append("Is Insert: ").append(query.isInsert())
+                .append(query.isInsert() ? "     " : "    ")
                 .append("Query: ").append(query.getSparql()).append("\n");
         });
         return sb.toString();
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
index 3bfbadc..bbbcb2a 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
@@ -33,6 +33,7 @@ import org.apache.rya.streams.api.queries.InMemoryQueryRepository;
 import org.apache.rya.streams.api.queries.QueryChange;
 import org.apache.rya.streams.api.queries.QueryChangeLog;
 import org.apache.rya.streams.api.queries.QueryRepository;
+import org.apache.rya.streams.client.RyaStreamsCommand.ArgumentsException;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLog;
 import org.apache.rya.streams.kafka.serialization.queries.QueryChangeDeserializer;
@@ -78,7 +79,8 @@ public class AddQueryCommandIT {
                 "-i", kafka.getKafkaHostname(),
                 "-p", kafka.getKafkaPort(),
                 "-q", query,
-                "-a", "true"
+                "-a", "true",
+                "-n", "false"
         };
 
         // Execute the command.
@@ -100,7 +102,8 @@ public class AddQueryCommandIT {
                 "--kafkaHostname", kafka.getKafkaHostname(),
                 "--kafkaPort", kafka.getKafkaPort(),
                 "--query", query,
-                "--isActive", "true"
+                "--isActive", "true",
+                "--isInsert", "false"
         };
 
         // Execute the command.
@@ -112,4 +115,22 @@ public class AddQueryCommandIT {
         assertEquals(1, queries.size());
         assertEquals(query, queries.iterator().next().getSparql());
     }
+
+    @Test(expected = ArgumentsException.class)
+    public void canNotInsertQueries() throws Exception {
+        // Arguments that add a query to Rya Streams.
+        final String query = "SELECT * WHERE { ?person <urn:name> ?name }";
+        final String[] args = new String[] {
+                "--ryaInstance", "" + ryaInstance,
+                "--kafkaHostname", kafka.getKafkaHostname(),
+                "--kafkaPort", kafka.getKafkaPort(),
+                "--query", query,
+                "--isActive", "true",
+                "--isInsert", "true"
+        };
+
+        // Execute the command.
+        final AddQueryCommand command = new AddQueryCommand();
+        command.execute(args);
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
index 7bec080..4cfdedb 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
@@ -74,9 +74,9 @@ public class DeleteQueryCommandIT {
     @Test
     public void shortParams() throws Exception {
         // Add a few queries to Rya Streams.
-        queryRepo.add("query1", true);
-        final UUID query2Id = queryRepo.add("query2", false).getQueryId();
-        queryRepo.add("query3", true);
+        queryRepo.add("query1", true, true);
+        final UUID query2Id = queryRepo.add("query2", false, true).getQueryId();
+        queryRepo.add("query3", true, false);
 
         // Show that all three of the queries were added.
         Set<StreamsQuery> queries = queryRepo.list();
@@ -105,9 +105,9 @@ public class DeleteQueryCommandIT {
     @Test
     public void longParams() throws Exception {
         // Add a few queries to Rya Streams.
-        queryRepo.add("query1", true);
-        final UUID query2Id = queryRepo.add("query2", false).getQueryId();
-        queryRepo.add("query3", true);
+        queryRepo.add("query1", true, true);
+        final UUID query2Id = queryRepo.add("query2", false, true).getQueryId();
+        queryRepo.add("query3", true, false);
 
         // Show that all three of the queries were added.
         Set<StreamsQuery> queries = queryRepo.list();

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
index f6ceb75..e9f961a 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
@@ -68,9 +68,9 @@ public class ListQueryCommandIT {
     @Test
     public void shortParams() throws Exception {
         // Add a few queries to Rya Streams.
-        queryRepo.add("query1", true);
-        queryRepo.add("query2", false);
-        queryRepo.add("query3", true);
+        queryRepo.add("query1", true, true);
+        queryRepo.add("query2", false, true);
+        queryRepo.add("query3", true, false);
 
         // Execute the List Queries command.
         final String[] args = new String[] {
@@ -86,9 +86,9 @@ public class ListQueryCommandIT {
     @Test
     public void longParams() throws Exception {
         // Add a few queries to Rya Streams.
-        queryRepo.add("query1", true);
-        queryRepo.add("query2", false);
-        queryRepo.add("query3", true);
+        queryRepo.add("query1", true, true);
+        queryRepo.add("query2", false, true);
+        queryRepo.add("query3", true, false);
 
         // Execute the List Queries command.
         final String[] args = new String[] {

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
index 176b920..21a8e4c 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
@@ -116,7 +116,7 @@ public class RunQueryCommandIT {
     @Test
     public void runQuery() throws Exception {
         // Register a query with the Query Repository.
-        final StreamsQuery sQuery = queryRepo.add("SELECT * WHERE { ?person <urn:worksAt> ?business . }", true);
+        final StreamsQuery sQuery = queryRepo.add("SELECT * WHERE { ?person <urn:worksAt> ?business . }", true, false);
 
         // Arguments that run the query we just registered with Rya Streams.
         final String[] args = new String[] {

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
index c9abb41..4459057 100644
--- a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
+++ b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
@@ -88,7 +88,7 @@ public class KafkaRunQueryIT {
         final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS) );
 
         // Add the query to the query repository.
-        final StreamsQuery sQuery = queries.add("SELECT * WHERE { ?person <urn:worksAt> ?business . }", true);
+        final StreamsQuery sQuery = queries.add("SELECT * WHERE { ?person <urn:worksAt> ?business . }", true, false);
         final UUID queryId = sQuery.getQueryId();
         final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/queries/KafkaQueryChangeLogIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/queries/KafkaQueryChangeLogIT.java b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/queries/KafkaQueryChangeLogIT.java
index c2b821f..0dcd079 100644
--- a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/queries/KafkaQueryChangeLogIT.java
+++ b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/queries/KafkaQueryChangeLogIT.java
@@ -79,7 +79,7 @@ public class KafkaQueryChangeLogIT extends KafkaITBase {
     public void testWrite() throws Exception {
         final String sparql = "SOME QUERY HERE";
         final UUID uuid = UUID.randomUUID();
-        final QueryChange newChange = QueryChange.create(uuid, sparql, true);
+        final QueryChange newChange = QueryChange.create(uuid, sparql, true, false);
         changeLog.write(newChange);
 
         consumer.subscribe(Lists.newArrayList(topic));
@@ -93,7 +93,7 @@ public class KafkaQueryChangeLogIT extends KafkaITBase {
     @Test
     public void readSingleWrite() throws Exception {
         // Write a single change to the log.
-        final QueryChange change = QueryChange.create(UUID.randomUUID(), "query", true);
+        final QueryChange change = QueryChange.create(UUID.randomUUID(), "query", true, false);
         changeLog.write(change);
 
         // Read that entry from the log.
@@ -198,7 +198,7 @@ public class KafkaQueryChangeLogIT extends KafkaITBase {
             assertFalse( changeLog2.readFromStart().hasNext() );
 
             // Write a change to the first log.
-            final QueryChange change = QueryChange.create(UUID.randomUUID(), "query", true);
+            final QueryChange change = QueryChange.create(UUID.randomUUID(), "query", true, false);
             changeLog.write(change);
 
             // Show it's in the first log.
@@ -214,7 +214,7 @@ public class KafkaQueryChangeLogIT extends KafkaITBase {
         for (int ii = 0; ii < 10; ii++) {
             final String sparql = "SOME QUERY HERE_" + ii;
             final UUID uuid = UUID.randomUUID();
-            final QueryChange newChange = QueryChange.create(uuid, sparql, true);
+            final QueryChange newChange = QueryChange.create(uuid, sparql, true, false);
             changeLog.write(newChange);
             changes.add(newChange);
         }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java
index cb708ed..2cb543a 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java
@@ -79,13 +79,13 @@ public class LogEventWorkerTest {
 
         // Write a message that indicates a new query should be active.
         final UUID firstQueryId = UUID.randomUUID();
-        changeLog.write(QueryChange.create(firstQueryId, "select * where { ?a ?b ?c . }", true));
+        changeLog.write(QueryChange.create(firstQueryId, "select * where { ?a ?b ?c . }", true, false));
 
         // Write a message that adds an active query, but then makes it inactive. Because both of these
         // events are written to the log before the worker subscribes to the repository for updates, they
         // must result in a single query stopped event.
         final UUID secondQueryId = UUID.randomUUID();
-        changeLog.write(QueryChange.create(secondQueryId, "select * where { ?d ?e ?f . }", true));
+        changeLog.write(QueryChange.create(secondQueryId, "select * where { ?d ?e ?f . }", true, false));
         changeLog.write(QueryChange.update(secondQueryId, false));
 
         // Start the worker that will be tested.
@@ -103,7 +103,7 @@ public class LogEventWorkerTest {
             // Query 2, stopped.
             Set<QueryEvent> expectedEvents = new HashSet<>();
             expectedEvents.add(QueryEvent.executing("rya",
-                    new StreamsQuery(firstQueryId, "select * where { ?a ?b ?c . }", true)));
+                    new StreamsQuery(firstQueryId, "select * where { ?a ?b ?c . }", true, false)));
             expectedEvents.add(QueryEvent.stopped("rya", secondQueryId));
 
             Set<QueryEvent> queryEvents = new HashSet<>();
@@ -146,7 +146,7 @@ public class LogEventWorkerTest {
 
         // Write a message that indicates a new query should be active.
         final UUID firstQueryId = UUID.randomUUID();
-        changeLog.write(QueryChange.create(firstQueryId, "select * where { ?a ?b ?c . }", true));
+        changeLog.write(QueryChange.create(firstQueryId, "select * where { ?a ?b ?c . }", true, false));
 
         // Start the worker that will be tested.
         final Thread logEventWorker = new Thread(new LogEventWorker(logEventQueue,
@@ -165,7 +165,7 @@ public class LogEventWorkerTest {
             // second message was effectively skipped as it would have add its work added twice otherwise.
             final Set<QueryEvent> expectedEvents = new HashSet<>();
             expectedEvents.add(QueryEvent.executing("rya",
-                    new StreamsQuery(firstQueryId, "select * where { ?a ?b ?c . }", true)));
+                    new StreamsQuery(firstQueryId, "select * where { ?a ?b ?c . }", true, false)));
 
             final Set<QueryEvent> queryEvents = new HashSet<>();
             queryEvents.add( queryEventQueue.poll(500, TimeUnit.MILLISECONDS) );

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java
index 4495e19..ea6a37b 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java
@@ -87,9 +87,9 @@ public class QueryEventWorkGeneratorTest {
 
         // A thread that will attempt to notify the generator with a created query.
         final UUID queryId = UUID.randomUUID();
-        final StreamsQuery query = new StreamsQuery(queryId, "query", true);
+        final StreamsQuery query = new StreamsQuery(queryId, "query", true, false);
         final Thread notifyThread = new Thread(() -> {
-            final QueryChange change = QueryChange.create(queryId, query.getSparql(), query.isActive());
+            final QueryChange change = QueryChange.create(queryId, query.getSparql(), query.isActive(), query.isInsert());
             final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
             generator.notify(entry, Optional.of(query));
         });
@@ -108,7 +108,7 @@ public class QueryEventWorkGeneratorTest {
 
             // Show work was added to the queue and the notifying thread died.
             final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
-            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive()));
+            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive(), query.isInsert()));
             assertEquals(expected, event);
         } finally {
             shutdownSignal.set(true);
@@ -132,9 +132,9 @@ public class QueryEventWorkGeneratorTest {
 
         // A thread that will attempt to notify the generator with a created query.
         final UUID queryId = UUID.randomUUID();
-        final StreamsQuery query = new StreamsQuery(queryId, "query", true);
+        final StreamsQuery query = new StreamsQuery(queryId, "query", true, false);
         final Thread notifyThread = new Thread(() -> {
-            final QueryChange change = QueryChange.create(queryId, query.getSparql(), query.isActive());
+            final QueryChange change = QueryChange.create(queryId, query.getSparql(), query.isActive(), query.isInsert());
             final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
             generator.notify(entry, Optional.of(query));
         });
@@ -145,7 +145,7 @@ public class QueryEventWorkGeneratorTest {
         try {
             // Show work was added to the queue and the notifying thread died.
             final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
-            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive()));
+            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive(), query.isInsert()));
             assertEquals(expected, event);
         } finally {
             shutdownSignal.set(true);
@@ -205,7 +205,7 @@ public class QueryEventWorkGeneratorTest {
 
         // A thread that will attempt to notify the generator with an update query change.
         final UUID queryId = UUID.randomUUID();
-        final StreamsQuery query = new StreamsQuery(queryId, "query", true);
+        final StreamsQuery query = new StreamsQuery(queryId, "query", true, false);
         final Thread notifyThread = new Thread(() -> {
             final QueryChange change = QueryChange.update(queryId, true);
             final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
@@ -218,7 +218,7 @@ public class QueryEventWorkGeneratorTest {
         try {
             // Show work was added to the queue and the notifying thread died.
             final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
-            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive()));
+            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive(), query.isInsert()));
             assertEquals(expected, event);
         } finally {
             shutdownSignal.set(true);
@@ -242,7 +242,7 @@ public class QueryEventWorkGeneratorTest {
 
         // A thread that will attempt to notify the generator with an update query change.
         final UUID queryId = UUID.randomUUID();
-        final StreamsQuery query = new StreamsQuery(queryId, "query", false);
+        final StreamsQuery query = new StreamsQuery(queryId, "query", false, false);
         final Thread notifyThread = new Thread(() -> {
             final QueryChange change = QueryChange.update(queryId, false);
             final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java
index 33c0719..95c7a54 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java
@@ -68,7 +68,7 @@ public class QueryEventWorkerTest {
 
         // The message that indicates a query needs to be executed.
         final String ryaInstance = "rya";
-        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "sparql", true);
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "sparql", true, false);
         final QueryEvent executingEvent = QueryEvent.executing(ryaInstance, query);
 
         // Release a latch if the startQuery method on the queryExecutor is invoked with the correct values.

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
index 04e70c0..f1c9e0f 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
@@ -50,7 +50,7 @@ public class QueryManagerTest {
         //The new QueryChangeLog
         final QueryChangeLog newChangeLog = new InMemoryQueryChangeLog();
         final String ryaInstance = "ryaTestInstance";
-        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true);
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true, false);
 
         // when the query executor is told to start the test query on the test
         // rya instance, count down on the countdown latch
@@ -69,7 +69,7 @@ public class QueryManagerTest {
             //The listener created by the Query Manager
             final SourceListener listener = (SourceListener) invocation.getArguments()[0];
             listener.notifyCreate(ryaInstance, newChangeLog);
-            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive()));
+            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive(), query.isInsert()));
             return null;
         }).when(source).subscribe(any(SourceListener.class));
 
@@ -91,7 +91,7 @@ public class QueryManagerTest {
     public void testDeleteQuery() throws Exception {
         //The new QueryChangeLog
         final QueryChangeLog newChangeLog = new InMemoryQueryChangeLog();
-        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true);
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true, false);
         final String ryaInstance = "ryaTestInstance";
 
         // when the query executor is told to start the test query on the test
@@ -121,7 +121,7 @@ public class QueryManagerTest {
             final SourceListener listener = (SourceListener) invocation.getArguments()[0];
             listener.notifyCreate(ryaInstance, newChangeLog);
             Thread.sleep(1000);
-            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive()));
+            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive(), query.isInsert()));
             queryStarted.await(5, TimeUnit.SECONDS);
             newChangeLog.write(QueryChange.delete(query.getQueryId()));
             return null;
@@ -145,7 +145,7 @@ public class QueryManagerTest {
     public void testUpdateQuery() throws Exception {
         // The new QueryChangeLog
         final QueryChangeLog newChangeLog = new InMemoryQueryChangeLog();
-        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true);
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "some query", true, false);
         final String ryaInstance = "ryaTestInstance";
 
         // when the query executor is told to start the test query on the test
@@ -176,7 +176,7 @@ public class QueryManagerTest {
             final SourceListener listener = (SourceListener) invocation.getArguments()[0];
             listener.notifyCreate(ryaInstance, newChangeLog);
             Thread.sleep(1000);
-            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive()));
+            newChangeLog.write(QueryChange.create(query.getQueryId(), query.getSparql(), query.isActive(), query.isInsert()));
             queryStarted.await(5, TimeUnit.SECONDS);
             newChangeLog.write(QueryChange.update(query.getQueryId(), false));
             return null;

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
index 6358104..83f040d 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
@@ -86,7 +86,7 @@ public class LocalQueryExecutorIT {
     public void runQuery() throws Exception {
         // Test values.
         final String ryaInstance = "rya";
-        final StreamsQuery sQuery = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?person <urn:worksAt> ?business . }", true);
+        final StreamsQuery sQuery = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?person <urn:worksAt> ?business . }", true, false);
 
         // Create the statements that will be loaded.
         final ValueFactory vf = new ValueFactoryImpl();

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
index c0f888e..efbcf4b 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
@@ -46,14 +46,14 @@ public class LocalQueryExecutorTest {
     @Test(expected = IllegalStateException.class)
     public void startQuery_serviceNotStarted() throws Exception {
         final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), mock(KafkaStreamsFactory.class));
-        executor.startQuery("rya", new StreamsQuery(UUID.randomUUID(), "query", true));
+        executor.startQuery("rya", new StreamsQuery(UUID.randomUUID(), "query", true, false));
     }
 
     @Test
     public void startQuery() throws Exception {
         // Test values.
         final String ryaInstance = "rya";
-        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
 
         // Mock the streams factory so that we can tell if the start function is invoked by the executor.
         final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
@@ -97,7 +97,7 @@ public class LocalQueryExecutorTest {
     public void stopQuery() throws Exception {
         // Test values.
         final String ryaInstance = "rya";
-        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
 
         // Mock the streams factory so that we can tell if the stop function is invoked by the executor.
         final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
@@ -131,8 +131,8 @@ public class LocalQueryExecutorTest {
     public void stopAll_noneForThatRyaInstance() throws Exception {
         // Test values.
         final String ryaInstance = "rya";
-        final StreamsQuery query1= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
-        final StreamsQuery query2= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query1= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
+        final StreamsQuery query2= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
 
         // Mock the streams factory so that we can tell if the stop function is invoked by the executor.
         final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
@@ -169,9 +169,9 @@ public class LocalQueryExecutorTest {
     public void stopAll() throws Exception {
         // Test values.
         final String ryaInstance1 = "rya1";
-        final StreamsQuery query1= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query1= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
         final String ryaInstance2 = "rya2";
-        final StreamsQuery query2= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query2= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
 
         // Mock the streams factory so that we can tell if the stop function is invoked by the executor.
         final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
@@ -230,9 +230,9 @@ public class LocalQueryExecutorTest {
     public void getRunningQueryIds_noneStopped() throws Exception {
         // Test values.
         final String ryaInstance = "rya";
-        final StreamsQuery query1 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
-        final StreamsQuery query2 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
-        final StreamsQuery query3 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query1 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
+        final StreamsQuery query2 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
+        final StreamsQuery query3 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
 
         // Mock the streams factory so that we can figure out what is started.
         final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
@@ -265,9 +265,9 @@ public class LocalQueryExecutorTest {
     public void getRunningQueryIds_stoppedNoLongerListed() throws Exception {
         // Test values.
         final String ryaInstance = "rya";
-        final StreamsQuery query1 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
-        final StreamsQuery query2 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
-        final StreamsQuery query3 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query1 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
+        final StreamsQuery query2 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
+        final StreamsQuery query3 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true, false);
 
         // Mock the streams factory so that we can figure out what is started.
         final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/shell/src/main/java/org/apache/rya/shell/RyaStreamsCommands.java
----------------------------------------------------------------------
diff --git a/extras/shell/src/main/java/org/apache/rya/shell/RyaStreamsCommands.java b/extras/shell/src/main/java/org/apache/rya/shell/RyaStreamsCommands.java
index 5f7df84..fede1a9 100644
--- a/extras/shell/src/main/java/org/apache/rya/shell/RyaStreamsCommands.java
+++ b/extras/shell/src/main/java/org/apache/rya/shell/RyaStreamsCommands.java
@@ -28,13 +28,16 @@ import org.apache.rya.api.client.RyaClient;
 import org.apache.rya.api.client.RyaClientException;
 import org.apache.rya.api.instance.RyaDetails;
 import org.apache.rya.api.instance.RyaDetails.RyaStreamsDetails;
+import org.apache.rya.api.utils.QueryInvestigator;
 import org.apache.rya.shell.SharedShellState.ConnectionState;
+import org.apache.rya.shell.util.ConsolePrinter;
 import org.apache.rya.shell.util.SparqlPrompt;
 import org.apache.rya.shell.util.StreamsQueryFormatter;
 import org.apache.rya.streams.api.RyaStreamsClient;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.exception.RyaStreamsException;
 import org.apache.rya.streams.kafka.KafkaRyaStreamsClientFactory;
+import org.openrdf.query.MalformedQueryException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.shell.core.CommandMarker;
 import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
@@ -61,19 +64,23 @@ public class RyaStreamsCommands implements CommandMarker {
 
     private final SharedShellState state;
     private final SparqlPrompt sparqlPrompt;
+    private final ConsolePrinter consolePrinter;
 
     /**
      * Constructs an instance of {@link RyaStreamsCommands}.
      *
      * @param state - Holds shared state between all of the command classes. (not null)
      * @param sparqlPrompt - Prompts a user for a SPARQL query. (not null)
+     * @param consolePrinter - Prints messages to the console. (not null)
      */
     @Autowired
     public RyaStreamsCommands(
             final SharedShellState state,
-            final SparqlPrompt sparqlPrompt) {
+            final SparqlPrompt sparqlPrompt,
+            final ConsolePrinter consolePrinter) {
         this.state = requireNonNull(state);
         this.sparqlPrompt = requireNonNull(sparqlPrompt);
+        this.consolePrinter = requireNonNull(consolePrinter);
     }
 
     /**
@@ -172,7 +179,10 @@ public class RyaStreamsCommands implements CommandMarker {
     public String addQuery(
             @CliOption(key = {"inactive"}, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
                        help = "Setting this flag will add the query, but not run it. (default: false)")
-            final boolean inactive) {
+            final boolean inactive,
+            @CliOption(key = {"insert"}, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
+                       help = "Setting this flag will insert the query's results back into Rya. (default: false)")
+            final boolean isInsert) {
         final RyaStreamsClient streamsClient = state.getShellState().getRyaStreamsCommands().get();
 
         // Prompt the user for the SPARQL that defines the query.
@@ -184,10 +194,32 @@ public class RyaStreamsCommands implements CommandMarker {
                 return "";
             }
 
-            final StreamsQuery streamsQuery = streamsClient.getAddQuery().addQuery(sparql.get(), !inactive);
+            final boolean isConstructQuery = QueryInvestigator.isConstruct(sparql.get());
+            final boolean isInsertQuery = QueryInvestigator.isInsertWhere(sparql.get());
+
+            // If the user wants to insert a CONSTRUCT into Rya, print a warning.
+            if(isInsert && isConstructQuery) {
+                consolePrinter.println("WARNING: CONSTRUCT is part of the SPARQL Query API, so they do not normally");
+                consolePrinter.println("get written back to the triple store. Consider using an INSERT, which is");
+                consolePrinter.println("part of the SPARQL Update API, in the future.");
+            }
+
+            // If the user wants to use an INSERT query, but not insert it back into Rya, suggest using a construct.
+            if(!isInsert && isInsertQuery) {
+                consolePrinter.println("WARNING: INSERT is part of the SPARQL Update API, so they normally get written");
+                consolePrinter.println("back to the triple store. Consider using a CONSTRUCT, which is part of the");
+                consolePrinter.println("SPARQL Query API, in the future.");
+            }
+
+            // If the user wants to insert the query back into Rya, make sure it is a legal query to do that.
+            if(isInsert && !(isConstructQuery || isInsertQuery)) {
+                throw new RuntimeException("Only CONSTRUCT queries and INSERT updates may be inserted back to the triple store.");
+            }
+
+            final StreamsQuery streamsQuery = streamsClient.getAddQuery().addQuery(sparql.get(), !inactive, isInsert);
             return "The added query's ID is " + streamsQuery.getQueryId();
 
-        } catch (final IOException | RyaStreamsException e) {
+        } catch (final MalformedQueryException | IOException | RyaStreamsException e) {
             throw new RuntimeException("Unable to add the SPARQL query to the Rya Streams subsystem.", e);
         }
     }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/010c6927/extras/shell/src/main/java/org/apache/rya/shell/util/StreamsQueryFormatter.java
----------------------------------------------------------------------
diff --git a/extras/shell/src/main/java/org/apache/rya/shell/util/StreamsQueryFormatter.java b/extras/shell/src/main/java/org/apache/rya/shell/util/StreamsQueryFormatter.java
index 6c06caf..babeec8 100644
--- a/extras/shell/src/main/java/org/apache/rya/shell/util/StreamsQueryFormatter.java
+++ b/extras/shell/src/main/java/org/apache/rya/shell/util/StreamsQueryFormatter.java
@@ -63,6 +63,7 @@ public final class StreamsQueryFormatter {
         final StringBuilder builder = new StringBuilder();
         builder.append(" Query ID: ").append( query.getQueryId() ) .append("\n");
         builder.append("Is Active: ").append( query.isActive() ).append("\n");
+        builder.append("Is Insert: ").append( query.isInsert() ).append("\n");
         builder.append("   SPARQL: ").append( lines[0] ).append("\n");
 
         for(int i = 1; i < lines.length; i++) {


[19/22] incubator-rya git commit: RYA-462 Updated the Kafka topic name for StreamsQueries to include the Rya Instance name.

Posted by pu...@apache.org.
RYA-462 Updated the Kafka topic name for StreamsQueries to include the Rya Instance name.

Conflicts:
	extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/e07390d3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/e07390d3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/e07390d3

Branch: refs/heads/master
Commit: e07390d38e17df13d49eb41a81f0391b92e1e27f
Parents: e453694
Author: kchilton2 <ke...@gmail.com>
Authored: Thu Feb 8 17:21:10 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 13:00:02 2018 -0500

----------------------------------------------------------------------
 .../api/interactor/GetQueryResultStream.java    |  6 +-
 .../streams/client/command/RunQueryCommand.java |  4 +-
 .../client/command/StreamResultsCommand.java    | 60 ++++----------------
 .../client/command/RunQueryCommandIT.java       |  2 +-
 .../kafka/processors/filter/GeoFilterIT.java    |  2 +-
 .../aggregation/AggregationProcessorIT.java     | 17 +++---
 .../processors/filter/FilterProcessorIT.java    |  2 +-
 .../processors/filter/TemporalFilterIT.java     |  8 +--
 .../kafka/processors/join/JoinProcessorIT.java  | 10 ++--
 .../projection/MultiProjectionProcessorIT.java  |  3 +-
 .../projection/ProjectionProcessorIT.java       |  3 +-
 .../sp/StatementPatternProcessorIT.java         |  9 ++-
 .../apache/rya/streams/kafka/KafkaTopics.java   | 28 ++++++++-
 .../kafka/SingleThreadKafkaStreamsFactory.java  |  2 +-
 .../interactor/KafkaGetQueryResultStream.java   | 12 ++--
 .../rya/streams/kafka/KafkaTopicsTest.java      |  4 +-
 .../interactor/KafkaGetQueryResultStreamIT.java | 18 +++---
 .../kafka/interactor/KafkaRunQueryIT.java       |  2 +-
 .../kafka/KafkaQueryChangeLogSource.java        |  4 +-
 .../querymanager/kafka/LocalQueryExecutor.java  |  2 +-
 .../kafka/LocalQueryExecutorIT.java             |  2 +-
 21 files changed, 93 insertions(+), 107 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/GetQueryResultStream.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/GetQueryResultStream.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/GetQueryResultStream.java
index 951d060..0e70391 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/GetQueryResultStream.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/interactor/GetQueryResultStream.java
@@ -37,18 +37,20 @@ public interface GetQueryResultStream<T> {
     /**
      * Stream all of the results that have been produced by a query.
      *
+     * @param ryaInstance - The name of the Rya Instance the query is for. (not null)
      * @param queryId - Indicates which query results to stream. (not null)
      * @return A {@link QueryResultStream} that starts with the first result that was ever produced.
      * @throws RyaStreamsException Could not create the result stream.
      */
-    public QueryResultStream<T> fromStart(UUID queryId) throws RyaStreamsException;
+    public QueryResultStream<T> fromStart(String ryaInstance, UUID queryId) throws RyaStreamsException;
 
     /**
      * Stream results that have been produced by a query after this method was invoked.
      *
+     * @param ryaInstance - The name of the Rya Instance the query is for. (not null)
      * @param queryId - Indicates which query results to stream. (not null)
      * @return A {@link QueryResultStream} that only returns results that were produced after this method is invoked.
      * @throws RyaStreamsException Could not create the result stream.
      */
-    public QueryResultStream<T> fromNow(UUID queryId) throws RyaStreamsException;
+    public QueryResultStream<T> fromNow(String ryaInstance, UUID queryId) throws RyaStreamsException;
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
index 7b311f6..f9a9458 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
@@ -135,7 +135,7 @@ public class RunQueryCommand implements RyaStreamsCommand {
                 // Make sure the topics required by the application exists for the specified Rya instances.
                 final Set<String> topics = new HashSet<>();
                 topics.add( KafkaTopics.statementsTopic(params.ryaInstance) );
-                topics.add( KafkaTopics.queryResultsTopic(queryId) );
+                topics.add( KafkaTopics.queryResultsTopic(params.ryaInstance, queryId) );
                 KafkaTopics.createTopics(params.zookeeperServers, topics, 1, 1);
 
                 // Run the query that uses those topics.
@@ -143,7 +143,7 @@ public class RunQueryCommand implements RyaStreamsCommand {
                         params.kafkaIP,
                         params.kafkaPort,
                         KafkaTopics.statementsTopic(params.ryaInstance),
-                        KafkaTopics.queryResultsTopic(queryId),
+                        KafkaTopics.queryResultsTopic(params.ryaInstance, queryId),
                         queryRepo,
                         new TopologyFactory());
                 runQuery.run(queryId);

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
index 8ae4e08..783aedc 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -20,18 +20,11 @@ package org.apache.rya.streams.client.command;
 
 import static java.util.Objects.requireNonNull;
 
-import java.io.OutputStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
 import java.util.Optional;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
-import org.apache.rya.api.model.VisibilityBindingSet;
-import org.apache.rya.api.model.VisibilityStatement;
-import org.apache.rya.api.utils.QueryInvestigator;
 import org.apache.rya.streams.api.entity.QueryResultStream;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.interactor.GetQueryResultStream;
@@ -39,13 +32,13 @@ import org.apache.rya.streams.api.queries.InMemoryQueryRepository;
 import org.apache.rya.streams.api.queries.QueryChangeLog;
 import org.apache.rya.streams.api.queries.QueryRepository;
 import org.apache.rya.streams.client.RyaStreamsCommand;
-import org.apache.rya.streams.client.util.QueryResultsOutputUtil;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.interactor.KafkaGetQueryResultStream;
 import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLogFactory;
 import org.apache.rya.streams.kafka.serialization.VisibilityBindingSetDeserializer;
 import org.apache.rya.streams.kafka.serialization.VisibilityStatementDeserializer;
 import org.openrdf.query.MalformedQueryException;
+import org.openrdf.query.algebra.Reduced;
 import org.openrdf.query.algebra.TupleExpr;
 import org.openrdf.query.parser.sparql.SPARQLParser;
 
@@ -72,20 +65,14 @@ public class StreamResultsCommand implements RyaStreamsCommand {
         @Parameter(names = {"--queryId", "-q"}, required = true, description = "The query whose results will be streamed to the console.")
         private String queryId;
 
-        @Parameter(names = {"--file", "-f"}, required = false, description = "If provided, the output file the results will stream into.")
-        private String outputPath;
-
         @Override
         public String toString() {
             final StringBuilder parameters = new StringBuilder();
             parameters.append(super.toString());
 
             if (!Strings.isNullOrEmpty(queryId)) {
-                parameters.append("\tQuery ID: " + queryId + "\n");
-            }
-
-            if(!Strings.isNullOrEmpty(outputPath)) {
-                parameters.append("\tOutput Path: " + outputPath + "\n");
+                parameters.append("\tQuery ID: " + queryId);
+                parameters.append("\n");
             }
 
             return parameters.toString();
@@ -173,12 +160,10 @@ public class StreamResultsCommand implements RyaStreamsCommand {
         });
 
         // Build the interactor based on the type of result the query produces.
-        boolean isStatementResults = false;
-
         final GetQueryResultStream<?> getQueryResultStream;
         try {
-            isStatementResults = QueryInvestigator.isConstruct(sparql) | QueryInvestigator.isInsertWhere(sparql);
-            if(isStatementResults) {
+            final TupleExpr tupleExpr = new SPARQLParser().parseQuery(sparql, null).getTupleExpr();
+            if(tupleExpr instanceof Reduced) {
                 getQueryResultStream = new KafkaGetQueryResultStream<>(params.kafkaIP, params.kafkaPort, VisibilityStatementDeserializer.class);
             } else {
                 getQueryResultStream = new KafkaGetQueryResultStream<>(params.kafkaIP, params.kafkaPort, VisibilityBindingSetDeserializer.class);
@@ -187,22 +172,12 @@ public class StreamResultsCommand implements RyaStreamsCommand {
             throw new ExecutionException("Could not parse the SPARQL for the query: " + sparql, e);
         }
 
-        // Iterate through the results and print them to the configured output mechanism.
-        try (final QueryResultStream<?> resultsStream = getQueryResultStream.fromStart(queryId)) {
-            final TupleExpr tupleExpr = new SPARQLParser().parseQuery(sparql, null).getTupleExpr();
-            if(params.outputPath != null) {
-                final Path file = Paths.get(params.outputPath);
-                try (final OutputStream out = Files.newOutputStream(file)) {
-                    if(isStatementResults) {
-                        final QueryResultStream<VisibilityStatement> stmtStream = (QueryResultStream<VisibilityStatement>) resultsStream;
-                        QueryResultsOutputUtil.toNtriplesFile(out, stmtStream, finished);
-                    } else {
-                        final QueryResultStream<VisibilityBindingSet> bsStream = (QueryResultStream<VisibilityBindingSet>) resultsStream;
-                        QueryResultsOutputUtil.toBindingSetJSONFile(out, tupleExpr, bsStream, finished);
-                    }
+        // Iterate through the results and print them to the console until the program or the stream ends.
+        try (final QueryResultStream<?> stream = getQueryResultStream.fromStart(params.ryaInstance, queryId)) {
+            while(!finished.get()) {
+                for(final Object result : stream.poll(1000)) {
+                    System.out.println(result);
                 }
-            } else {
-                streamToSystemOut(resultsStream, finished);
             }
         } catch (final Exception e) {
             System.err.println("Error while reading the results from the stream.");
@@ -210,15 +185,4 @@ public class StreamResultsCommand implements RyaStreamsCommand {
             System.exit(1);
         }
     }
-
-    private static void streamToSystemOut(final QueryResultStream<?> stream, final AtomicBoolean shutdownSignal) throws Exception {
-        requireNonNull(stream);
-        requireNonNull(shutdownSignal);
-
-        while(!shutdownSignal.get()) {
-            for(final Object result : stream.poll(1000)) {
-                System.out.println(result);
-            }
-        }
-    }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
index 5d63f32..176b920 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
@@ -184,7 +184,7 @@ public class RunQueryCommandIT {
             loadStatements.fromCollection(statements);
 
             // Read the output of the streams program.
-            final String resultsTopic = KafkaTopics.queryResultsTopic(sQuery.getQueryId());
+            final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, sQuery.getQueryId());
             resultConsumer.subscribe( Lists.newArrayList(resultsTopic) );
             results = KafkaTestUtil.pollForResults(500, 6, 3, resultConsumer);
         } finally {

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/geo/src/test/java/org/apache/rya/streams/kafka/processors/filter/GeoFilterIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/geo/src/test/java/org/apache/rya/streams/kafka/processors/filter/GeoFilterIT.java b/extras/rya.streams/geo/src/test/java/org/apache/rya/streams/kafka/processors/filter/GeoFilterIT.java
index c090afa..17a290a 100644
--- a/extras/rya.streams/geo/src/test/java/org/apache/rya/streams/kafka/processors/filter/GeoFilterIT.java
+++ b/extras/rya.streams/geo/src/test/java/org/apache/rya/streams/kafka/processors/filter/GeoFilterIT.java
@@ -88,7 +88,7 @@ public class GeoFilterIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Get the RDF model objects that will be used to build the query.
         final String sparql =

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/aggregation/AggregationProcessorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/aggregation/AggregationProcessorIT.java b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/aggregation/AggregationProcessorIT.java
index a4e4a3e..2a1e760 100644
--- a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/aggregation/AggregationProcessorIT.java
+++ b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/aggregation/AggregationProcessorIT.java
@@ -34,7 +34,6 @@ import org.apache.rya.streams.kafka.processors.aggregation.AggregationProcessorS
 import org.apache.rya.streams.kafka.serialization.VisibilityBindingSetDeserializer;
 import org.apache.rya.streams.kafka.topology.TopologyFactory;
 import org.apache.rya.test.kafka.KafkaTestInstanceRule;
-import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.openrdf.model.ValueFactory;
@@ -90,7 +89,7 @@ public class AggregationProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
@@ -137,7 +136,7 @@ public class AggregationProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
@@ -183,7 +182,7 @@ public class AggregationProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
@@ -233,7 +232,7 @@ public class AggregationProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
@@ -283,7 +282,7 @@ public class AggregationProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
@@ -371,7 +370,7 @@ public class AggregationProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
@@ -380,9 +379,7 @@ public class AggregationProcessorIT {
         RyaStreamsTestUtil.runStreamProcessingTest(kafka, statementsTopic, resultsTopic, builder, statements, expected, VisibilityBindingSetDeserializer.class);
     }
 
-    // Ignored because this test is kind of flakey.
     @Test
-    @Ignore
     public void multipleAggregations() throws Exception {
         // A query that figures out what the youngest and oldest ages are across all people.
         final String sparql =
@@ -436,7 +433,7 @@ public class AggregationProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final TopologyBuilder builder = new TopologyFactory().build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/FilterProcessorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/FilterProcessorIT.java b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/FilterProcessorIT.java
index aaa67ea..7fb228a 100644
--- a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/FilterProcessorIT.java
+++ b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/FilterProcessorIT.java
@@ -54,7 +54,7 @@ public class FilterProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Get the RDF model objects that will be used to build the query.
         final String sparql =

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/TemporalFilterIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/TemporalFilterIT.java b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/TemporalFilterIT.java
index 6e27669..11637b7 100644
--- a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/TemporalFilterIT.java
+++ b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/filter/TemporalFilterIT.java
@@ -85,7 +85,7 @@ public class TemporalFilterIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Get the RDF model objects that will be used to build the query.
         final String sparql =
@@ -119,7 +119,7 @@ public class TemporalFilterIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Get the RDF model objects that will be used to build the query.
         final String sparql =
@@ -153,7 +153,7 @@ public class TemporalFilterIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Get the RDF model objects that will be used to build the query.
         final String sparql =
@@ -187,7 +187,7 @@ public class TemporalFilterIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Get the RDF model objects that will be used to build the query.
         final String sparql =

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/join/JoinProcessorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/join/JoinProcessorIT.java b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/join/JoinProcessorIT.java
index bdb9be6..5f09372 100644
--- a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/join/JoinProcessorIT.java
+++ b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/join/JoinProcessorIT.java
@@ -69,7 +69,7 @@ public class JoinProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query =
@@ -120,7 +120,7 @@ public class JoinProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query =
@@ -171,7 +171,7 @@ public class JoinProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query =
@@ -228,7 +228,7 @@ public class JoinProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query =
@@ -269,7 +269,7 @@ public class JoinProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query =

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/MultiProjectionProcessorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/MultiProjectionProcessorIT.java b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/MultiProjectionProcessorIT.java
index a560294..c6fd1cf 100644
--- a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/MultiProjectionProcessorIT.java
+++ b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/MultiProjectionProcessorIT.java
@@ -28,7 +28,6 @@ import org.apache.kafka.streams.processor.TopologyBuilder;
 import org.apache.rya.api.model.VisibilityStatement;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.RyaStreamsTestUtil;
-import org.apache.rya.streams.kafka.processors.projection.MultiProjectionProcessorSupplier;
 import org.apache.rya.streams.kafka.processors.projection.MultiProjectionProcessorSupplier.MultiProjectionProcessor;
 import org.apache.rya.streams.kafka.serialization.VisibilityStatementDeserializer;
 import org.apache.rya.streams.kafka.topology.TopologyFactory;
@@ -54,7 +53,7 @@ public class MultiProjectionProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Create a topology for the Query that will be tested.
         final String sparql =

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/ProjectionProcessorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/ProjectionProcessorIT.java b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/ProjectionProcessorIT.java
index 322bba9..f53f2c4 100644
--- a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/ProjectionProcessorIT.java
+++ b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/projection/ProjectionProcessorIT.java
@@ -30,7 +30,6 @@ import org.apache.rya.api.model.VisibilityBindingSet;
 import org.apache.rya.api.model.VisibilityStatement;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.RyaStreamsTestUtil;
-import org.apache.rya.streams.kafka.processors.StatementPatternProcessorSupplier;
 import org.apache.rya.streams.kafka.processors.StatementPatternProcessorSupplier.StatementPatternProcessor;
 import org.apache.rya.streams.kafka.serialization.VisibilityBindingSetDeserializer;
 import org.apache.rya.streams.kafka.topology.TopologyFactory;
@@ -57,7 +56,7 @@ public class ProjectionProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Create a topology for the Query that will be tested.
         final String sparql =

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/sp/StatementPatternProcessorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/sp/StatementPatternProcessorIT.java b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/sp/StatementPatternProcessorIT.java
index ba11e57..fd0a48d 100644
--- a/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/sp/StatementPatternProcessorIT.java
+++ b/extras/rya.streams/integration/src/test/java/org/apache/rya/streams/kafka/processors/sp/StatementPatternProcessorIT.java
@@ -30,7 +30,6 @@ import org.apache.rya.api.model.VisibilityBindingSet;
 import org.apache.rya.api.model.VisibilityStatement;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.RyaStreamsTestUtil;
-import org.apache.rya.streams.kafka.processors.StatementPatternProcessorSupplier;
 import org.apache.rya.streams.kafka.processors.StatementPatternProcessorSupplier.StatementPatternProcessor;
 import org.apache.rya.streams.kafka.serialization.VisibilityBindingSetDeserializer;
 import org.apache.rya.streams.kafka.topology.TopologyFactory;
@@ -55,7 +54,7 @@ public class StatementPatternProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query = "SELECT * WHERE { ?person <urn:talksTo> ?otherPerson }";
@@ -85,7 +84,7 @@ public class StatementPatternProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query = "SELECT * WHERE { ?person <urn:talksTo> ?otherPerson }";
@@ -123,7 +122,7 @@ public class StatementPatternProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query = "SELECT * WHERE { "
@@ -157,7 +156,7 @@ public class StatementPatternProcessorIT {
         final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // Setup a topology.
         final String query = "SELECT * WHERE { "

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
index 989799a..f0cc842 100644
--- a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
@@ -62,7 +62,7 @@ public class KafkaTopics {
      * @param changeLogTopic - The topic to evaluate. (not null)
      * @return If the topic is well formatted, then the Rya instance name that was part of the topic name.
      */
-    public static Optional<String> getRyaInstance(final String changeLogTopic) {
+    public static Optional<String> getRyaInstanceFromQueryChangeLog(final String changeLogTopic) {
         requireNonNull(changeLogTopic);
 
         // Return absent if the provided topic does not represent a query change log topic.
@@ -93,9 +93,31 @@ public class KafkaTopics {
      * @param queryId - The id of the query the topic is for.
      * @return The name of the Kafka topic.
      */
-    public static String queryResultsTopic(final UUID queryId) {
+    public static String queryResultsTopic(final String ryaInstance, final UUID queryId) {
         requireNonNull(queryId);
-        return "QueryResults-" + queryId.toString();
+        return ryaInstance + "-QueryResults-" + queryId.toString();
+    }
+
+    /**
+     * TODO doc
+     *
+     * @param queryResultsTopic
+     * @return
+     */
+    public static String getRyaInstanceFromQueryResultsTopic(final String queryResultsTopic) {
+        // TODO
+        return "";
+    }
+
+    /**
+     * TODO doc
+     *
+     * @param queryResultsTopic
+     * @return
+     */
+    public static UUID getQueryIdFromQueryResultsTopic(final String queryResultsTopic) {
+        // TODO
+        return null;
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
index 8093951..63d64b9 100644
--- a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
@@ -78,7 +78,7 @@ public class SingleThreadKafkaStreamsFactory implements KafkaStreamsFactory {
 
         // Setup the topology that processes the Query.
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
-        final String resultsTopic = KafkaTopics.queryResultsTopic(query.getQueryId());
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, query.getQueryId());
 
         try {
             final TopologyBuilder topologyBuilder = topologyFactory.build(query.getSparql(), statementsTopic, resultsTopic, new RandomUUIDFactory());

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStream.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStream.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStream.java
index 529b493..d91edeb 100644
--- a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStream.java
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStream.java
@@ -66,22 +66,22 @@ public class KafkaGetQueryResultStream<T> implements GetQueryResultStream<T> {
     }
 
     @Override
-    public QueryResultStream<T> fromStart(final UUID queryId) throws RyaStreamsException {
+    public QueryResultStream<T> fromStart(final String ryaInstance, final UUID queryId) throws RyaStreamsException {
         requireNonNull(queryId);
 
         // Always start at the earliest point within the topic.
-        return makeStream(queryId, "earliest");
+        return makeStream(ryaInstance, queryId, "earliest");
     }
 
     @Override
-    public QueryResultStream<T> fromNow(final UUID queryId) throws RyaStreamsException {
+    public QueryResultStream<T> fromNow(final String ryaInstance, final UUID queryId) throws RyaStreamsException {
         requireNonNull(queryId);
 
         // Always start at the latest point within the topic.
-        return makeStream(queryId, "latest");
+        return makeStream(ryaInstance, queryId, "latest");
     }
 
-    private QueryResultStream<T> makeStream(final UUID queryId, final String autoOffsetResetConfig) {
+    private QueryResultStream<T> makeStream(final String ryaInstance, final UUID queryId, final String autoOffsetResetConfig) {
         // Configure which instance of Kafka to connect to.
         final Properties props = new Properties();
         props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
@@ -106,7 +106,7 @@ public class KafkaGetQueryResultStream<T> implements GetQueryResultStream<T> {
         final KafkaConsumer<String, T> consumer = new KafkaConsumer<>(props);
 
         // Register the consumer for the query's results.
-        final String resultTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
         consumer.subscribe(Arrays.asList(resultTopic));
 
         // Return the result stream.

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java
index a057de7..8eaf080 100644
--- a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java
+++ b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java
@@ -37,7 +37,7 @@ public class KafkaTopicsTest {
         final String topicName = KafkaTopics.queryChangeLogTopic(ryaInstance);
 
         // Show the rya instance name is able to be extracted from the topic.
-        final Optional<String> resolvedRyaInstance = KafkaTopics.getRyaInstance(topicName);
+        final Optional<String> resolvedRyaInstance = KafkaTopics.getRyaInstanceFromQueryChangeLog(topicName);
         assertEquals(ryaInstance, resolvedRyaInstance.get());
     }
 
@@ -47,7 +47,7 @@ public class KafkaTopicsTest {
         final String invalidTopic = "thisIsABadTopicName";
 
         // Show there is no Rya Instance name in it.
-        final Optional<String> ryaInstance = KafkaTopics.getRyaInstance(invalidTopic);
+        final Optional<String> ryaInstance = KafkaTopics.getRyaInstanceFromQueryChangeLog(invalidTopic);
         assertFalse( ryaInstance.isPresent() );
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStreamIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStreamIT.java b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStreamIT.java
index 8882753..59c08b7 100644
--- a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStreamIT.java
+++ b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaGetQueryResultStreamIT.java
@@ -85,6 +85,7 @@ public class KafkaGetQueryResultStreamIT {
     @Test
     public void fromStart() throws Exception {
         // Create an ID for the query.
+        final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
 
         // Create a list of test VisibilityBindingSets.
@@ -106,7 +107,7 @@ public class KafkaGetQueryResultStreamIT {
         // Write some entries to the query result topic in Kafka.
         try(final Producer<?, VisibilityBindingSet> producer =
                 KafkaTestUtil.makeProducer(kafka, StringSerializer.class, VisibilityBindingSetSerializer.class)) {
-            final String resultTopic = KafkaTopics.queryResultsTopic(queryId);
+            final String resultTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
             for(final VisibilityBindingSet visBs : original) {
                 producer.send(new ProducerRecord<>(resultTopic, visBs));
             }
@@ -115,7 +116,7 @@ public class KafkaGetQueryResultStreamIT {
         // Use the interactor that is being tested to read all of the visibility binding sets.
         final GetQueryResultStream<VisibilityBindingSet> interactor =
                 new KafkaGetQueryResultStream<>(kafka.getKafkaHostname(), kafka.getKafkaPort(), VisibilityBindingSetDeserializer.class);
-        final List<VisibilityBindingSet> read = pollForResults(500, 3, 3, interactor.fromStart(queryId));
+        final List<VisibilityBindingSet> read = pollForResults(500, 3, 3, interactor.fromStart(ryaInstance, queryId));
 
         // Show the fetched binding sets match the original, as well as their order.
         assertEquals(original, read);
@@ -124,11 +125,12 @@ public class KafkaGetQueryResultStreamIT {
     @Test
     public void fromNow() throws Exception {
         // Create an ID for the query.
+        final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
 
         try(final Producer<?, VisibilityBindingSet> producer =
                 KafkaTestUtil.makeProducer(kafka, StringSerializer.class, VisibilityBindingSetSerializer.class)) {
-            final String resultTopic = KafkaTopics.queryResultsTopic(queryId);
+            final String resultTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
             // Write a single visibility binding set to the query's result topic. This will not appear in the expected results.
             final ValueFactory vf = new ValueFactoryImpl();
@@ -140,7 +142,7 @@ public class KafkaGetQueryResultStreamIT {
             // Use the interactor that is being tested to read all of the visibility binding sets that appear after this point.
             final GetQueryResultStream<VisibilityBindingSet> interactor =
                     new KafkaGetQueryResultStream<>(kafka.getKafkaHostname(), kafka.getKafkaPort(), VisibilityBindingSetDeserializer.class);
-            try(QueryResultStream<VisibilityBindingSet> results = interactor.fromNow(queryId)) {
+            try(QueryResultStream<VisibilityBindingSet> results = interactor.fromNow(ryaInstance, queryId)) {
                 // Read results from the stream.
                 List<VisibilityBindingSet> read = new ArrayList<>();
                 for(final VisibilityBindingSet visBs : results.poll(500)) {
@@ -178,12 +180,13 @@ public class KafkaGetQueryResultStreamIT {
     @Test(expected = IllegalStateException.class)
     public void pollClosedStream() throws Exception {
         // Create an ID for the query.
+        final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
 
         // Use the interactor that is being tested to create a result stream and immediately close it.
         final GetQueryResultStream<VisibilityBindingSet> interactor =
                 new KafkaGetQueryResultStream<>(kafka.getKafkaHostname(), kafka.getKafkaPort(), VisibilityBindingSetDeserializer.class);
-        final QueryResultStream<VisibilityBindingSet> results = interactor.fromStart(queryId);
+        final QueryResultStream<VisibilityBindingSet> results = interactor.fromStart(ryaInstance, queryId);
         results.close();
 
         // Try to poll the closed stream.
@@ -193,6 +196,7 @@ public class KafkaGetQueryResultStreamIT {
     @Test
     public void fromStart_visibilityStatements() throws Exception {
         // Create an ID for the query.
+        final String ryaInstance = UUID.randomUUID().toString();
         final UUID queryId = UUID.randomUUID();
 
         // Create some statements that will be written to the result topic.
@@ -205,7 +209,7 @@ public class KafkaGetQueryResultStreamIT {
         // Write the entries to the query result topic in Kafka.
         try(final Producer<?, VisibilityStatement> producer =
                 KafkaTestUtil.makeProducer(kafka, StringSerializer.class, VisibilityStatementSerializer.class)) {
-            final String resultTopic = KafkaTopics.queryResultsTopic(queryId);
+            final String resultTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
             for(final VisibilityStatement visStmt : original) {
                 producer.send(new ProducerRecord<>(resultTopic, visStmt));
             }
@@ -214,7 +218,7 @@ public class KafkaGetQueryResultStreamIT {
         // Use the interactor that is being tested to read all of the visibility binding sets.
         final GetQueryResultStream<VisibilityStatement> interactor =
                 new KafkaGetQueryResultStream<>(kafka.getKafkaHostname(), kafka.getKafkaPort(), VisibilityStatementDeserializer.class);
-        final List<VisibilityStatement> read = pollForResults(500, 3, 3, interactor.fromStart(queryId));
+        final List<VisibilityStatement> read = pollForResults(500, 3, 3, interactor.fromStart(ryaInstance, queryId));
 
         // Show the fetched binding sets match the original, as well as their order.
         assertEquals(original, read);

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
index 5dbd27f..c9abb41 100644
--- a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
+++ b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
@@ -90,7 +90,7 @@ public class KafkaRunQueryIT {
         // Add the query to the query repository.
         final StreamsQuery sQuery = queries.add("SELECT * WHERE { ?person <urn:worksAt> ?business . }", true);
         final UUID queryId = sQuery.getQueryId();
-        final String resultsTopic = KafkaTopics.queryResultsTopic(queryId);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
 
         // The thread that will run the tested interactor.
         final Thread testThread = new Thread() {

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
index e746baf..2aa7054 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
@@ -171,11 +171,11 @@ public class KafkaQueryChangeLogSource extends AbstractScheduledService implemen
             final Set<String> changeLogTopics = new HashSet<>( listTopicsConsumer.listTopics().keySet() );
 
             // Remove all topics that are not valid Rya Query Change Log topic names.
-            changeLogTopics.removeIf( topic -> !KafkaTopics.getRyaInstance(topic).isPresent() );
+            changeLogTopics.removeIf( topic -> !KafkaTopics.getRyaInstanceFromQueryChangeLog(topic).isPresent() );
 
             // Extract the Rya instance names from the change log topics.
             final Set<String> ryaInstances = changeLogTopics.stream()
-                    .map(topic -> KafkaTopics.getRyaInstance(topic).get() )
+                    .map(topic -> KafkaTopics.getRyaInstanceFromQueryChangeLog(topic).get() )
                     .collect(Collectors.toSet());
 
             // Any Rya instances that are in the old set of topics, but not the new one, have been deleted.

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
index 3a59636..4bd022a 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
@@ -128,7 +128,7 @@ public class LocalQueryExecutor extends AbstractIdleService implements QueryExec
             // Make sure the Statements topic exists for the query.
             final Set<String> topics = Sets.newHashSet(
                     KafkaTopics.statementsTopic(ryaInstance),
-                    KafkaTopics.queryResultsTopic(query.getQueryId()));
+                    KafkaTopics.queryResultsTopic(ryaInstance, query.getQueryId()));
 
             // Make sure the Query Results topic exists for the query.
             createKafkaTopic.createTopics(topics, 1, 1);

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/e07390d3/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
index f9c8a03..6358104 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
@@ -138,7 +138,7 @@ public class LocalQueryExecutorIT {
             loadStatements.fromCollection(statements);
 
             // Read the output of the streams program.
-            final String resultsTopic = KafkaTopics.queryResultsTopic(sQuery.getQueryId());
+            final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, sQuery.getQueryId());
             resultConsumer.subscribe( Lists.newArrayList(resultsTopic) );
             final List<VisibilityBindingSet> results = KafkaTestUtil.pollForResults(500, 6, 3, resultConsumer);
             assertEquals(expected, results);


[08/22] incubator-rya git commit: RYA-458 Updating the configuration XML so that you may only specify a single QueryChangeLogSource.

Posted by pu...@apache.org.
RYA-458 Updating the configuration XML so that you may only specify a single QueryChangeLogSource.



Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/a31e256c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/a31e256c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/a31e256c

Branch: refs/heads/master
Commit: a31e256c3a4b32b3ea256634ebca6b4d7438b9d3
Parents: ee29450
Author: kchilton2 <ke...@gmail.com>
Authored: Fri Jan 26 12:06:07 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:44 2018 -0500

----------------------------------------------------------------------
 .../src/main/config/configuration.xml           | 22 +++++++--------
 .../src/main/xsd/QueryManagerConfig.xsd         | 14 +++-------
 .../xml/QueryManagerConfigMarshallerTest.java   | 28 +++++++++-----------
 3 files changed, 26 insertions(+), 38 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a31e256c/extras/rya.streams/query-manager/src/main/config/configuration.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/config/configuration.xml b/extras/rya.streams/query-manager/src/main/config/configuration.xml
index b78900e..a5e3fb6 100644
--- a/extras/rya.streams/query-manager/src/main/config/configuration.xml
+++ b/extras/rya.streams/query-manager/src/main/config/configuration.xml
@@ -18,19 +18,17 @@ specific language governing permissions and limitations
 under the License.
 -->
 <queryManagerConfig>
-    <!-- A list of Query Change Log Sources. A source needs to be defined for
-       - every system that is used to manage Rya Streams Query Change Logs.
-       - The query manager will manage queries for all Rya instances whose
-       - change logs are stored within those sources.
+    <!-- The  Query Change Log Sources. The source defines a system where Rya
+       - Streams Query Change Logs are managed. The query manager will manage 
+       - queries for all Rya instances whose change logs are stored within the
+       - source.
        -->
-    <queryChangeLogSources>
-        <queryChangeLogSource>
-            <kafka>
-                <hostname>[Kafka Broker Hostname]</hostname>
-                <port>[Kafka Broker Port]</port>
-            </kafka>
-        </queryChangeLogSource>
-    </queryChangeLogSources>
+    <queryChangeLogSource>
+        <kafka>
+            <hostname>[Kafka Broker Hostname]</hostname>
+            <port>[Kafka Broker Port]</port>
+        </kafka>
+    </queryChangeLogSource>
     
     <!-- This section defines performance related tuning values. Sensible
        - default have been provided to simplify configuration. 

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a31e256c/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd b/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
index 17d667f..c1285d4 100644
--- a/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
+++ b/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
@@ -23,17 +23,11 @@ under the License.
   <xs:element name="queryManagerConfig">
     <xs:complexType>
       <xs:sequence>
-        <xs:element name="queryChangeLogSources">
+        <xs:element name="queryChangeLogSource">
           <xs:complexType>
-            <xs:sequence>
-              <xs:element name="queryChangeLogSource" maxOccurs="unbounded">
-                <xs:complexType>
-                  <xs:choice>
-                    <xs:element name="kafka" type="kafka"/>
-                  </xs:choice>
-                </xs:complexType>
-              </xs:element>
-            </xs:sequence>
+            <xs:choice>
+              <xs:element name="kafka" type="kafka"/>
+            </xs:choice>
           </xs:complexType>
         </xs:element>
         <xs:element name="performanceTunning">

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a31e256c/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
index bc8a040..831c06b 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
@@ -36,14 +36,12 @@ public class QueryManagerConfigMarshallerTest {
         final String xml =
                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                 "<queryManagerConfig>\n" +
-                "    <queryChangeLogSources>\n" +
-                "        <queryChangeLogSource>\n" +
-                "            <kafka>\n" +
-                "                <hostname>localhost</hostname>\n" +
-                "                <port>6</port>\n" +
-                "            </kafka>\n" +
-                "        </queryChangeLogSource>\n" +
-                "    </queryChangeLogSources>\n" +
+                "    <queryChangeLogSource>\n" +
+                "        <kafka>\n" +
+                "            <hostname>localhost</hostname>\n" +
+                "            <port>6</port>\n" +
+                "        </kafka>\n" +
+                "    </queryChangeLogSource>\n" +
                 "    <performanceTunning>\n" +
                 "        <queryChanngeLogDiscoveryPeriod>\n" +
                 "            <value>1</value>\n" +
@@ -62,14 +60,12 @@ public class QueryManagerConfigMarshallerTest {
         final String xml =
                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                 "<queryManagerConfig>\n" +
-                "    <queryChangeLogSources>\n" +
-                "        <queryChangeLogSource>\n" +
-                "            <kafka>\n" +
-                "                <hostname>localhost</hostname>\n" +
-                "                <port>6</port>\n" +
-                "            </kafka>\n" +
-                "        </queryChangeLogSource>\n" +
-                "    </queryChangeLogSources>\n" +
+                "    <queryChangeLogSource>\n" +
+                "        <kafka>\n" +
+                "            <hostname>localhost</hostname>\n" +
+                "            <port>6</port>\n" +
+                "        </kafka>\n" +
+                "    </queryChangeLogSource>\n" +
                 "</queryManagerConfig>";
 
 


[15/22] incubator-rya git commit: RYA-451 Fixing threading issues with the QueryManager class.

Posted by pu...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
index 947a215..3a59636 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
@@ -32,10 +32,15 @@ import org.apache.kafka.streams.KafkaStreams;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.kafka.KafkaStreamsFactory;
 import org.apache.rya.streams.kafka.KafkaStreamsFactory.KafkaStreamsFactoryException;
+import org.apache.rya.streams.kafka.KafkaTopics;
+import org.apache.rya.streams.kafka.interactor.CreateKafkaTopic;
 import org.apache.rya.streams.querymanager.QueryExecutor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.Multimap;
+import com.google.common.collect.Sets;
 import com.google.common.util.concurrent.AbstractIdleService;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
@@ -50,6 +55,7 @@ import kafka.consumer.KafkaStream;
  */
 @DefaultAnnotation(NonNull.class)
 public class LocalQueryExecutor extends AbstractIdleService implements QueryExecutor {
+    private static final Logger log = LoggerFactory.getLogger(LocalQueryExecutor.class);
 
     /**
      * Provides thread safety when interacting with this class.
@@ -72,6 +78,11 @@ public class LocalQueryExecutor extends AbstractIdleService implements QueryExec
     private final Map<UUID, KafkaStreams> byQueryId = new HashMap<>();
 
     /**
+     * Used to create the input and output topics for a Kafka Streams job.
+     */
+    private final CreateKafkaTopic createKafkaTopic;
+
+    /**
      * Builds the {@link KafkaStreams} objects that execute {@link KafkaStream}s.
      */
     private final KafkaStreamsFactory streamsFactory;
@@ -79,23 +90,31 @@ public class LocalQueryExecutor extends AbstractIdleService implements QueryExec
     /**
      * Constructs an instance of {@link LocalQueryExecutor}.
      *
+     * @param createKafkaTopic - Used to create the input and output topics for a Kafka Streams job. (not null)
      * @param streamsFactory - Builds the {@link KafkaStreams} objects that execute {@link KafkaStream}s. (not null)
      */
-    public LocalQueryExecutor(final KafkaStreamsFactory streamsFactory) {
+    public LocalQueryExecutor(
+            final CreateKafkaTopic createKafkaTopic,
+            final KafkaStreamsFactory streamsFactory) {
+        this.createKafkaTopic = requireNonNull(createKafkaTopic);
         this.streamsFactory = requireNonNull(streamsFactory);
     }
 
     @Override
     protected void startUp() throws Exception {
-        // Nothing to do.
+        log.info("Local Query Executor starting up.");
     }
 
     @Override
     protected void shutDown() throws Exception {
+        log.info("Local Query Executor shutting down. Stopping all jobs...");
+
         // Stop all of the running queries.
         for(final KafkaStreams job : byQueryId.values()) {
             job.close();
         }
+
+        log.info("Local Query Executor shut down.");
     }
 
     @Override
@@ -106,6 +125,14 @@ public class LocalQueryExecutor extends AbstractIdleService implements QueryExec
 
         lock.lock();
         try {
+            // Make sure the Statements topic exists for the query.
+            final Set<String> topics = Sets.newHashSet(
+                    KafkaTopics.statementsTopic(ryaInstance),
+                    KafkaTopics.queryResultsTopic(query.getQueryId()));
+
+            // Make sure the Query Results topic exists for the query.
+            createKafkaTopic.createTopics(topics, 1, 1);
+
             // Setup the Kafka Streams job that will execute.
             final KafkaStreams streams = streamsFactory.make(ryaInstance, query);
             streams.start();

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd b/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
index c1285d4..21170bb 100644
--- a/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
+++ b/extras/rya.streams/query-manager/src/main/xsd/QueryManagerConfig.xsd
@@ -30,6 +30,13 @@ under the License.
             </xs:choice>
           </xs:complexType>
         </xs:element>
+        <xs:element name="queryExecutor">
+            <xs:complexType>
+              <xs:choice>
+                <xs:element name="localKafkaStreams" type="localKafkaStreams"/>
+              </xs:choice>
+            </xs:complexType>
+        </xs:element>
         <xs:element name="performanceTunning">
           <xs:complexType>
             <xs:sequence>
@@ -65,6 +72,13 @@ under the License.
     </xs:sequence>
   </xs:complexType>
   
+  <!-- Define what a local Kafka Streams query executor looks like. -->
+  <xs:complexType name="localKafkaStreams">
+    <xs:sequence>
+      <xs:element name="zookeepers" type="xs:string"/>
+    </xs:sequence>
+  </xs:complexType>
+  
   <!-- Define the legal range for a TCP port. -->
   <xs:simpleType name="tcpPort">
     <xs:restriction base="xs:int">

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkGeneratorTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkGeneratorTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkGeneratorTest.java
new file mode 100644
index 0000000..da9be78
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkGeneratorTest.java
@@ -0,0 +1,136 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.rya.streams.api.queries.QueryChangeLog;
+import org.apache.rya.streams.querymanager.QueryManager.LogEvent;
+import org.apache.rya.streams.querymanager.QueryManager.LogEvent.LogEventType;
+import org.apache.rya.streams.querymanager.QueryManager.LogEventWorkGenerator;
+import org.junit.Test;
+
+/**
+ * Unit tests the methods of {@link LogEventWorkGenerator}.
+ */
+public class LogEventWorkGeneratorTest {
+
+    @Test
+    public void shutdownSignalKillsThread() {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<LogEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the LogEventWorkGenerator work.
+        final LogEventWorkGenerator generator = new LogEventWorkGenerator(queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with a created change log.
+        final Thread notifyThread = new Thread(() -> {
+            generator.notifyCreate("rya", mock(QueryChangeLog.class));
+        });
+
+        // Fill the queue so that nothing may be offered to it.
+        queue.offer(LogEvent.delete("rya"));
+
+        // Start the thread and show that it is still alive after the offer period.
+        notifyThread.start();
+        assertTrue( ThreadUtil.stillAlive(notifyThread, 200) );
+
+        // Set the shutdown signal to true and join the thread. If we were able to join, then it shut down.
+        shutdownSignal.set(true);
+        assertFalse( ThreadUtil.stillAlive(notifyThread, 1000) );
+    }
+
+    @Test
+    public void notifyCreate() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<LogEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the LogEventWorkGenerator work.
+        final LogEventWorkGenerator generator = new LogEventWorkGenerator(queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with a created change log.
+        final CountDownLatch notified = new CountDownLatch(1);
+        final Thread notifyThread = new Thread(() -> {
+            generator.notifyCreate("rya", mock(QueryChangeLog.class));
+            notified.countDown();
+        });
+
+        try {
+            // Start the thread that performs the notification.
+            notifyThread.start();
+
+            // Wait for the thread to indicate it has notified and check the queue for the value.
+            notified.await(200, TimeUnit.MILLISECONDS);
+            final LogEvent event = queue.poll(200, TimeUnit.MILLISECONDS);
+            assertEquals(LogEventType.CREATE, event.getEventType());
+            assertEquals("rya", event.getRyaInstanceName());
+        } finally {
+            shutdownSignal.set(true);
+            notifyThread.join();
+        }
+    }
+
+    @Test
+    public void notifyDelete() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<LogEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the LogEventWorkGenerator work.
+        final LogEventWorkGenerator generator = new LogEventWorkGenerator(queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with a deleted change log.
+        final CountDownLatch notified = new CountDownLatch(1);
+        final Thread notifyThread = new Thread(() -> {
+            generator.notifyDelete("rya");
+            notified.countDown();
+        });
+
+        try {
+            // Start the thread that performs the notification.
+            notifyThread.start();
+
+            // Wait for the thread to indicate it has notified and check the queue for the value.
+            notified.await(200, TimeUnit.MILLISECONDS);
+            final LogEvent event = queue.poll(200, TimeUnit.MILLISECONDS);
+            assertEquals(LogEventType.DELETE, event.getEventType());
+            assertEquals("rya", event.getRyaInstanceName());
+        } finally {
+            shutdownSignal.set(true);
+            notifyThread.join();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java
new file mode 100644
index 0000000..cb708ed
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/LogEventWorkerTest.java
@@ -0,0 +1,245 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.api.queries.InMemoryQueryChangeLog;
+import org.apache.rya.streams.api.queries.QueryChange;
+import org.apache.rya.streams.api.queries.QueryChangeLog;
+import org.apache.rya.streams.querymanager.QueryManager.LogEvent;
+import org.apache.rya.streams.querymanager.QueryManager.LogEventWorker;
+import org.apache.rya.streams.querymanager.QueryManager.QueryEvent;
+import org.junit.Test;
+
+/**
+ * Unit tests the methods of {@link LogEventWorker}.
+ */
+public class LogEventWorkerTest {
+
+    @Test
+    public void shutdownSignalKillsThread() {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The thread that will perform the LogEventWorker task.
+        final Thread logEventWorker = new Thread(new LogEventWorker(new ArrayBlockingQueue<>(1),
+                new ArrayBlockingQueue<>(1), 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        logEventWorker.start();
+
+        // Wait longer than the poll time to see if the thread died. Show that it is still running.
+        assertTrue(ThreadUtil.stillAlive(logEventWorker, 200));
+
+        // Set the shutdown signal to true and join the thread. If we were able to join, then it shut down.
+        shutdownSignal.set(true);
+        assertFalse(ThreadUtil.stillAlive(logEventWorker, 500));
+    }
+
+    @Test
+    public void nofity_logCreated_doesNotExist() throws Exception {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue used to feed work.
+        final BlockingQueue<LogEvent> logEventQueue = new ArrayBlockingQueue<>(10);
+
+        // The queue work is written to.
+        final BlockingQueue<QueryEvent> queryEventQueue = new ArrayBlockingQueue<>(10);
+
+        // The Query Change Log that will be watched.
+        final QueryChangeLog changeLog = new InMemoryQueryChangeLog();
+
+        // Write a message that indicates a new query should be active.
+        final UUID firstQueryId = UUID.randomUUID();
+        changeLog.write(QueryChange.create(firstQueryId, "select * where { ?a ?b ?c . }", true));
+
+        // Write a message that adds an active query, but then makes it inactive. Because both of these
+        // events are written to the log before the worker subscribes to the repository for updates, they
+        // must result in a single query stopped event.
+        final UUID secondQueryId = UUID.randomUUID();
+        changeLog.write(QueryChange.create(secondQueryId, "select * where { ?d ?e ?f . }", true));
+        changeLog.write(QueryChange.update(secondQueryId, false));
+
+        // Start the worker that will be tested.
+        final Thread logEventWorker = new Thread(new LogEventWorker(logEventQueue,
+                queryEventQueue, 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        logEventWorker.start();
+
+        try {
+            // Write a unit of work that indicates a log was created.
+            final LogEvent createLogEvent = LogEvent.create("rya", changeLog);
+            logEventQueue.offer(createLogEvent);
+
+            // We must see the following Query Events added to the work queue.
+            // Query 1, executing.
+            // Query 2, stopped.
+            Set<QueryEvent> expectedEvents = new HashSet<>();
+            expectedEvents.add(QueryEvent.executing("rya",
+                    new StreamsQuery(firstQueryId, "select * where { ?a ?b ?c . }", true)));
+            expectedEvents.add(QueryEvent.stopped("rya", secondQueryId));
+
+            Set<QueryEvent> queryEvents = new HashSet<>();
+            queryEvents.add( queryEventQueue.poll(500, TimeUnit.MILLISECONDS) );
+            queryEvents.add( queryEventQueue.poll(500, TimeUnit.MILLISECONDS) );
+
+            assertEquals(expectedEvents, queryEvents);
+
+            // Write an event to the change log that stops the first query.
+            changeLog.write(QueryChange.update(firstQueryId, false));
+
+            // Show it was also reflected in the changes.
+            // Query 1, stopped.
+            expectedEvents = new HashSet<>();
+            expectedEvents.add(QueryEvent.stopped("rya", firstQueryId));
+
+            queryEvents = new HashSet<>();
+            queryEvents.add( queryEventQueue.poll(500, TimeUnit.MILLISECONDS) );
+
+            assertEquals(expectedEvents, queryEvents);
+        } finally {
+            shutdownSignal.set(true);
+            logEventWorker.join();
+        }
+    }
+
+    @Test
+    public void nofity_logCreated_exists() throws Exception {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue used to feed work.
+        final BlockingQueue<LogEvent> logEventQueue = new ArrayBlockingQueue<>(10);
+
+        // The queue work is written to.
+        final BlockingQueue<QueryEvent> queryEventQueue = new ArrayBlockingQueue<>(10);
+
+        // The Query Change Log that will be watched.
+        final QueryChangeLog changeLog = new InMemoryQueryChangeLog();
+
+        // Write a message that indicates a new query should be active.
+        final UUID firstQueryId = UUID.randomUUID();
+        changeLog.write(QueryChange.create(firstQueryId, "select * where { ?a ?b ?c . }", true));
+
+        // Start the worker that will be tested.
+        final Thread logEventWorker = new Thread(new LogEventWorker(logEventQueue,
+                queryEventQueue, 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        logEventWorker.start();
+
+        try {
+            // Write a unit of work that indicates a log was created.
+            final LogEvent createLogEvent = LogEvent.create("rya", changeLog);
+            logEventQueue.offer(createLogEvent);
+
+            // Say the same log was created a second time.
+            logEventQueue.offer(createLogEvent);
+
+            // Show that only a single unit of work was added for the log. This indicates the
+            // second message was effectively skipped as it would have add its work added twice otherwise.
+            final Set<QueryEvent> expectedEvents = new HashSet<>();
+            expectedEvents.add(QueryEvent.executing("rya",
+                    new StreamsQuery(firstQueryId, "select * where { ?a ?b ?c . }", true)));
+
+            final Set<QueryEvent> queryEvents = new HashSet<>();
+            queryEvents.add( queryEventQueue.poll(500, TimeUnit.MILLISECONDS) );
+
+            assertNull(queryEventQueue.poll(500, TimeUnit.MILLISECONDS));
+            assertEquals(expectedEvents, queryEvents);
+        } finally {
+            shutdownSignal.set(true);
+            logEventWorker.join();
+        }
+    }
+
+    @Test
+    public void notify_logDeleted_exists() throws Exception {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue used to feed work.
+        final BlockingQueue<LogEvent> logEventQueue = new ArrayBlockingQueue<>(10);
+
+        // The queue work is written to.
+        final BlockingQueue<QueryEvent> queryEventQueue = new ArrayBlockingQueue<>(10);
+
+        // The Query Change Log that will be watched.
+        final QueryChangeLog changeLog = new InMemoryQueryChangeLog();
+
+        // Start the worker that will be tested.
+        final Thread logEventWorker = new Thread(new LogEventWorker(logEventQueue,
+                queryEventQueue, 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        logEventWorker.start();
+
+        try {
+            // Write a unit of work that indicates a log was created.
+            final LogEvent createLogEvent = LogEvent.create("rya", changeLog);
+            logEventQueue.offer(createLogEvent);
+
+            // Write a unit of work that indicates a log was deleted.
+            logEventQueue.offer(LogEvent.delete("rya"));
+
+            // Show that a single unit of work was created for deleting everything for "rya".
+            assertEquals(QueryEvent.stopALL("rya"),  queryEventQueue.poll(500, TimeUnit.MILLISECONDS));
+            assertNull(queryEventQueue.poll(500, TimeUnit.MILLISECONDS));
+        } finally {
+            shutdownSignal.set(true);
+            logEventWorker.join();
+        }
+    }
+
+    @Test
+    public void notify_logDeleted_doesNotExist() throws Exception {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue used to feed work.
+        final BlockingQueue<LogEvent> logEventQueue = new ArrayBlockingQueue<>(10);
+
+        // The queue work is written to.
+        final BlockingQueue<QueryEvent> queryEventQueue = new ArrayBlockingQueue<>(10);
+
+        // Start the worker that will be tested.
+        final Thread logEventWorker = new Thread(new LogEventWorker(logEventQueue,
+                queryEventQueue, 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        logEventWorker.start();
+
+        try {
+            // Write a unit of work that indicates a log was deleted. Since it was never created,
+            // this will not cause anything to be written to the QueryEvent queue.
+            logEventQueue.offer(LogEvent.delete("rya"));
+
+            // Show that a single unit of work was created for deleting everything for "rya".
+            assertNull(queryEventQueue.poll(500, TimeUnit.MILLISECONDS));
+        } finally {
+            shutdownSignal.set(true);
+            logEventWorker.join();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java
new file mode 100644
index 0000000..4495e19
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkGeneratorTest.java
@@ -0,0 +1,265 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.api.queries.ChangeLogEntry;
+import org.apache.rya.streams.api.queries.QueryChange;
+import org.apache.rya.streams.querymanager.QueryManager.QueryEvent;
+import org.apache.rya.streams.querymanager.QueryManager.QueryEventWorkGenerator;
+import org.junit.Test;
+
+/**
+ * Unit tests the methods of {@link QueryEventWorkGenerator}.
+ */
+public class QueryEventWorkGeneratorTest {
+
+    @Test
+    public void shutdownSignalKillsThread() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the QueryEventWorkGenerator work.
+        final QueryEventWorkGenerator generator =
+                new QueryEventWorkGenerator("rya", new CountDownLatch(1), queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with a created query.
+        final Thread notifyThread = new Thread(() -> {
+            generator.notify(mock(ChangeLogEntry.class), Optional.empty());
+        });
+
+        // Fill the queue so that nothing may be offered to it.
+        queue.offer(QueryEvent.stopALL("rya"));
+
+        // Start the thread and show that it is still alive after the offer period.
+        notifyThread.start();
+        assertTrue( ThreadUtil.stillAlive(notifyThread, 200) );
+
+        // Set the shutdown signal to true and join the thread. If we were able to join, then it shut down.
+        shutdownSignal.set(true);
+        assertFalse( ThreadUtil.stillAlive(notifyThread, 1000) );
+    }
+
+    @Test
+    public void waitsForSubscriptionWork() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the QueryEventWorkGenerator work.
+        final CountDownLatch latch = new CountDownLatch(1);
+        final QueryEventWorkGenerator generator =
+                new QueryEventWorkGenerator("rya", latch, queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with a created query.
+        final UUID queryId = UUID.randomUUID();
+        final StreamsQuery query = new StreamsQuery(queryId, "query", true);
+        final Thread notifyThread = new Thread(() -> {
+            final QueryChange change = QueryChange.create(queryId, query.getSparql(), query.isActive());
+            final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
+            generator.notify(entry, Optional.of(query));
+        });
+
+        // Start the thread.
+        notifyThread.start();
+
+        try {
+            // Wait longer than the blocking period and show the thread is still alive and nothing has been added
+            // to the work queue.
+            Thread.sleep(150);
+            assertTrue( notifyThread.isAlive() );
+
+            // Count down the latch.
+            latch.countDown();
+
+            // Show work was added to the queue and the notifying thread died.
+            final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
+            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive()));
+            assertEquals(expected, event);
+        } finally {
+            shutdownSignal.set(true);
+            notifyThread.join();
+        }
+    }
+
+    @Test
+    public void notifyCreate() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the QueryEventWorkGenerator work.
+        final CountDownLatch latch = new CountDownLatch(1);
+        latch.countDown();
+        final QueryEventWorkGenerator generator =
+                new QueryEventWorkGenerator("rya", latch, queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with a created query.
+        final UUID queryId = UUID.randomUUID();
+        final StreamsQuery query = new StreamsQuery(queryId, "query", true);
+        final Thread notifyThread = new Thread(() -> {
+            final QueryChange change = QueryChange.create(queryId, query.getSparql(), query.isActive());
+            final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
+            generator.notify(entry, Optional.of(query));
+        });
+
+        // Start the thread.
+        notifyThread.start();
+
+        try {
+            // Show work was added to the queue and the notifying thread died.
+            final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
+            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive()));
+            assertEquals(expected, event);
+        } finally {
+            shutdownSignal.set(true);
+            notifyThread.join();
+        }
+    }
+
+    @Test
+    public void notifyDelete() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the QueryEventWorkGenerator work.
+        final CountDownLatch latch = new CountDownLatch(1);
+        latch.countDown();
+        final QueryEventWorkGenerator generator =
+                new QueryEventWorkGenerator("rya", latch, queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with a deleted query.
+        final UUID queryId = UUID.randomUUID();
+        final Thread notifyThread = new Thread(() -> {
+            final QueryChange change = QueryChange.delete(queryId);
+            final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
+            generator.notify(entry, Optional.empty());
+        });
+
+        // Start the thread.
+        notifyThread.start();
+
+        try {
+            // Show work was added to the queue and the notifying thread died.
+            final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
+            final QueryEvent expected = QueryEvent.stopped("rya", queryId);
+            assertEquals(expected, event);
+        } finally {
+            shutdownSignal.set(true);
+            notifyThread.join();
+        }
+    }
+
+    @Test
+    public void notifyUpdate_isActive() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the QueryEventWorkGenerator work.
+        final CountDownLatch latch = new CountDownLatch(1);
+        latch.countDown();
+        final QueryEventWorkGenerator generator =
+                new QueryEventWorkGenerator("rya", latch, queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with an update query change.
+        final UUID queryId = UUID.randomUUID();
+        final StreamsQuery query = new StreamsQuery(queryId, "query", true);
+        final Thread notifyThread = new Thread(() -> {
+            final QueryChange change = QueryChange.update(queryId, true);
+            final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
+            generator.notify(entry, Optional.of(query));
+        });
+
+        // Start the thread.
+        notifyThread.start();
+
+        try {
+            // Show work was added to the queue and the notifying thread died.
+            final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
+            final QueryEvent expected = QueryEvent.executing("rya", new StreamsQuery(queryId, query.getSparql(), query.isActive()));
+            assertEquals(expected, event);
+        } finally {
+            shutdownSignal.set(true);
+            notifyThread.join();
+        }
+    }
+
+    @Test
+    public void notifyUpdate_isNotActive() throws Exception {
+        // The signal that will kill the notifying thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue generated work is offered to.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The listener that will perform the QueryEventWorkGenerator work.
+        final CountDownLatch latch = new CountDownLatch(1);
+        latch.countDown();
+        final QueryEventWorkGenerator generator =
+                new QueryEventWorkGenerator("rya", latch, queue, 50, TimeUnit.MILLISECONDS, shutdownSignal);
+
+        // A thread that will attempt to notify the generator with an update query change.
+        final UUID queryId = UUID.randomUUID();
+        final StreamsQuery query = new StreamsQuery(queryId, "query", false);
+        final Thread notifyThread = new Thread(() -> {
+            final QueryChange change = QueryChange.update(queryId, false);
+            final ChangeLogEntry<QueryChange> entry = new ChangeLogEntry<>(0, change);
+            generator.notify(entry, Optional.of(query));
+        });
+
+        // Start the thread.
+        notifyThread.start();
+
+        try {
+            // Show work was added to the queue and the notifying thread died.
+            final QueryEvent event = queue.poll(500, TimeUnit.MILLISECONDS);
+            final QueryEvent expected = QueryEvent.stopped("rya", queryId);
+            assertEquals(expected, event);
+        } finally {
+            shutdownSignal.set(true);
+            notifyThread.join();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java
new file mode 100644
index 0000000..33c0719
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryEventWorkerTest.java
@@ -0,0 +1,172 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+
+import java.util.UUID;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.querymanager.QueryManager.QueryEvent;
+import org.apache.rya.streams.querymanager.QueryManager.QueryEventWorker;
+import org.junit.Test;
+
+/**
+ * Unit tests the methods of {@link QueryManager.QueryEventWorker}.
+ */
+public class QueryEventWorkerTest {
+
+    @Test
+    public void shutdownSignalKillsThread() {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The thread that will perform the QueryEventWorker task.
+        final Thread queryEventWorker = new Thread(new QueryEventWorker(new ArrayBlockingQueue<>(1),
+                mock(QueryExecutor.class), 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        queryEventWorker.start();
+
+        // Wait longer than the poll time to see if the thread died. Show that it is still running.
+        assertTrue(ThreadUtil.stillAlive(queryEventWorker, 200));
+
+        // Set the shutdown signal to true and join the thread. If we were able to join, then it shut down.
+        shutdownSignal.set(true);
+        assertFalse(ThreadUtil.stillAlive(queryEventWorker, 1000));
+    }
+
+    @Test
+    public void executingWork() throws Exception {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue used to send the execute work to the thread.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The message that indicates a query needs to be executed.
+        final String ryaInstance = "rya";
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "sparql", true);
+        final QueryEvent executingEvent = QueryEvent.executing(ryaInstance, query);
+
+        // Release a latch if the startQuery method on the queryExecutor is invoked with the correct values.
+        final CountDownLatch startQueryInvoked = new CountDownLatch(1);
+        final QueryExecutor queryExecutor = mock(QueryExecutor.class);
+        doAnswer(invocation -> {
+            startQueryInvoked.countDown();
+            return null;
+        }).when(queryExecutor).startQuery(ryaInstance, query);
+
+        // The thread that will perform the QueryEventWorker task.
+        final Thread queryEventWorker = new Thread(new QueryEventWorker(queue,
+                queryExecutor, 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        try {
+            queryEventWorker.start();
+
+            // Provide a message indicating a query needs to be executing.
+            queue.put(executingEvent);
+
+            // Verify the Query Executor was told to start the query.
+            assertTrue( startQueryInvoked.await(150, TimeUnit.MILLISECONDS) );
+        } finally {
+            shutdownSignal.set(true);
+            queryEventWorker.join();
+        }
+    }
+
+    @Test
+    public void stoppedWork() throws Exception {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue used to send the execute work to the thread.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The message that indicates a query needs to be stopped.
+        final UUID queryId = UUID.randomUUID();
+        final QueryEvent stoppedEvent = QueryEvent.stopped("rya", queryId);
+
+        // Release a latch if the stopQuery method on the queryExecutor is invoked with the correct values.
+        final CountDownLatch stopQueryInvoked = new CountDownLatch(1);
+        final QueryExecutor queryExecutor = mock(QueryExecutor.class);
+        doAnswer(invocation -> {
+            stopQueryInvoked.countDown();
+            return null;
+        }).when(queryExecutor).stopQuery(queryId);
+
+        final Thread queryEventWorker = new Thread(new QueryEventWorker(queue,
+                queryExecutor, 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        try {
+            // The thread that will perform the QueryEventWorker task.
+            queryEventWorker.start();
+
+            // Provide a message indicating a query needs to be executing.
+            queue.put(stoppedEvent);
+
+            // Verify the Query Executor was told to stop the query.
+            assertTrue( stopQueryInvoked.await(150, TimeUnit.MILLISECONDS) );
+        } finally {
+            shutdownSignal.set(true);
+            queryEventWorker.join();
+        }
+    }
+
+    @Test
+    public void stopAllWork() throws Exception {
+        // The signal that will kill the working thread.
+        final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+        // The queue used to send the execute work to the thread.
+        final BlockingQueue<QueryEvent> queue = new ArrayBlockingQueue<>(1);
+
+        // The message that indicates all queries for a rya instance need to be stopped.
+        final String ryaInstance = "rya";
+        final QueryEvent stopAllEvent = QueryEvent.stopALL(ryaInstance);
+
+        // Release a latch if the stopQuery method on the queryExecutor is invoked with the correct values.
+        final CountDownLatch testMethodInvoked = new CountDownLatch(1);
+        final QueryExecutor queryExecutor = mock(QueryExecutor.class);
+        doAnswer(invocation -> {
+            testMethodInvoked.countDown();
+            return null;
+        }).when(queryExecutor).stopAll(ryaInstance);
+
+        final Thread queryEventWorker = new Thread(new QueryEventWorker(queue,
+                queryExecutor, 50, TimeUnit.MILLISECONDS, shutdownSignal));
+        try {
+            // The thread that will perform the QueryEventWorker task.
+            queryEventWorker.start();
+
+            // Provide a message indicating a query needs to be executing.
+            queue.put(stopAllEvent);
+
+            // Verify the Query Executor was told to stop all the queries.
+            assertTrue( testMethodInvoked.await(150, TimeUnit.MILLISECONDS) );
+        } finally {
+            shutdownSignal.set(true);
+            queryEventWorker.join();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
index a1203a0..04e70c0 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/QueryManagerTest.java
@@ -1,18 +1,20 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.rya.streams.querymanager;
 
@@ -34,13 +36,10 @@ import org.apache.rya.streams.api.queries.QueryChangeLog;
 import org.apache.rya.streams.querymanager.QueryChangeLogSource.SourceListener;
 import org.junit.Test;
 
-import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
-
 /**
- * Test for the {@link QueryManager}
+ * Unit tests the methods of {@link QueryManager}.
  */
 public class QueryManagerTest {
-    private static final Scheduler TEST_SCHEDULER = Scheduler.newFixedRateSchedule(0, 100, TimeUnit.MILLISECONDS);
 
     /**
      * Tests when the query manager is notified to create a new query, the query
@@ -74,7 +73,7 @@ public class QueryManagerTest {
             return null;
         }).when(source).subscribe(any(SourceListener.class));
 
-        final QueryManager qm = new QueryManager(qe, source, TEST_SCHEDULER);
+        final QueryManager qm = new QueryManager(qe, source, 50, TimeUnit.MILLISECONDS);
         try {
             qm.startAndWait();
             queryStarted.await(5, TimeUnit.SECONDS);
@@ -128,7 +127,7 @@ public class QueryManagerTest {
             return null;
         }).when(source).subscribe(any(SourceListener.class));
 
-        final QueryManager qm = new QueryManager(qe, source, TEST_SCHEDULER);
+        final QueryManager qm = new QueryManager(qe, source, 50, TimeUnit.MILLISECONDS);
         try {
             qm.startAndWait();
             queryDeleted.await(5, TimeUnit.SECONDS);
@@ -183,7 +182,7 @@ public class QueryManagerTest {
             return null;
         }).when(source).subscribe(any(SourceListener.class));
 
-        final QueryManager qm = new QueryManager(qe, source, TEST_SCHEDULER);
+        final QueryManager qm = new QueryManager(qe, source, 50, TimeUnit.MILLISECONDS);
         try {
             qm.startAndWait();
             queryDeleted.await(10, TimeUnit.SECONDS);
@@ -192,4 +191,4 @@ public class QueryManagerTest {
             qm.stopAndWait();
         }
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/ThreadUtil.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/ThreadUtil.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/ThreadUtil.java
new file mode 100644
index 0000000..9896e31
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/ThreadUtil.java
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Utilities that are useful for interacting with {@link Thread}s while testing.
+ */
+public class ThreadUtil {
+
+    /**
+     * Private constructor to prevent instantiation.
+     */
+    private ThreadUtil() { }
+
+    /**
+     * A utility function that returns whether a thread is alive or not after waiting
+     * some specified period of time to join it.
+     *
+     * @param thread - The thread that will be joined. (not null)
+     * @param millis - How long to wait to join the thread.
+     * @return {@code true} if the thread is still alive, otherwise {@code false}.
+     */
+    public static boolean stillAlive(final Thread thread, final long millis) {
+        requireNonNull(thread);
+        try {
+            thread.join(millis);
+        } catch (final InterruptedException e) { }
+        return thread.isAlive();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
index 3cbe894..f9c8a03 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
@@ -35,6 +35,7 @@ import org.apache.rya.streams.api.interactor.LoadStatements;
 import org.apache.rya.streams.kafka.KafkaStreamsFactory;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.SingleThreadKafkaStreamsFactory;
+import org.apache.rya.streams.kafka.interactor.CreateKafkaTopic;
 import org.apache.rya.streams.kafka.interactor.KafkaLoadStatements;
 import org.apache.rya.streams.kafka.serialization.VisibilityBindingSetDeserializer;
 import org.apache.rya.streams.kafka.serialization.VisibilityStatementSerializer;
@@ -119,9 +120,10 @@ public class LocalQueryExecutorIT {
         expected.add(new VisibilityBindingSet(bs, "a"));
 
         // Start the executor that will be tested.
+        final CreateKafkaTopic createKafkaTopic = new CreateKafkaTopic( kafka.getZookeeperServers() );
         final String kafkaServers = kafka.getKafkaHostname() + ":" + kafka.getKafkaPort();
         final KafkaStreamsFactory jobFactory = new SingleThreadKafkaStreamsFactory(kafkaServers);
-        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        final QueryExecutor executor = new LocalQueryExecutor(createKafkaTopic, jobFactory);
         executor.startAndWait();
         try {
             // Start the query.

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
index 0df5794..c0f888e 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
@@ -32,6 +32,7 @@ import java.util.UUID;
 import org.apache.kafka.streams.KafkaStreams;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.kafka.KafkaStreamsFactory;
+import org.apache.rya.streams.kafka.interactor.CreateKafkaTopic;
 import org.apache.rya.streams.querymanager.QueryExecutor;
 import org.junit.Test;
 
@@ -44,7 +45,7 @@ public class LocalQueryExecutorTest {
 
     @Test(expected = IllegalStateException.class)
     public void startQuery_serviceNotStarted() throws Exception {
-        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), mock(KafkaStreamsFactory.class));
         executor.startQuery("rya", new StreamsQuery(UUID.randomUUID(), "query", true));
     }
 
@@ -60,7 +61,7 @@ public class LocalQueryExecutorTest {
         when(jobFactory.make(eq(ryaInstance), eq(query))).thenReturn(queryJob);
 
         // Start the executor that will be tested.
-        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), jobFactory);
         executor.startAndWait();
         try {
             // Tell the executor to start the query.
@@ -75,14 +76,14 @@ public class LocalQueryExecutorTest {
 
     @Test(expected = IllegalStateException.class)
     public void stopQuery_serviceNotStarted() throws Exception {
-        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), mock(KafkaStreamsFactory.class));
         executor.stopQuery(UUID.randomUUID());
     }
 
     @Test
     public void stopQuery_queryNotRunning() throws Exception {
         // Start an executor.
-        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), mock(KafkaStreamsFactory.class));
         executor.startAndWait();
         try {
             // Try to stop a query that was never stareted.
@@ -104,7 +105,7 @@ public class LocalQueryExecutorTest {
         when(jobFactory.make(eq(ryaInstance), eq(query))).thenReturn(queryJob);
 
         // Start the executor that will be tested.
-        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), jobFactory);
         executor.startAndWait();
         try {
             // Tell the executor to start the query.
@@ -122,7 +123,7 @@ public class LocalQueryExecutorTest {
 
     @Test(expected = IllegalStateException.class)
     public void stopAll_serviceNotStarted() throws Exception {
-        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), mock(KafkaStreamsFactory.class));
         executor.stopAll("rya");
     }
 
@@ -141,7 +142,7 @@ public class LocalQueryExecutorTest {
         when(jobFactory.make(eq(ryaInstance), eq(query2))).thenReturn(queryJob2);
 
         // Start the executor that will be tested.
-        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), jobFactory);
         executor.startAndWait();
         try {
             // Tell the executor to start the queries.
@@ -180,7 +181,7 @@ public class LocalQueryExecutorTest {
         when(jobFactory.make(eq(ryaInstance2), eq(query2))).thenReturn(queryJob2);
 
         // Start the executor that will be tested.
-        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), jobFactory);
         executor.startAndWait();
         try {
             // Tell the executor to start the queries.
@@ -205,14 +206,14 @@ public class LocalQueryExecutorTest {
 
     @Test(expected = IllegalStateException.class)
     public void getRunningQueryIds_serviceNotStarted() throws Exception {
-        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), mock(KafkaStreamsFactory.class));
         executor.getRunningQueryIds();
     }
 
     @Test
     public void getRunningQueryIds_noneStarted() throws Exception {
         // Start an executor.
-        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), mock(KafkaStreamsFactory.class));
         executor.startAndWait();
         try {
             // Get the list of running queries.
@@ -240,7 +241,7 @@ public class LocalQueryExecutorTest {
         when(jobFactory.make(eq(ryaInstance), eq(query3))).thenReturn(mock(KafkaStreams.class));
 
         // Start the executor that will be tested.
-        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), jobFactory);
         executor.startAndWait();
         try {
             // Start the queries.
@@ -275,7 +276,7 @@ public class LocalQueryExecutorTest {
         when(jobFactory.make(eq(ryaInstance), eq(query3))).thenReturn(mock(KafkaStreams.class));
 
         // Start the executor that will be tested.
-        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        final QueryExecutor executor = new LocalQueryExecutor(mock(CreateKafkaTopic.class), jobFactory);
         executor.startAndWait();
         try {
             // Start the queries.

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
index f2b50ab..de6b9f3 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
@@ -45,6 +45,11 @@ public class QueryManagerConfigMarshallerTest {
                 "            <port>6</port>\n" +
                 "        </kafka>\n" +
                 "    </queryChangeLogSource>\n" +
+                "    <queryExecutor>\n" +
+                "        <localKafkaStreams>\n" +
+                "            <zookeepers>zoo1,zoo2,zoo3</zookeepers>\n" +
+                "        </localKafkaStreams>\n" +
+                "    </queryExecutor>\n" +
                 "    <performanceTunning>\n" +
                 "        <queryChanngeLogDiscoveryPeriod>\n" +
                 "            <value>1</value>\n" +


[12/22] incubator-rya git commit: RYA-446 Create a bin and rpm distribution for the Rya Streams Query Manager application.

Posted by pu...@apache.org.
RYA-446 Create a bin and rpm distribution for the Rya Streams Query Manager application.


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/3b05a0b7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/3b05a0b7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/3b05a0b7

Branch: refs/heads/master
Commit: 3b05a0b76cdef5ba38503a2d174d81b9bfe044d7
Parents: 16202ac
Author: kchilton2 <ke...@gmail.com>
Authored: Thu Jan 25 17:19:58 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:50 2018 -0500

----------------------------------------------------------------------
 extras/rya.streams/query-manager/pom.xml        | 131 ++++++++++++++++++-
 .../src/assembly/binary-release.xml             |  30 +++++
 .../src/assembly/component-release.xml          |  71 ++++++++++
 .../query-manager/src/assembly/rpm-staging.xml  |  31 +++++
 .../query-manager/src/main/README.txt           |  55 ++++++++
 .../query-manager/src/main/config/log4j.xml     |  36 +++++
 .../main/scripts/rya-streams-query-manager.sh   | 104 +++++++++++++++
 .../systemd/rya-streams-query-manager.service   |  29 ++++
 8 files changed, 484 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
index deaccdb..e459814 100644
--- a/extras/rya.streams/query-manager/pom.xml
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -33,6 +33,10 @@ under the License.
         This module contains the Rya Streams Query Manager.
     </description>
 
+    <properties>
+        <rpm.staging.path>${project.build.directory}/${project.artifactId}-${project.version}-rpm-staging</rpm.staging.path>
+    </properties>
+
     <dependencies>
         <!-- Rya dependencies -->
         <dependency>
@@ -46,7 +50,10 @@ under the License.
             <artifactId>commons-daemon</artifactId>
             <version>1.1.0</version>
         </dependency>
-        
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-log4j12</artifactId>
+        </dependency>
         <dependency>
             <groupId>com.beust</groupId>
             <artifactId>jcommander</artifactId>
@@ -97,7 +104,7 @@ under the License.
                 </configuration>
             </plugin>
          
-            <!-- Ensure the generated java source contains the lisence header. -->   
+            <!-- Ensure the generated java source contains the license header. -->   
             <plugin>
                 <groupId>com.mycila</groupId>
                 <artifactId>license-maven-plugin</artifactId>
@@ -121,6 +128,7 @@ under the License.
                 </executions>
             </plugin>
         
+            <!-- Create a shaded jar that is able to execute the Daemon. -->
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-shade-plugin</artifactId>
@@ -141,6 +149,123 @@ under the License.
                     </execution>
                 </executions>
             </plugin>
+            
+            <!-- Use the assembly plugin to create the binary and RPM distributions. -->
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-assembly-plugin</artifactId>
+                <executions>
+                    <!-- The binary distribution of Rya Streams Query Manager. -->
+                    <execution>
+                        <id>create-binary-distribution</id>
+                        <goals>
+                            <goal>single</goal>
+                        </goals>
+                        <phase>package</phase>
+                        <configuration>
+                            <tarLongFileMode>gnu</tarLongFileMode>
+                            <descriptors>
+                                <descriptor>src/assembly/binary-release.xml</descriptor>
+                            </descriptors>
+                        </configuration>
+                    </execution>
+                    
+                    <!-- Stage the files for the RPM construction. -->
+                    <execution>
+                        <id>stage-content-for-rpms</id>
+                        <goals>
+                            <goal>single</goal>
+                        </goals>
+                        <phase>package</phase>
+                        <configuration>
+                            <!-- This is only staging, so don't attach the built folder to the project. -->
+                            <attach>false</attach>
+                            <descriptors>
+                                <descriptor>src/assembly/rpm-staging.xml</descriptor>
+                            </descriptors>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>rpm-maven-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>set-rpm-properties</id>
+                        <goals>
+                            <goal>version</goal>
+                        </goals>
+                    </execution>
+                    <execution>
+                        <id>create-rpm-distribution</id>
+                        <goals>
+                            <goal>attached-rpm</goal>
+                        </goals>
+                        <phase>package</phase>
+                        <configuration>
+                            <group>${project.groupId}</group>
+                            <name>${project.artifactId}</name>
+                            <classifier>noarch</classifier>
+                            <defaultUsername>root</defaultUsername>
+                            <defaultGroupname>root</defaultGroupname>
+                            <defaultDirmode>755</defaultDirmode>
+                            <defaultFilemode>644</defaultFilemode>
+                            
+                            <!-- This project requires the Apache Commons Daemon applications. -->
+                            <requires>
+                                <require>jsvc</require>
+                            </requires>
+                            
+                            <mappings>
+                                <!-- Copy everything over to the /opt directory, except for the scripts. -->
+                                <mapping>
+                                    <directory>/opt/rya-streams-query-manager-${rpm.version}</directory>
+                                    <sources>
+                                        <!-- Copy over everything exception for the executable script. -->
+                                        <source>
+                                            <location>${rpm.staging.path}</location>
+                                            <includes>
+                                                <include>bin/systemd/rya-streams-query-manager.service</include>
+                                                <include>config/*</include>
+                                                <include>lib/*</include>
+                                                <include>README.txt</include>
+                                            </includes>
+                                        </source>
+                                    </sources>
+                                </mapping>
+                                
+                                <!-- Copy over the scripts with the correct execution permissions. -->
+                                <mapping>
+                                    <directory>/opt/rya-streams-query-manager-${rpm.version}/bin</directory>
+                                    <directoryIncluded>false</directoryIncluded>
+                                    <filemode>554</filemode>
+                                    <sources>
+                                        <source>
+                                            <location>${rpm.staging.path}/bin</location>
+                                            <includes>
+                                                <include>rya-streams-query-manager.sh</include>
+                                            </includes>
+                                        </source>
+                                    </sources>
+                                </mapping>
+                                
+                                <!-- Symbolic link the service file after it has been copied over. -->
+                                <mapping>
+                                    <directory>/etc/systemd/system/</directory>
+                                    <sources>
+                                        <softlinkSource>
+                                            <location>/opt/rya-streams-query-manager-${rpm.version}/bin/systemd/rya-streams-query-manager.service</location>
+                                            <destination>rya-streams-query-manager.service</destination>
+                                        </softlinkSource>
+                                    </sources>
+                                </mapping>
+                            </mappings>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
         </plugins>
      </build>
-</project>
+</project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/src/assembly/binary-release.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/assembly/binary-release.xml b/extras/rya.streams/query-manager/src/assembly/binary-release.xml
new file mode 100644
index 0000000..07e2de0
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/assembly/binary-release.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" 
+          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
+    <id>bin</id>
+    <formats>
+        <format>tar.gz</format>
+    </formats>
+    <componentDescriptors>
+        <componentDescriptor>src/assembly/component-release.xml</componentDescriptor>
+    </componentDescriptors>
+</assembly>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/src/assembly/component-release.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/assembly/component-release.xml b/extras/rya.streams/query-manager/src/assembly/component-release.xml
new file mode 100644
index 0000000..f68d53d
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/assembly/component-release.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<component xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/component/1.1.3" 
+           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+           xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/component/1.1.3 http://maven.apache.org/xsd/component-1.1.3.xsd">
+
+    <!-- Define the files that will be included in the distribution. -->
+    <fileSets>
+        <!-- Configuration files. -->
+        <fileSet>
+            <directory>src/main/config</directory>
+            <outputDirectory>config</outputDirectory>
+            <lineEnding>unix</lineEnding>
+        </fileSet>
+
+        <!-- Linux Scripts. -->
+        <fileSet>
+            <directory>src/main/scripts</directory>
+            <outputDirectory>bin</outputDirectory>
+            <lineEnding>unix</lineEnding>
+            <filtered>true</filtered>
+        </fileSet>
+
+        <!-- The README.txt file. -->
+        <fileSet>
+            <directory>src/main</directory>
+            <outputDirectory></outputDirectory>
+            <includes>
+                <include>README.txt</include>
+            </includes>
+            <lineEnding>unix</lineEnding>
+            <filtered>true</filtered>
+        </fileSet>
+
+        <!-- The shaded jar that is executed to run the program. -->
+        <fileSet>
+            <directory>${project.build.directory}</directory>
+            <outputDirectory>lib</outputDirectory>
+            <includes>
+                <include>${project.artifactId}-${project.version}-shaded.jar</include>
+            </includes>
+        </fileSet>
+    </fileSets>
+
+    <!-- The commons-daemon jar file. -->
+    <dependencySets>
+        <dependencySet>
+            <outputDirectory>lib</outputDirectory>
+            <includes>
+                <include>commons-daemon:commons-daemon</include>
+            </includes>
+        </dependencySet>
+    </dependencySets>
+</component>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/src/assembly/rpm-staging.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/assembly/rpm-staging.xml b/extras/rya.streams/query-manager/src/assembly/rpm-staging.xml
new file mode 100644
index 0000000..09b3bf2
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/assembly/rpm-staging.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
+    <id>rpm-staging</id>
+    <formats>
+        <format>dir</format>
+    </formats>
+    <includeBaseDirectory>false</includeBaseDirectory>
+    <componentDescriptors>
+        <componentDescriptor>src/assembly/component-release.xml</componentDescriptor>
+    </componentDescriptors>
+</assembly>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/src/main/README.txt
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/README.txt b/extras/rya.streams/query-manager/src/main/README.txt
new file mode 100644
index 0000000..03f9c01
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/README.txt
@@ -0,0 +1,55 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+Project: rya-streams-query-manager
+Version: ${project.version}
+
+### Description ###
+The Rya Streams Query Manager daemon service is an application that notices
+when new Rya instances are registered to use Rya Streams and then reacts to
+query create/delete/start/stop requests. Users may use the Rya Shell to issue
+those commands.
+
+This version of the manager only supports Kafka sources and it runs every query
+as a single threaded Kafka Streams job. All of the queries are processed within 
+a single JVM, so it is only suitable for a single node instance of Rya. This 
+version does not scale.
+
+### Requirements ###
+CentOS 7
+JSVC
+Java 8
+
+### Installation ###
+ 1. Copy over the RPM to the machine that will run the daemon.
+ 
+ 2. Use yum to install the RPM:
+    yum install -y ${project.artifactId}-${project.version}.noarch.rpm
+    
+ 3. Update the configuration file:
+    Replace "[Kafka Broker Hostname]" with the IP address of the Kafka broker.
+    Replace "[Kafka Broker Port]" with the port of the Kafka broker (usually 9092)
+    
+ 4. Start the service:
+    systemctl start rya-streams-query-manager
+    
+### Uninstallation ###
+ 1. Get the name of the RPM you want to uninstall:
+    rpm -qa | grep rya.streams.query-manager
+    
+ 2. Uninstall it:
+    rpm -e <the value from the last command here>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/src/main/config/log4j.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/config/log4j.xml b/extras/rya.streams/query-manager/src/main/config/log4j.xml
new file mode 100644
index 0000000..2021638
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/config/log4j.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+<log4j:configuration debug="true"
+    xmlns:log4j='http://jakarta.apache.org/log4j/'>
+
+    <appender name="console" class="org.apache.log4j.ConsoleAppender">
+        <layout class="org.apache.log4j.PatternLayout">
+        <param name="ConversionPattern"
+          value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
+        </layout>
+    </appender>
+
+    <root>
+        <level value="INFO" />
+        <appender-ref ref="console" />
+    </root>
+
+</log4j:configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh b/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh
new file mode 100644
index 0000000..daa1ae5
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+NAME=rya-streams-query-manager
+DESC="Rya Streams Query Manager Daemon service"
+
+# The path to JSVC
+EXEC="/usr/bin/jsvc"
+
+# Get the parent directory of the dir this script resides within.
+PROJECT_HOME=$(dirname $(cd $(dirname $0) && pwd))
+
+# This classpath must contain the commons-daemon jar as well as the jar we're executing.
+CLASS_PATH="$PROJECT_HOME/lib/commons-daemon-1.1.0.jar:$PROJECT_HOME/lib/${project.artifactId}-${project.version}-shaded.jar:$PROJECT_HOME/config/log4j.xml"
+
+# The fully qualified name of the class to execute. This class must implement the Daemon interface.
+DAEMON_CLASS=org.apache.rya.streams.querymanager.QueryManagerDaemon
+
+# The PID file that indicates if rya-streams-query-manager is running. 
+PID="/var/run/$NAME.pid"
+
+# System.out writes to this file...
+LOG_OUT="$PROJECT_HOME/logs/$NAME.out"
+
+# System.err writes to this file...
+LOG_ERR="$PROJECT_HOME/logs/$NAME.err"
+
+start ()
+{
+    if [ -f "$PID" ]
+    then
+        echo "The $DESC is already running."
+        exit 1
+    else
+        echo "Starting the $DESC."
+        $EXEC -cp $CLASS_PATH -user root -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $1 $DAEMON_CLASS \
+            -c "$PROJECT_HOME/config/configuration.xml"
+    fi
+}
+
+stop ()
+{
+    if [ -f "$PID" ]
+    then
+        echo "Stopping the $DESC."
+        $EXEC -cp $CLASS_PATH -user root -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID -stop $DAEMON_CLASS
+    else
+        echo "The $DESC is already stopped."
+    fi
+}
+
+status ()
+{
+    if [ -f "$PID" ]
+    then
+        echo "The $DESC is running." 
+    else
+        echo "The $DESC is stopped."
+    fi
+}
+
+restart ()
+{
+    echo "Restarting the $DESC..."
+    if [ -f "$PID" ]; then        
+        # Stop the service
+        stop
+    fi
+    
+    # Start the service
+    start
+    echo "The $DESC has restarted."
+}
+
+usage ()
+{
+    echo "usage: rya-streams-query-manager.sh (start|stop|status|restart)"
+    exit 1
+}
+
+case "$1" in
+    start) start ;;
+    stop) stop ;;
+    status) status ;;
+    restart) restart ;;
+    *) usage ;;
+esac
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/3b05a0b7/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service b/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
new file mode 100644
index 0000000..0ec41c5
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
@@ -0,0 +1,29 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+TODO This will be the service file installed to CentOS 7 for systemd integration.
+
+[Units]
+TODO
+
+[Service]
+TODO
+
+[Install]
+TODO
\ No newline at end of file


[16/22] incubator-rya git commit: RYA-451 Fixing threading issues with the QueryManager class.

Posted by pu...@apache.org.
RYA-451 Fixing threading issues with the QueryManager class.


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/1cd8db32
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/1cd8db32
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/1cd8db32

Branch: refs/heads/master
Commit: 1cd8db32e04f116934fef22fe9b465f7cd807755
Parents: a342fe2
Author: kchilton2 <ke...@gmail.com>
Authored: Fri Feb 2 22:47:59 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:55 2018 -0500

----------------------------------------------------------------------
 .../rya/streams/api/entity/StreamsQuery.java    |   4 +-
 .../api/queries/InMemoryQueryRepository.java    |  30 +-
 .../rya/streams/api/queries/QueryChange.java    |  10 +
 .../queries/InMemoryQueryRepositoryTest.java    |  16 +-
 .../client/command/ListQueriesCommand.java      |  12 +-
 .../streams/client/command/RunQueryCommand.java |   2 +-
 .../apache/rya/streams/kafka/KafkaTopics.java   |   4 +-
 .../kafka/SingleThreadKafkaStreamsFactory.java  |   2 +-
 .../kafka/interactor/CreateKafkaTopic.java      |  60 ++
 .../query-manager/src/main/README.txt           |   7 +-
 .../src/main/config/configuration.xml           |  10 +-
 .../query-manager/src/main/config/log4j.xml     |  17 +
 .../querymanager/QueryChangeLogSource.java      |   5 +-
 .../rya/streams/querymanager/QueryManager.java  | 929 ++++++++++++++++---
 .../querymanager/QueryManagerDaemon.java        |   8 +-
 .../kafka/KafkaQueryChangeLogSource.java        |  46 +-
 .../querymanager/kafka/LocalQueryExecutor.java  |  31 +-
 .../src/main/xsd/QueryManagerConfig.xsd         |  14 +
 .../querymanager/LogEventWorkGeneratorTest.java | 136 +++
 .../querymanager/LogEventWorkerTest.java        | 245 +++++
 .../QueryEventWorkGeneratorTest.java            | 265 ++++++
 .../querymanager/QueryEventWorkerTest.java      | 172 ++++
 .../streams/querymanager/QueryManagerTest.java  |  41 +-
 .../rya/streams/querymanager/ThreadUtil.java    |  48 +
 .../kafka/LocalQueryExecutorIT.java             |   4 +-
 .../kafka/LocalQueryExecutorTest.java           |  25 +-
 .../xml/QueryManagerConfigMarshallerTest.java   |   5 +
 27 files changed, 1907 insertions(+), 241 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
index 7194834..11423bd 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/entity/StreamsQuery.java
@@ -85,7 +85,7 @@ public class StreamsQuery {
         }
         return false;
     }
-    
+
     @Override
     public String toString() {
         final StringBuilder sb = new StringBuilder();
@@ -95,7 +95,7 @@ public class StreamsQuery {
         sb.append(getSparql() + "\n");
         sb.append("Is ");
         if (!isActive) {
-            sb.append(" Not ");
+            sb.append("Not ");
         }
         sb.append("Running.\n");
         return sb.toString();

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
index 5fb0297..95c1922 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
@@ -51,9 +51,9 @@ import info.aduna.iteration.CloseableIteration;
  */
 @DefaultAnnotation(NonNull.class)
 public class InMemoryQueryRepository extends AbstractScheduledService implements QueryRepository {
-    private static final Logger LOG = LoggerFactory.getLogger(InMemoryQueryRepository.class);
+    private static final Logger log = LoggerFactory.getLogger(InMemoryQueryRepository.class);
 
-    private final ReentrantLock lock = new ReentrantLock();
+    private final ReentrantLock lock = new ReentrantLock(true);
 
     /**
      * The change log that is the ground truth for describing what the queries look like.
@@ -198,7 +198,6 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
 
     @Override
     protected void shutDown() throws Exception {
-        super.shutDown();
         lock.lock();
         try {
             changeLog.close();
@@ -211,11 +210,12 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
      * Updates the {@link #queriesCache} to reflect the latest position within the {@link #changeLog}.
      */
     private void updateCache() {
-        requireNonNull(changeLog);
+        log.trace("updateCache() - Enter");
 
         CloseableIteration<ChangeLogEntry<QueryChange>, QueryChangeLogException> it = null;
         try {
             // Iterate over everything since the last position that was handled within the change log.
+            log.debug("Starting cache position:" + cachePosition);
             if(cachePosition.isPresent()) {
                 it = changeLog.readFromPosition(cachePosition.get() + 1);
             } else {
@@ -228,6 +228,8 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
                 final QueryChange change = entry.getEntry();
                 final UUID queryId = change.getQueryId();
 
+                log.debug("Updating the cache to reflect:\n" + change);
+
                 switch(change.getChangeType()) {
                     case CREATE:
                         final StreamsQuery query = new StreamsQuery(
@@ -253,15 +255,17 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
                         break;
                 }
 
+                log.debug("Notifying listeners with the updated state.");
                 final Optional<StreamsQuery> newQueryState = Optional.ofNullable(queriesCache.get(queryId));
                 listeners.forEach(listener -> listener.notify(entry, newQueryState));
 
                 cachePosition = Optional.of( entry.getPosition() );
+                log.debug("New chache position: " + cachePosition);
             }
 
         } catch (final QueryChangeLogException e) {
             // Rethrow the exception because the object the supplier tried to create could not be created.
-            throw new RuntimeException("Could not initialize the " + InMemoryQueryRepository.class.getName(), e);
+            throw new RuntimeException("Could not update the cache of " + InMemoryQueryRepository.class.getName(), e);
 
         } finally {
             // Try to close the iteration if it was opened.
@@ -270,18 +274,22 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
                     it.close();
                 }
             } catch (final QueryChangeLogException e) {
-                LOG.error("Could not close the " + CloseableIteration.class.getName(), e);
+                log.error("Could not close the " + CloseableIteration.class.getName(), e);
             }
+
+            log.trace("updateCache() - Exit");
         }
     }
 
     @Override
     protected void runOneIteration() throws Exception {
+        log.trace("runOneIteration() - Enter");
         lock.lock();
         try {
             updateCache();
         } finally {
             lock.unlock();
+            log.trace("runOneIteration() - Exit");
         }
     }
 
@@ -292,17 +300,25 @@ public class InMemoryQueryRepository extends AbstractScheduledService implements
 
     @Override
     public Set<StreamsQuery> subscribe(final QueryChangeLogListener listener) {
+        log.trace("subscribe(listener) - Enter");
+
         //locks to prevent the current state from changing while subscribing.
         lock.lock();
+        log.trace("subscribe(listener) - Acquired lock");
         try {
             listeners.add(listener);
+            log.trace("subscribe(listener) - Listener Registered");
 
             //return the current state of the query repository
-            return queriesCache.values()
+            final Set<StreamsQuery> queries = queriesCache.values()
                     .stream()
                     .collect(Collectors.toSet());
+            log.trace("subscribe(listener) - Returning " + queries.size() + " existing queries");
+            return queries;
         } finally {
+            log.trace("subscribe(listener) - Releasing lock");
             lock.unlock();
+            log.trace("subscribe(listener) - Exit");
         }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
index d283957..d34a394 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChange.java
@@ -110,6 +110,16 @@ public final class QueryChange implements Serializable {
         return false;
     }
 
+    @Override
+    public String toString() {
+        return "QueryChange: {" +
+               "    Query ID: " + queryId + ",\n" +
+               "    Change Type: " + changeType + ",\n" +
+               "    Is Active: " + isActive + ",\n" +
+               "    SPARQL: " + sparql + "\n" +
+               "}";
+    }
+
     /**
      * Create a {@link QueryChange} that represents a new SPARQL query that will be managed by Rya Streams.
      *

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
index 3b3d48a..d7e116b 100644
--- a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
+++ b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
@@ -93,13 +93,9 @@ public class InMemoryQueryRepositoryTest {
 
             // Create a new totally in memory QueryRepository.
             final QueryRepository initializedQueries = new InMemoryQueryRepository( changeLog, SCHEDULE );
-            try {
-                // Listing the queries should work using an initialized change log.
-                final Set<StreamsQuery> stored = initializedQueries.list();
-                assertEquals(expected, stored);
-            } finally {
-                queries.stop();
-            }
+            // Listing the queries should work using an initialized change log.
+            final Set<StreamsQuery> stored = initializedQueries.list();
+            assertEquals(expected, stored);
         } finally {
             queries.stop();
         }
@@ -166,7 +162,7 @@ public class InMemoryQueryRepositoryTest {
             final StreamsQuery query = queries.add("query 1", true);
 
             final Set<StreamsQuery> existing = queries.subscribe((queryChangeEvent, newQueryState) -> {
-                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(1L,
+                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<>(1L,
                         QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
                 final Optional<StreamsQuery> expectedQueryState = Optional.of(
                         new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
@@ -197,7 +193,7 @@ public class InMemoryQueryRepositoryTest {
             //show listener on repo that query was added to is being notified of the new query.
             final CountDownLatch repo1Latch = new CountDownLatch(1);
             queries.subscribe((queryChangeEvent, newQueryState) -> {
-                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
+                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<>(0L,
                         QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
                 final Optional<StreamsQuery> expectedQueryState = Optional.of(
                         new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
@@ -210,7 +206,7 @@ public class InMemoryQueryRepositoryTest {
             //show listener not on the repo that query was added to is being notified as well.
             final CountDownLatch repo2Latch = new CountDownLatch(1);
             queries2.subscribe((queryChangeEvent, newQueryState) -> {
-                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
+                final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<>(0L,
                         QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
                 final Optional<StreamsQuery> expectedQueryState = Optional.of(
                         new StreamsQuery(queryChangeEvent.getEntry().getQueryId(), "query 2", true));

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
index cd78975..a5507a6 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
@@ -23,6 +23,7 @@ import static java.util.Objects.requireNonNull;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.exception.RyaStreamsException;
 import org.apache.rya.streams.api.interactor.ListQueries;
@@ -112,12 +113,11 @@ public class ListQueriesCommand implements RyaStreamsCommand {
         sb.append("Queries in Rya Streams:\n");
         sb.append("---------------------------------------------------------\n");
         queries.forEach(query -> {
-            sb.append("ID: ");
-            sb.append(query.getQueryId());
-            sb.append("\t\t");
-            sb.append("Query: ");
-            sb.append(query.getSparql());
-            sb.append("\n");
+            sb.append("ID: ").append(query.getQueryId())
+                .append("    ")
+                .append("Is Active: ").append(query.isActive())
+                .append(StringUtils.rightPad("" + query.isActive(), 9))
+                .append("Query: ").append(query.getSparql()).append("\n");
         });
         return sb.toString();
     }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
index ddaf647..7b311f6 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
@@ -136,7 +136,7 @@ public class RunQueryCommand implements RyaStreamsCommand {
                 final Set<String> topics = new HashSet<>();
                 topics.add( KafkaTopics.statementsTopic(params.ryaInstance) );
                 topics.add( KafkaTopics.queryResultsTopic(queryId) );
-                KafkaTopics.createTopic(params.zookeeperServers, topics, 1, 1);
+                KafkaTopics.createTopics(params.zookeeperServers, topics, 1, 1);
 
                 // Run the query that uses those topics.
                 final KafkaRunQuery runQuery = new KafkaRunQuery(

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
index 095465c..989799a 100644
--- a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
@@ -55,7 +55,7 @@ public class KafkaTopics {
     }
 
     /**
-     * Get the Rya instance name from a Kafka topic name that has been used for a {@link QueryChnageLog}.
+     * Get the Rya instance name from a Kafka topic name that has been used for a {@link QueryChangeLog}.
      * <p/>
      * This is the inverse function of {@link #queryChangeLogTopic(String)}.
      *
@@ -106,7 +106,7 @@ public class KafkaTopics {
      * @param partitions - The number of partitions that each of the topics will have.
      * @param replicationFactor - The replication factor of the topics that are created.
      */
-    public static void createTopic(
+    public static void createTopics(
             final String zookeeperServers,
             final Set<String> topicNames,
             final int partitions,

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
index 7ab7e90..8093951 100644
--- a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
@@ -83,7 +83,7 @@ public class SingleThreadKafkaStreamsFactory implements KafkaStreamsFactory {
         try {
             final TopologyBuilder topologyBuilder = topologyFactory.build(query.getSparql(), statementsTopic, resultsTopic, new RandomUUIDFactory());
             return new KafkaStreams(topologyBuilder, new StreamsConfig(streamsProps));
-        } catch (MalformedQueryException | TopologyBuilderException e) {
+        } catch (final MalformedQueryException | TopologyBuilderException e) {
             throw new KafkaStreamsFactoryException("Could not create a KafkaStreams processing topology for query " + query.getQueryId(), e);
         }
     }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/CreateKafkaTopic.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/CreateKafkaTopic.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/CreateKafkaTopic.java
new file mode 100644
index 0000000..771e1c8
--- /dev/null
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/interactor/CreateKafkaTopic.java
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.kafka.interactor;
+
+import static java.util.Objects.requireNonNull;
+
+import java.util.Set;
+
+import org.apache.rya.streams.kafka.KafkaTopics;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * Creates topics in Kafka.
+ */
+@DefaultAnnotation(NonNull.class)
+public class CreateKafkaTopic {
+
+    private final String zookeeperServers;
+
+    /**
+     * Constructs an instance of {@link CreateKafkaTopic}.
+     *
+     * @param zookeeperServers - The Zookeeper servers that are used to manage the Kafka instance. (not null)
+     */
+    public CreateKafkaTopic(final String zookeeperServers) {
+        this.zookeeperServers = requireNonNull(zookeeperServers);
+    }
+
+    /**
+     * Creates a set of Kafka topics for each topic that does not already exist.
+     *
+     * @param topicNames - The topics that will be created. (not null)
+     * @param partitions - The number of partitions that each of the topics will have.
+     * @param replicationFactor - The replication factor of the topics that are created.
+     */
+    public void createTopics(
+            final Set<String> topicNames,
+            final int partitions,
+            final int replicationFactor) {
+        KafkaTopics.createTopics(zookeeperServers, topicNames, partitions, replicationFactor);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/README.txt
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/README.txt b/extras/rya.streams/query-manager/src/main/README.txt
index 3b2dbfe..93d5ac5 100644
--- a/extras/rya.streams/query-manager/src/main/README.txt
+++ b/extras/rya.streams/query-manager/src/main/README.txt
@@ -41,8 +41,11 @@ Java 8
     yum install -y ${project.artifactId}-${project.version}.noarch.rpm
     
  3. Update the configuration file:
-    Replace "[Kafka Broker Hostname]" with the IP address of the Kafka broker.
-    Replace the Kafka port if using something other than the default of 9092.
+    A. Replace "[Zookeepers used to manage Kafka. E.g.: zoo1,zoo2,zoo3]" with 
+       the zookeepers used to manage the Kafka cluster. It is a comma separated 
+       list.
+    B. Replace "[Kafka Broker Hostname]" with the IP address of the Kafka broker.
+    C. Replace the Kafka port if using something other than the default of 9092.
     
  4. Start the service:
     systemctl start rya-streams-query-manager.service

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/config/configuration.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/config/configuration.xml b/extras/rya.streams/query-manager/src/main/config/configuration.xml
index 96da501..7077125 100644
--- a/extras/rya.streams/query-manager/src/main/config/configuration.xml
+++ b/extras/rya.streams/query-manager/src/main/config/configuration.xml
@@ -18,7 +18,7 @@ specific language governing permissions and limitations
 under the License.
 -->
 <queryManagerConfig>
-    <!-- The  Query Change Log Sources. The source defines a system where Rya
+    <!-- The Query Change Log Sources. The source defines a system where Rya
        - Streams Query Change Logs are managed. The query manager will manage 
        - queries for all Rya instances whose change logs are stored within the
        - source.
@@ -29,6 +29,14 @@ under the License.
             <port>9092</port>
         </kafka>
     </queryChangeLogSource>
+
+    <!-- The Query Executor. The executor defines a system for executing the
+         Rya Streams queries. -->    
+    <queryExecutor>
+        <localKafkaStreams>
+            <zookeepers>[Zookeepers used to manage Kafka. E.g.: zoo1,zoo2,zoo3]</zookeepers>
+        </localKafkaStreams>
+    </queryExecutor>
     
     <!-- This section defines performance related tuning values. Sensible
        - default have been provided to simplify configuration. 

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/config/log4j.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/config/log4j.xml b/extras/rya.streams/query-manager/src/main/config/log4j.xml
index 2021638..96ea56c 100644
--- a/extras/rya.streams/query-manager/src/main/config/log4j.xml
+++ b/extras/rya.streams/query-manager/src/main/config/log4j.xml
@@ -28,6 +28,23 @@ under the License.
         </layout>
     </appender>
 
+    <!-- Kafka configuration configs are loud. -->
+    <logger name="org.apache.kafka.streams.StreamsConfig">
+        <level value="OFF"/>
+    </logger>
+    <logger name="org.apache.kafka.clients.consumer.ConsumerConfig">
+        <level value="OFF"/>
+    </logger>
+    <logger name="org.apache.kafka.clients.producer.ProducerConfig">
+        <level value="OFF"/>
+    </logger>
+
+    <!-- Change this level to DEBUG to see more information about what the 
+         QueryManager is doing. -->
+    <logger name="org.apache.rya.streams.querymanager.QueryManager">
+        <level value="INFO"/>
+    </logger>
+
     <root>
         <level value="INFO" />
         <appender-ref ref="console" />

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java
index 73e5d12..eb5ca08 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryChangeLogSource.java
@@ -51,8 +51,9 @@ public interface QueryChangeLogSource extends Service {
     public void unsubscribe(final SourceListener listener);
 
     /**
-     * A listener that is notified when a {@link QueryChangeLog} has
-     * been added or removed from a {@link QueryChangeLogSource}.
+     * A listener that is notified when a {@link QueryChangeLog} has been added or
+     * removed from a {@link QueryChangeLogSource}. The listener receives the only
+     * copy of the change log and is responsible for shutting it down.
      */
     @DefaultAnnotation(NonNull.class)
     public interface SourceListener {

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java
index 30b4538..e6bd800 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManager.java
@@ -1,18 +1,20 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
  *
- * http://www.apache.org/licenses/LICENSE-2.0
+ *   http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package org.apache.rya.streams.querymanager;
 
@@ -20,16 +22,23 @@ import static java.util.Objects.requireNonNull;
 
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
-import java.util.concurrent.locks.ReentrantLock;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.queries.ChangeLogEntry;
 import org.apache.rya.streams.api.queries.InMemoryQueryRepository;
 import org.apache.rya.streams.api.queries.QueryChange;
-import org.apache.rya.streams.api.queries.QueryChange.ChangeType;
 import org.apache.rya.streams.api.queries.QueryChangeLog;
 import org.apache.rya.streams.api.queries.QueryChangeLogListener;
 import org.apache.rya.streams.api.queries.QueryRepository;
@@ -38,8 +47,10 @@ import org.apache.rya.streams.querymanager.QueryExecutor.QueryExecutorException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.util.concurrent.AbstractIdleService;
+import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+import com.google.common.util.concurrent.AbstractService;
+import com.google.common.util.concurrent.UncheckedExecutionException;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
@@ -51,205 +62,823 @@ import edu.umd.cs.findbugs.annotations.NonNull;
  * instances/rya streams instances.
  */
 @DefaultAnnotation(NonNull.class)
-public class QueryManager extends AbstractIdleService {
-    private static final Logger LOG = LoggerFactory.getLogger(QueryManager.class);
+public class QueryManager extends AbstractService {
+    private static final Logger log = LoggerFactory.getLogger(QueryManager.class);
+
+    /**
+     * The source of {@link QueryChangeLog}s. Each log discovered is bound to a specific
+     * Rya instnace.
+     */
+    private final QueryChangeLogSource changeLogSource;
 
+    /**
+     * The engine that is responsible for executing {@link StreamsQuery}s.
+     */
     private final QueryExecutor queryExecutor;
-    private final Scheduler scheduler;
 
     /**
-     * Map of Rya Instance name to {@link QueryRepository}.
+     * How long blocking operations will be attempted before potentially trying again.
      */
-    private final Map<String, QueryRepository> queryRepos = new HashMap<>();
+    private final long blockingValue;
 
-    private final ReentrantLock lock = new ReentrantLock();
+    /**
+     * The units for {@link #blockingValue}.
+     */
+    private final TimeUnit blockingUnits;
 
-    private final QueryChangeLogSource source;
+    /**
+     * Used to inform threads that the application is shutting down, so they must stop work.
+     */
+    private final AtomicBoolean shutdownSignal = new AtomicBoolean(false);
+
+    /**
+     * This thread pool manages the two thread used to work the {@link LogEvent}s
+     * and the {@link QueryEvent}s.
+     */
+    private final ExecutorService executor = Executors.newFixedThreadPool(2);
 
     /**
      * Creates a new {@link QueryManager}.
      *
      * @param queryExecutor - Runs the active {@link StreamsQuery}s. (not null)
      * @param source - The {@link QueryChangeLogSource} of QueryChangeLogs. (not null)
-     * @param scheduler - The {@link Scheduler} used to discover query changes
-     *      within the {@link QueryChangeLog}s (not null)
+     * @param blockingValue - How long blocking operations will try before looping. (> 0)
+     * @param blockingUnits - The units of the {@code blockingValue}. (not null)
      */
-    public QueryManager(final QueryExecutor queryExecutor, final QueryChangeLogSource source, final Scheduler scheduler) {
-        this.source = requireNonNull(source);
+    public QueryManager(
+            final QueryExecutor queryExecutor,
+            final QueryChangeLogSource source,
+            final long blockingValue,
+            final TimeUnit blockingUnits) {
+        this.changeLogSource = requireNonNull(source);
         this.queryExecutor = requireNonNull(queryExecutor);
-        this.scheduler = requireNonNull(scheduler);
+        Preconditions.checkArgument(blockingValue > 0, "The blocking value must be > 0. Was: " + blockingValue);
+        this.blockingValue = blockingValue;
+        this.blockingUnits = requireNonNull(blockingUnits);
+    }
+
+    @Override
+    protected void doStart() {
+        log.info("Starting a QueryManager.");
+
+        // A work queue of discovered Query Change Logs that need to be handled.
+        // This queue exists so that the source notifying thread may be released
+        // immediately instead of calling into blocking functions.
+        final BlockingQueue<LogEvent> logEvents = new ArrayBlockingQueue<>(1024);
+
+        // A work queue of discovered Query Changes from the monitored Query Change Logs
+        // that need to be handled. This queue exists so that the Query Repository notifying
+        // thread may be released immediately instead of calling into blocking functions.
+        final BlockingQueue<QueryEvent> queryEvents = new ArrayBlockingQueue<>(1024);
+
+        try {
+            // Start up a LogEventWorker using the executor service.
+            executor.submit(new LogEventWorker(logEvents, queryEvents, blockingValue, blockingUnits, shutdownSignal));
+
+            // Start up a QueryEvent Worker using the executor service.
+            executor.submit(new QueryEventWorker(queryEvents, queryExecutor, blockingValue, blockingUnits, shutdownSignal));
+
+            // Start up the query execution framework.
+            queryExecutor.startAndWait();
+
+            // Startup the source that discovers new Query Change Logs.
+            changeLogSource.startAndWait();
+
+            // Subscribe the source a listener that writes to the LogEventWorker's work queue.
+            changeLogSource.subscribe(new LogEventWorkGenerator(logEvents, blockingValue, blockingUnits, shutdownSignal));
+        } catch(final RejectedExecutionException | UncheckedExecutionException e) {
+            log.error("Could not start up a QueryManager.", e);
+            notifyFailed(e);
+        }
+
+        // Notify the service was successfully started.
+        notifyStarted();
+
+        log.info("QueryManager has finished starting.");
+    }
+
+    @Override
+    protected void doStop() {
+        log.info("Stopping a QueryManager.");
+
+        // Set the shutdown flag so that all components that rely on that signal will stop processing.
+        shutdownSignal.set(true);
+
+        // Stop the workers and wait for them to die.
+        executor.shutdownNow();
+        try {
+            if(!executor.awaitTermination(10, TimeUnit.SECONDS)) {
+                log.warn("Waited 10 seconds for the worker threads to die, but they are still running.");
+            }
+        } catch (final InterruptedException e) {
+            log.warn("Waited 10 seconds for the worker threads to die, but they are still running.");
+        }
+
+        // Stop the source of new Change Logs.
+        try {
+            changeLogSource.stopAndWait();
+        } catch(final UncheckedExecutionException e) {
+            log.warn("Could not stop the Change Log Source.", e);
+        }
+
+        // Stop the query execution framework.
+        try {
+            queryExecutor.stopAndWait();
+        } catch(final UncheckedExecutionException e) {
+            log.warn("Could not stop the Query Executor", e);
+        }
+
+        // Notify the service was successfully stopped.
+        notifyStopped();
+
+        log.info("QueryManager has finished stopping.");
     }
 
     /**
-     * Starts running a query.
+     * Offer a unit of work to a blocking queue until it is either accepted, or the
+     * shutdown signal is set.
      *
-     * @param ryaInstanceName - The Rya instance the query belongs to. (not null)
-     * @param query - The query to run.(not null)
+     * @param workQueue - The blocking work queue to write to. (not null)
+     * @param event - The event that will be offered to the work queue. (not null)
+     * @param offerValue - How long to wait when offering new work.
+     * @param offerUnits - The unit for the {@code offerValue}. (not null)
+     * @param shutdownSignal - Used to signal application shutdown has started, so
+     *   this method may terminate without ever placing the event on the queue. (not null)
+     * @return {@code true} if the evet nwas added to the queue, otherwise false.
      */
-    private void runQuery(final String ryaInstanceName, final StreamsQuery query) {
-        requireNonNull(ryaInstanceName);
-        requireNonNull(query);
-        LOG.info("Starting Query: " + query.toString() + " on the rya instance: " + ryaInstanceName);
+    private static <T> boolean offerUntilAcceptedOrShutdown(
+            final BlockingQueue<T> workQueue,
+            final T event,
+            final long offerValue,
+            final TimeUnit offerUnits,
+            final AtomicBoolean shutdownSignal) {
+        requireNonNull(workQueue);
+        requireNonNull(event);
+        requireNonNull(shutdownSignal);
 
-        try {
-            queryExecutor.startQuery(ryaInstanceName, query);
-        } catch (final QueryExecutorException e) {
-            LOG.error("Failed to start query.", e);
+        boolean submitted = false;
+        while(!submitted && !shutdownSignal.get()) {
+            try {
+                submitted = workQueue.offer(event, offerValue, offerUnits);
+                if(!submitted) {
+                    log.debug("An event could not be added to a work queue after waiting 5 seconds. Trying again...");
+                }
+            } catch (final InterruptedException e) {
+                log.debug("An event could not be added to a work queue after waiting 5 seconds. Trying again...");
+            }
         }
+        return submitted;
     }
 
     /**
-     * Stops the specified query from running.
-     *
-     * @param queryId - The ID of the query to stop running. (not null)
+     * An observation that a {@link QueryChangeLog} was created within or
+     * removed from a {@link QueryChangeLogSource}.
      */
-    private void stopQuery(final UUID queryId) {
-        requireNonNull(queryId);
+    @DefaultAnnotation(NonNull.class)
+    static class LogEvent {
+
+        /**
+         * The types of events that may be observed.
+         */
+        static enum LogEventType {
+            /**
+             * A {@link QueryChangeLog} was created within a {@link QueryChangeLogSource}.
+             */
+            CREATE,
+
+            /**
+             * A {@link QueryChangeLog} was deleted from a {@link QueryChangeLogSource}.
+             */
+            DELETE;
+        }
 
-        LOG.info("Stopping query: " + queryId.toString());
+        private final String ryaInstance;
+        private final LogEventType eventType;
+        private final Optional<QueryChangeLog> log;
 
-        try {
-            queryExecutor.stopQuery(queryId);
-        } catch (final QueryExecutorException e) {
-            LOG.error("Failed to stop query.", e);
+        /**
+         * Constructs an instance of {@link LogEvent}.
+         *
+         * @param ryaInstance - The Rya Instance the log is/was for. (not null)
+         * @param eventType - The type of event that was observed. (not null)
+         * @param log - The log if this is a create event. (not null)
+         */
+        private LogEvent(final String ryaInstance, final LogEventType eventType, final Optional<QueryChangeLog> log) {
+            this.ryaInstance = requireNonNull(ryaInstance);
+            this.eventType = requireNonNull(eventType);
+            this.log = requireNonNull(log);
+        }
+
+        /**
+         * @return The Rya Instance whose log was either created or deleted.
+         */
+        public String getRyaInstanceName() {
+            return ryaInstance;
+        }
+
+        /**
+         * @return The type of event that was observed.
+         */
+        public LogEventType getEventType() {
+            return eventType;
+        }
+
+        /**
+         * @return The {@link QueryChangeLog} if this is a CREATE event.
+         */
+        public Optional<QueryChangeLog> getQueryChangeLog() {
+            return log;
+        }
+
+        @Override
+        public String toString() {
+            return "LogEvent {\n" +
+                   "    Rya Instance: " + ryaInstance + ",\n" +
+                   "    Event Type: " + eventType + "\n" +
+                   "}";
+        }
+
+        /**
+         * Make a {@link LogEvent} that indicates a {@link QueryChangeLog} was created within a
+         * {@link QueryChangeLogSource}.
+         *
+         * @param ryaInstance - The Rya Instance the created log is for. (not null)
+         * @param log - The created {@link QueryChangeLog. (not null)
+         * @return A {@link LogEvent} built using the provided values.
+         */
+        public static LogEvent create(final String ryaInstance, final QueryChangeLog log) {
+            return new LogEvent(ryaInstance, LogEventType.CREATE, Optional.of(log));
+        }
+
+        /**
+         * Make a {@link LogEvent} that indicates a {@link QueryChangeLog} was deleted from
+         * a {@link QueryChangeLogSource}.
+         *
+         * @param ryaInstance - The Rya Instance whose log was deleted. (not null)
+         * @return A {@link LogEvent} built using the provided values.
+         */
+        public static LogEvent delete(final String ryaInstance) {
+            return new LogEvent(ryaInstance, LogEventType.DELETE, Optional.empty());
         }
     }
 
-    @Override
-    protected void startUp() throws Exception {
-        lock.lock();
-        try {
-            LOG.info("Starting Query Manager.");
-            queryExecutor.startAndWait();
-            source.startAndWait();
+    /**
+     * An observation that a {@link StreamsQuery} needs to be executing or not
+     * via the provided {@link QueryExecutor}.
+     */
+    @DefaultAnnotation(NonNull.class)
+    static class QueryEvent {
+
+        /**
+         * The type of events that may be observed.
+         */
+        public static enum QueryEventType {
+            /**
+             * Indicates a {@link StreamsQuery} needs to be executing.
+             */
+            EXECUTING,
+
+            /**
+             * Indicates a {@link StreamsQuery} needs to be stopped.
+             */
+            STOPPED,
+
+            /**
+             * Indicates all {@link StreamsQuery}s for a Rya instance need to be stopped.
+             */
+            STOP_ALL;
+        }
+
+        private final String ryaInstance;
+        private final QueryEventType type;
+        private final Optional<UUID> queryId;
+        private final Optional<StreamsQuery> query;
+
+        /**
+         * Constructs an instance of {@link QueryEvent}.
+         *
+         * @param ryaInstance - The Rya instance that generated the event. (not null)
+         * @param type - Indicates whether the query needs to be executing or not. (not null)
+         * @param queryId - If stopped, the ID of the query that must not be running. (not null)
+         * @param query - If executing, the StreamsQuery that defines what should be executing. (not null)
+         */
+        private QueryEvent(
+                final String ryaInstance,
+                final QueryEventType type,
+                final Optional<UUID> queryId,
+                final Optional<StreamsQuery> query) {
+            this.ryaInstance = requireNonNull(ryaInstance);
+            this.type = requireNonNull(type);
+            this.queryId = requireNonNull(queryId);
+            this.query = requireNonNull(query);
+        }
+
+        /**
+         * @return The Rya instance that generated the event.
+         */
+        public String getRyaInstance() {
+            return ryaInstance;
+        }
+
+        /**
+         * @return Indicates whether the query needs to be executing or not.
+         */
+        public QueryEventType getType() {
+            return type;
+        }
+
+        /**
+         * @return If stopped, the ID of the query that must not be running. Otherwise absent.
+         */
+        public Optional<UUID> getQueryId() {
+            return queryId;
+        }
+
+        /**
+         * @return If executing, the StreamsQuery that defines what should be executing. Otherwise absent.
+         */
+        public Optional<StreamsQuery> getStreamsQuery() {
+            return query;
+        }
 
-            // subscribe to the sources to be notified of changes.
-            source.subscribe(new QueryManagerSourceListener());
-        } finally {
-            lock.unlock();
+        @Override
+        public int hashCode() {
+            return Objects.hash(ryaInstance, type, queryId, query);
+        }
+
+        @Override
+        public boolean equals(final Object o) {
+            if(o instanceof QueryEvent) {
+                final QueryEvent other = (QueryEvent) o;
+                return Objects.equals(ryaInstance, other.ryaInstance) &&
+                        Objects.equals(type, other.type) &&
+                        Objects.equals(queryId, other.queryId) &&
+                        Objects.equals(query, other.query);
+            }
+            return false;
+        }
+
+        @Override
+        public String toString() {
+            final StringBuilder string = new StringBuilder();
+            string.append("Query Event {\n")
+                  .append("    Rya Instance: ").append(ryaInstance).append(",\n")
+                  .append("    Type: ").append(type).append(",\n");
+            switch(type) {
+                case EXECUTING:
+                    append(string, query.get());
+                    break;
+                case STOPPED:
+                    string.append("    Query ID: ").append(queryId.get()).append("\n");
+                    break;
+                case STOP_ALL:
+                    break;
+                default:
+                    // Default to showing everything that is in the object.
+                    string.append("    Query ID: ").append(queryId.get()).append("\n");
+                    append(string, query.get());
+                    break;
+            }
+            string.append("}");
+            return string.toString();
+        }
+
+        private void append(final StringBuilder string, final StreamsQuery query) {
+            requireNonNull(string);
+            requireNonNull(query);
+            string.append("    Streams Query {\n")
+                  .append("        Query ID: ").append(query.getQueryId()).append(",\n")
+                  .append("        Is Active: ").append(query.isActive()).append(",\n")
+                  .append("        SPARQL: ").append(query.getSparql()).append("\n")
+                  .append("    }");
+        }
+
+        /**
+         * Create a {@link QueryEvent} that indicates a query needs to be executing.
+         *
+         * @param ryaInstance - The Rya instance that generated the event. (not null)
+         * @param query - The StreamsQuery that defines what should be executing. (not null)
+         * @return A {@link QueryEvent} built using the provided values.
+         */
+        public static QueryEvent executing(final String ryaInstance, final StreamsQuery query) {
+            return new QueryEvent(ryaInstance, QueryEventType.EXECUTING, Optional.empty(), Optional.of(query));
+        }
+
+        /**
+         * Create a {@link QueryEvent} that indicates a query needs to be stopped.
+         *
+         * @param ryaInstance - The Rya instance that generated the event. (not null)
+         * @param queryId - The ID of the query that must not be running. (not null)
+         * @return A {@link QueryEvent} built using the provided values.
+         */
+        public static QueryEvent stopped(final String ryaInstance, final UUID queryId) {
+            return new QueryEvent(ryaInstance, QueryEventType.STOPPED, Optional.of(queryId), Optional.empty());
+        }
+
+        /**
+         * Create a {@link QueryEvent} that indicates all queries for a Rya instance needs to be stopped.
+         *
+         * @param ryaInstance - The Rya instance that generated the event. (not null)
+         * @return A {@link QueryEvent} built using the provided values.
+         */
+        public static QueryEvent stopALL(final String ryaInstance) {
+            return new QueryEvent(ryaInstance, QueryEventType.STOP_ALL, Optional.empty(), Optional.empty());
         }
     }
 
-    @Override
-    protected void shutDown() throws Exception {
-        lock.lock();
-        try {
-            LOG.info("Stopping Query Manager.");
-            source.stopAndWait();
-            queryExecutor.stopAndWait();
-        } finally {
-            lock.unlock();
+    /**
+     * Listens to a {@link QueryChangeLogSource} and adds observations to the provided
+     * work queue. It does so until the provided shutdown signal is set.
+     */
+    @DefaultAnnotation(NonNull.class)
+    static class LogEventWorkGenerator implements SourceListener {
+
+        private final BlockingQueue<LogEvent> workQueue;
+        private final AtomicBoolean shutdownSignal;
+        private final long offerValue;
+        private final TimeUnit offerUnits;
+
+        /**
+         * Constructs an instance of {@link QueryManagerSourceListener}.
+         *
+         * @param workQueue - A blocking queue that will have {@link LogEvent}s offered to it. (not null)
+         * @param offerValue - How long to wait when offering new work.
+         * @param offerUnits - The unit for the {@code offerValue}. (not null)
+         * @param shutdownSignal - Indicates to this listener that it needs to stop adding events
+         *   to the work queue because the application is shutting down. (not null)
+         */
+        public LogEventWorkGenerator(
+                final BlockingQueue<LogEvent> workQueue,
+                final long offerValue,
+                final TimeUnit offerUnits,
+                final AtomicBoolean shutdownSignal) {
+            this.workQueue = requireNonNull(workQueue);
+            this.shutdownSignal = requireNonNull(shutdownSignal);
+            this.offerValue = offerValue;
+            this.offerUnits = requireNonNull(offerUnits);
+        }
+
+        @Override
+        public void notifyCreate(final String ryaInstanceName, final QueryChangeLog changeLog) {
+            log.info("A new Query Change Log has been discovered for Rya Instance " + ryaInstanceName + ". All " +
+                    "queries that are set to active within it will be started.");
+
+            // Create an event that summarizes this notification.
+            final LogEvent event = LogEvent.create(ryaInstanceName, changeLog);
+
+            // Offer it to the worker until there is room for it in the work queue, or we are shutting down.
+            offerUntilAcceptedOrShutdown(workQueue, event, offerValue, offerUnits, shutdownSignal);
+        }
+
+        @Override
+        public void notifyDelete(final String ryaInstanceName) {
+            log.info("The Query Change Log for Rya Instance " + ryaInstanceName + " has been deleted. All of the " +
+                    "queries related to that instance will be stopped.");
+
+            // Create an event that summarizes this notification.
+            final LogEvent event = LogEvent.delete(ryaInstanceName);
+
+            // Offer it to the worker until there is room for it in the work queue, or we are shutting down.
+            offerUntilAcceptedOrShutdown(workQueue, event, offerValue, offerUnits, shutdownSignal);
         }
     }
 
     /**
-     * An implementation of {@link QueryChangeLogListener} for the
-     * {@link QueryManager}.
-     * <p>
-     * When notified of a {@link ChangeType} performs one of the following:
-     * <li>{@link ChangeType#CREATE}: Creates a new query using the
-     * {@link QueryExecutor} provided to the {@link QueryManager}</li>
-     * <li>{@link ChangeType#DELETE}: Deletes a running query by stopping the
-     * {@link QueryExecutor} service of the queryID in the event</li>
-     * <li>{@link ChangeType#UPDATE}: If the query is running and the update is
-     * to stop the query, stops the query. Otherwise, if the query is not
-     * running, it is removed.</li>
+     * Processes a work queue of {@link LogEvent}s.
+     * <p/>
+     * Whenever a new log has been created, then it registers a {@link QueryEventWorkGenerator}
+     * that generates {@link QueryEvent}s based on the content and updates to the discovered
+     * {@link QueryChagneLog}.
+     * <p/>
+     * Whenever a log is deleted, then the generator is stopped and a stop all {@link QueryEvent}
+     * is written to the work queue.
      */
-    private class QueryExecutionForwardingListener implements QueryChangeLogListener {
-        private final String ryaInstanceName;
+    @DefaultAnnotation(NonNull.class)
+    static class LogEventWorker implements Runnable {
 
         /**
-         * Creates a new {@link QueryExecutionForwardingListener}.
+         * A map of Rya Instance name to he Query Repository for that instance.
+         */
+        private final Map<String, QueryRepository> repos = new HashMap<>();
+
+        private final BlockingQueue<LogEvent> logWorkQueue;
+        private final BlockingQueue<QueryEvent> queryWorkQueue;
+        private final long blockingValue;
+        private final TimeUnit blockingUnits;
+        private final AtomicBoolean shutdownSignal;
+
+        /**
+         * Constructs an instance of {@link LogEventWorker}.
          *
-         * @param ryaInstanceName - The rya instance the query change is
-         *        performed on. (not null)
+         * @param logWorkQueue - A queue of {@link LogEvent}s that will be worked by this object. (not null)
+         * @param queryWorkQueue - A queue where {@link QueryEvent}s will be placed by this object. (not null)
+         * @param blockingValue - How long to wait when polling/offering new work.
+         * @param blockingUnits - The unit for the {@code blockingValue}. (not null)
+         * @param shutdownSignal - Indicates when the application has been shutdown, so the executing thread
+         *   may exit the {@link #run()} method. (not null)
          */
-        public QueryExecutionForwardingListener(final String ryaInstanceName) {
-            this.ryaInstanceName = requireNonNull(ryaInstanceName);
+        public LogEventWorker(
+                final BlockingQueue<LogEvent> logWorkQueue,
+                final BlockingQueue<QueryEvent> queryWorkQueue,
+                final long blockingValue,
+                final TimeUnit blockingUnits,
+                final AtomicBoolean shutdownSignal) {
+            this.logWorkQueue = requireNonNull(logWorkQueue);
+            this.queryWorkQueue = requireNonNull(queryWorkQueue);
+            this.blockingValue = blockingValue;
+            this.blockingUnits = requireNonNull(blockingUnits);
+            this.shutdownSignal = requireNonNull(shutdownSignal);
         }
 
         @Override
-        public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent, final Optional<StreamsQuery> newQueryState) {
-            LOG.debug("New query change event.");
-            final QueryChange entry = queryChangeEvent.getEntry();
+        public void run() {
+            // Run until the shutdown signal is set.
+            while(!shutdownSignal.get()) {
+                try {
+                    // Pull a unit of work from the queue.
+                    log.debug("LogEventWorker - Polling the work queue for a new LogEvent.");
+                    final LogEvent logEvent = logWorkQueue.poll(blockingValue, blockingUnits);
+                    if(logEvent == null) {
+                        // Poll again if nothing was found.
+                        continue;
+                    }
 
-            lock.lock();
-            try {
+                    log.info("LogEventWorker - handling: \n" + logEvent);
+                    final String ryaInstance = logEvent.getRyaInstanceName();
 
-                switch (entry.getChangeType()) {
-                    case CREATE:
-                        if(!newQueryState.isPresent()) {
-                            LOG.error("The query with ID: " + entry.getQueryId() + " must be present with the change to be created.");
-                            LOG.debug("newQueryState is not allowed to be absent with a CREATE QueryChange, there might be a bug in the QueryRepository.");
-                        } else {
-                            runQuery(ryaInstanceName, newQueryState.get());
-                        }
-                        break;
-                    case DELETE:
-                        stopQuery(entry.getQueryId());
-                        break;
-                    case UPDATE:
-                        if (!newQueryState.isPresent()) {
-                            LOG.error("The query with ID: " + entry.getQueryId() + " must be provided with the update, cannot perform update.");
-                            LOG.debug("newQueryState is not allowed to be absent with a UPDATE QueryChange, there might be a bug in the QueryRepository.");
-                        } else {
-                            final StreamsQuery updatedQuery = newQueryState.get();
-                            if (updatedQuery.isActive()) {
-                                runQuery(ryaInstanceName, updatedQuery);
-                                LOG.info("Starting query: " + updatedQuery.toString());
-                            } else {
-                                stopQuery(updatedQuery.getQueryId());
-                                LOG.info("Stopping query: " + updatedQuery.toString());
+                    switch(logEvent.getEventType()) {
+                        case CREATE:
+                            // If we see a create message for a Rya Instance we are already maintaining,
+                            // then don't do anything.
+                            if(repos.containsKey(ryaInstance)) {
+                                log.warn("LogEventWorker - A repository is already being managed for the Rya Instance " +
+                                        ryaInstance + ". This message will be ignored.");
+                                continue;
                             }
-                        }
-                        break;
+
+                            // Create and start a QueryRepository for the discovered log. Hold onto the repository
+                            // so that it may be shutdown later.
+                            final Scheduler scheduler = Scheduler.newFixedRateSchedule(0, blockingValue, blockingUnits);
+                            final QueryRepository repo = new InMemoryQueryRepository(logEvent.getQueryChangeLog().get(), scheduler);
+                            repo.startAndWait();
+                            repos.put(ryaInstance, repo);
+
+                            // Subscribe a worker that adds the Query Events to the queryWorkQueue queue.
+                            // A count down latch is used to ensure the returned set of queries are handled
+                            // prior to any notifications from the repository.
+                            final CountDownLatch subscriptionWorkFinished = new CountDownLatch(1);
+                            final QueryEventWorkGenerator queryWorkGenerator =
+                                    new QueryEventWorkGenerator(ryaInstance, subscriptionWorkFinished, queryWorkQueue,
+                                            blockingValue, blockingUnits, shutdownSignal);
+
+                            log.debug("LogEventWorker - Setting up a QueryWorkGenerator...");
+                            final Set<StreamsQuery> queries = repo.subscribe(queryWorkGenerator);
+                            log.debug("LogEventWorker - Finished setting up a QueryWorkGenerator.");
+
+                            // Handle the view of the queries within the repository as it existed when
+                            // the subscription was registered.
+                            queries.stream()
+                            .forEach(query -> {
+                                // Create a QueryEvent that represents the active state of the existing query.
+                                final QueryEvent queryEvent = query.isActive() ?
+                                        QueryEvent.executing(ryaInstance, query) : QueryEvent.stopped(ryaInstance, query.getQueryId());
+                                log.debug("LogEventWorker - offering: " + queryEvent);
+
+                                // Offer it to the worker until there is room for it in the work queue, or we are shutting down.
+                                offerUntilAcceptedOrShutdown(queryWorkQueue, queryEvent, blockingValue, blockingUnits, shutdownSignal);
+                            });
+
+                            // Indicate the subscription work is finished so that the registered listener may start
+                            // adding work to the queue.
+                            log.info("LogEventWorker - Counting down the subscription work latch.");
+                            subscriptionWorkFinished.countDown();
+                            break;
+
+                        case DELETE:
+                            if(repos.containsKey(ryaInstance)) {
+                                // Shut down the query repository for the Rya instance. This ensures the listener will
+                                // not receive any more work that needs to be done.
+                                final QueryRepository deletedRepo = repos.remove(ryaInstance);
+                                deletedRepo.stopAndWait();
+
+                                // Add work that stops all of the queries related to the instance.
+                                final QueryEvent stopAllEvent = QueryEvent.stopALL(ryaInstance);
+                                offerUntilAcceptedOrShutdown(queryWorkQueue, stopAllEvent, blockingValue, blockingUnits, shutdownSignal);
+                            }
+                            break;
+                    }
+                } catch (final InterruptedException e) {
+                    log.debug("LogEventWorker did not see any new events over the past 5 seconds. Polling again...");
                 }
-            } finally {
-                lock.unlock();
             }
+
+            log.info("LogEventWorker shutting down...");
+
+            // Shutdown all of the QueryRepositories that were started.
+            repos.values().forEach(repo -> repo.stopAndWait());
+
+            log.info("LogEventWorker shut down.");
         }
     }
 
     /**
-     * Listener used by the {@link QueryManager} to be notified when
-     * {@link QueryChangeLog}s are created or deleted.
+     * Listens to a {@link QueryRepository} and adds observations to the provided work queue.
+     * It does so until the provided shutdown signal is set.
      */
-    private class QueryManagerSourceListener implements SourceListener {
+    @DefaultAnnotation(NonNull.class)
+    static class QueryEventWorkGenerator implements QueryChangeLogListener {
+
+        private final String ryaInstance;
+        private final CountDownLatch subscriptionWorkFinished;
+        private final BlockingQueue<QueryEvent> queryWorkQueue;
+        private final long blockingValue;
+        private final TimeUnit blockingUnits;
+        private final AtomicBoolean shutdownSignal;
+
+        /**
+         * Constructs an instance of {@link QueryEventWorkGenerator}.
+         *
+         * @param ryaInstance - The rya instance whose log this objects is watching. (not null)
+         * @param subscriptionWorkFinished - Indicates when work that needs to be completed before this
+         *   listener handles notifications is completed. (not null)
+         * @param queryWorkQueue - A queue where {@link QueryEvent}s will be placed by this object. (not null)
+         * @param blockingValue - How long to wait when polling/offering new work.
+         * @param blockingUnits - The unit for the {@code blockingValue}. (not null)
+         * @param shutdownSignal - Indicates to this listener that it needs to stop adding events
+         *   to the work queue because the application is shutting down. (not null)
+         */
+        public QueryEventWorkGenerator(
+                final String ryaInstance,
+                final CountDownLatch subscriptionWorkFinished,
+                final BlockingQueue<QueryEvent> queryWorkQueue,
+                final long blockingValue,
+                final TimeUnit blockingUnits,
+                final AtomicBoolean shutdownSignal) {
+            this.ryaInstance = requireNonNull(ryaInstance);
+            this.subscriptionWorkFinished = requireNonNull(subscriptionWorkFinished);
+            this.queryWorkQueue = requireNonNull(queryWorkQueue);
+            this.blockingValue = blockingValue;
+            this.blockingUnits = requireNonNull(blockingUnits);
+            this.shutdownSignal = requireNonNull(shutdownSignal);
+        }
+
         @Override
-        public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
-            lock.lock();
+        public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent, final Optional<StreamsQuery> newQueryState) {
+            requireNonNull(queryChangeEvent);
+            requireNonNull(newQueryState);
+
+            // Wait for the subscription work to be finished.
             try {
-                LOG.info("Discovered new Query Change Log for Rya Instance " + ryaInstanceName + ".");
-                final QueryRepository repo = new InMemoryQueryRepository(log, scheduler);
-                repo.startAndWait();
-                final Set<StreamsQuery> queries = repo.subscribe(new QueryExecutionForwardingListener(ryaInstanceName));
-                queries.forEach(query -> {
-                    if (query.isActive()) {
-                        try {
-                            queryExecutor.startQuery(ryaInstanceName, query);
-                        } catch (IllegalStateException | QueryExecutorException e) {
-                            LOG.error("Unable to start query for rya instance " + ryaInstanceName, e);
+                log.debug("Waiting for Subscription Work Finished latch to release...");
+                while(!shutdownSignal.get() && !subscriptionWorkFinished.await(blockingValue, blockingUnits)) {
+                    log.debug("Still waiting...");
+                }
+                log.debug("Subscription Work Finished latch to released.");
+            } catch (final InterruptedException e) {
+                log.warn("Interrupted while waiting for the Subscription Work Finished latch to be " +
+                        "released. Shutting down?", e);
+            }
+
+            // If we left the loop because of a shutdown, return immediately.
+            if(shutdownSignal.get()) {
+                log.debug("Not processing notification. Shutting down.");
+                return;
+            }
+
+            // Generate work from the notification.
+            final QueryChange change = queryChangeEvent.getEntry();
+            switch(change.getChangeType()) {
+                case CREATE:
+                    if(newQueryState.isPresent()) {
+                        log.info("Rya Instance " + ryaInstance + " created Rya Streams query " + newQueryState + ".");
+                        final StreamsQuery newQuery = newQueryState.get();
+                        if(newQuery.isActive()) {
+                            final QueryEvent executeNewQuery = QueryEvent.executing(ryaInstance, newQuery);
+                            offerUntilAcceptedOrShutdown(queryWorkQueue, executeNewQuery, blockingValue, blockingUnits, shutdownSignal);
                         }
+                    } else {
+                        log.error("Received a CREATE QueryChange for Rya Instance: " + ryaInstance +
+                                ", Query ID: " + change.getQueryId() + ", but the QueryRepository did not supply a " +
+                                "StreamsQuery representing the created query. The query will not be processed.");
                     }
-                });
-                queryRepos.put(ryaInstanceName, repo);
-            } finally {
-                lock.unlock();
+                    break;
+
+                case DELETE:
+                    final UUID deletedQueryId = change.getQueryId();
+                    log.info("Rya Instance " + ryaInstance + " deleted Rya Streams query with ID " + deletedQueryId);
+                    final QueryEvent stopDeletedQuery = QueryEvent.stopped(ryaInstance, deletedQueryId);
+                    offerUntilAcceptedOrShutdown(queryWorkQueue, stopDeletedQuery, blockingValue, blockingUnits, shutdownSignal);
+                    break;
+
+                case UPDATE:
+                    if(newQueryState.isPresent()) {
+                        final StreamsQuery updatedQuery = newQueryState.get();
+                        if(updatedQuery.isActive()) {
+                            log.info("Rya Instance " + ryaInstance + " updated Rya Streams query with ID " +
+                                    updatedQuery.getQueryId() + " to be active.");
+                            final QueryEvent executeUpdatedQuery = QueryEvent.executing(ryaInstance, updatedQuery);
+                            offerUntilAcceptedOrShutdown(queryWorkQueue, executeUpdatedQuery, blockingValue, blockingUnits, shutdownSignal);
+                        } else {
+                            log.info("Rya Instance " + ryaInstance + " updated Rya Streams query with ID " +
+                                    updatedQuery.getQueryId() + " to be inactive.");
+                            final QueryEvent stopUpdatedQuery = QueryEvent.stopped(ryaInstance, updatedQuery.getQueryId());
+                            offerUntilAcceptedOrShutdown(queryWorkQueue, stopUpdatedQuery, blockingValue, blockingUnits, shutdownSignal);
+                        }
+                    } else {
+                        log.error("Received an UPDATE QueryChange for Rya Instance: " + ryaInstance +
+                                ", Query ID: " + change.getQueryId() + ", but the QueryRepository did not supply a " +
+                                "StreamsQuery representing the created query. The query will not be processed.");
+                    }
+                    break;
             }
         }
+    }
+
+    /**
+     * Processes a work queue of {@link QueryEvent}s.
+     * <p/>
+     * Each type of event maps the to corresponding method on {@link QueryExecutor} that is called into.
+     */
+    @DefaultAnnotation(NonNull.class)
+    static class QueryEventWorker implements Runnable {
+
+        private final BlockingQueue<QueryEvent> workQueue;
+        private final QueryExecutor queryExecutor;
+        private final long pollingValue;
+        private final TimeUnit pollingUnits;
+        private final AtomicBoolean shutdownSignal;
+
+        /**
+         * Constructs an instance of {@link QueryEventWorker}.
+         *
+         * @param workQueue - A queue of {@link QueryEvent}s that will be worked by this object. (not null)
+         * @param queryExecutor - Responsible for executing the {@link StreamsQuery}s. (not null)
+         * @param pollingValue - How long to wait when polling for new work.
+         * @param pollingUnits - The units for the {@code pollingValue}. (not null)
+         * @param shutdownSignal - Indicates when the application has been shutdown, so the executing thread
+         *   may exit the {@link #run()} method. (not null)
+         */
+        public QueryEventWorker(
+                final BlockingQueue<QueryEvent> workQueue,
+                final QueryExecutor queryExecutor,
+                final long pollingValue,
+                final TimeUnit pollingUnits,
+                final AtomicBoolean shutdownSignal) {
+            this.workQueue = requireNonNull(workQueue);
+            this.queryExecutor = requireNonNull(queryExecutor);
+            this.pollingValue = pollingValue;
+            this.pollingUnits = requireNonNull(pollingUnits);
+            this.shutdownSignal = requireNonNull(shutdownSignal);
+        }
 
         @Override
-        public void notifyDelete(final String ryaInstanceName) {
-            lock.lock();
-            try {
-                LOG.info("Notified of deleting QueryChangeLog, stopping all queries belonging to the change log for "
-                        + ryaInstanceName + ".");
-                queryExecutor.stopAll(ryaInstanceName);
-            } catch (final QueryExecutorException e) {
-                LOG.error("Failed to stop all queries belonging to: " + ryaInstanceName, e);
-            } finally {
-                lock.unlock();
+        public void run() {
+            log.info("QueryEventWorker starting.");
+
+            // Run until the shutdown signal is set.
+            while(!shutdownSignal.get()) {
+                // Pull a unit of work from the queue.
+                try {
+                    log.debug("Polling the work queue for a new QueryEvent.");
+                    final QueryEvent event = workQueue.poll(pollingValue, pollingUnits);
+                    if(event == null) {
+                        // Poll again if nothing was found.
+                        continue;
+                    }
+
+                    log.info("QueryEventWorker handling:\n" + event);
+
+                    // Ensure the state within the executor matches the query event's state.
+                    switch(event.getType()) {
+                        case EXECUTING:
+                            try {
+                                queryExecutor.startQuery(event.getRyaInstance(), event.getStreamsQuery().get());
+                            } catch (final IllegalStateException | QueryExecutorException e) {
+                                log.error("Could not start a query represented by the following work: " + event, e);
+                            }
+                            break;
+
+                        case STOPPED:
+                            try {
+                                queryExecutor.stopQuery(event.getQueryId().get());
+                            } catch (final IllegalStateException | QueryExecutorException e) {
+                                log.error("Could not stop a query represented by the following work: " + event, e);
+                            }
+                            break;
+
+                        case STOP_ALL:
+                            try {
+                                queryExecutor.stopAll(event.getRyaInstance());
+                            } catch (final IllegalStateException | QueryExecutorException e) {
+                                log.error("Could not stop all queries represented by the following work: " + event, e);
+                            }
+                        break;
+                    }
+                } catch (final InterruptedException e) {
+                    log.debug("QueryEventWorker interrupted. Probably shutting down.");
+                }
             }
+            log.info("QueryEventWorker shut down.");
         }
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
index 515d699..04a0382 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
@@ -33,6 +33,7 @@ import org.apache.commons.daemon.DaemonContext;
 import org.apache.commons.daemon.DaemonInitException;
 import org.apache.rya.streams.kafka.KafkaStreamsFactory;
 import org.apache.rya.streams.kafka.SingleThreadKafkaStreamsFactory;
+import org.apache.rya.streams.kafka.interactor.CreateKafkaTopic;
 import org.apache.rya.streams.querymanager.kafka.KafkaQueryChangeLogSource;
 import org.apache.rya.streams.querymanager.kafka.LocalQueryExecutor;
 import org.apache.rya.streams.querymanager.xml.Kafka;
@@ -91,7 +92,7 @@ public class QueryManagerDaemon implements Daemon {
 
         // Unmarshall the configuration file into an object.
         final QueryManagerConfig config;
-        try(InputStream stream = Files.newInputStream(configFile)) {
+        try(final InputStream stream = Files.newInputStream(configFile)) {
             config = QueryManagerConfigUnmarshaller.unmarshall(stream);
         } catch(final JAXBException | SAXException e) {
             throw new DaemonInitException("Unable to marshall the configuration XML file: " + configFile, e);
@@ -110,11 +111,12 @@ public class QueryManagerDaemon implements Daemon {
         final QueryChangeLogSource source = new KafkaQueryChangeLogSource(kafka.getHostname(), kafka.getPort(), scheduler);
 
         // Initialize a QueryExecutor.
+        final String zookeeperServers = config.getQueryExecutor().getLocalKafkaStreams().getZookeepers();
         final KafkaStreamsFactory streamsFactory = new SingleThreadKafkaStreamsFactory(kafka.getHostname() + ":" + kafka.getPort());
-        final QueryExecutor queryExecutor = new LocalQueryExecutor(streamsFactory);
+        final QueryExecutor queryExecutor = new LocalQueryExecutor(new CreateKafkaTopic(zookeeperServers), streamsFactory);
 
         // Initialize the QueryManager using the configured resources.
-        manager = new QueryManager(queryExecutor, source, scheduler);
+        manager = new QueryManager(queryExecutor, source, period, units);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/1cd8db32/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
index 32305f5..e746baf 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
@@ -33,11 +33,12 @@ import org.apache.kafka.clients.CommonClientConfigs;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.clients.consumer.KafkaConsumer;
 import org.apache.kafka.common.serialization.StringDeserializer;
-import org.apache.rya.streams.api.queries.QueryChangeLog;
 import org.apache.rya.streams.kafka.KafkaTopics;
 import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLog;
 import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLogFactory;
 import org.apache.rya.streams.querymanager.QueryChangeLogSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import com.google.common.collect.Sets;
 import com.google.common.util.concurrent.AbstractScheduledService;
@@ -53,6 +54,8 @@ import edu.umd.cs.findbugs.annotations.NonNull;
 @DefaultAnnotation(NonNull.class)
 public class KafkaQueryChangeLogSource extends AbstractScheduledService implements QueryChangeLogSource {
 
+    private static final Logger log = LoggerFactory.getLogger(KafkaQueryChangeLogSource.class);
+
     /**
      * Ensures thread safe interactions with this object.
      */
@@ -74,10 +77,10 @@ public class KafkaQueryChangeLogSource extends AbstractScheduledService implemen
     private final Set<SourceListener> listeners = new HashSet<>();
 
     /**
-     * Maps Rya instance name to a Query Change Log for that instance. This map is used to keep
-     * track of how the change logs change over time within the Kafka Server.
+     * Maps Rya instance names to the Query Change Log topic name in Kafka. This map is used to
+     * keep track of how the change logs change over time within the Kafka Server.
      */
-    private final HashMap<String, QueryChangeLog> knownChangeLogs = new HashMap<>();
+    private final HashMap<String, String> knownChangeLogs = new HashMap<>();
 
     /**
      * A consumer that is used to poll the Kafka Server for topics.
@@ -101,6 +104,8 @@ public class KafkaQueryChangeLogSource extends AbstractScheduledService implemen
 
     @Override
     protected void startUp() throws Exception {
+        log.info("Kafka Query Change Log Source watching " + kafkaBootstrapServer + " starting up...");
+
         // Setup the consumer that is used to list topics for the source.
         final Properties consumerProperties = new Properties();
         consumerProperties.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaBootstrapServer);
@@ -108,17 +113,23 @@ public class KafkaQueryChangeLogSource extends AbstractScheduledService implemen
         consumerProperties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
         consumerProperties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
         listTopicsConsumer = new KafkaConsumer<>(consumerProperties);
+
+        log.info("Kafka Query Change Log Source watching " + kafkaBootstrapServer + " started.");
     }
 
     @Override
     protected void shutDown() throws Exception {
-        // Shut down the consumer that's used to list topics.
-        listTopicsConsumer.close();
+        log.info("Kafka Query Change Log Source watching " + kafkaBootstrapServer + " shutting down...");
 
-        // Shut down all of the change logs that were created within this class.
-        for(final QueryChangeLog changeLog : knownChangeLogs.values()) {
-            changeLog.close();
+        lock.lock();
+        try {
+            // Shut down the consumer that's used to list topics.
+            listTopicsConsumer.close();
+        } finally {
+            lock.unlock();
         }
+
+        log.info("Kafka Query Change Log Source watching " + kafkaBootstrapServer + " shut down.");
     }
 
     @Override
@@ -130,8 +141,10 @@ public class KafkaQueryChangeLogSource extends AbstractScheduledService implemen
             listeners.add(listener);
 
             // Notify it with everything that already exists.
-            for(final Entry<String, QueryChangeLog> entry : knownChangeLogs.entrySet()) {
-                listener.notifyCreate(entry.getKey(), entry.getValue());
+            for(final Entry<String, String> entry : knownChangeLogs.entrySet()) {
+                final String changeLogTopic = entry.getValue();
+                final KafkaQueryChangeLog changeLog = KafkaQueryChangeLogFactory.make(kafkaBootstrapServer, changeLogTopic);
+                listener.notifyCreate(entry.getKey(), changeLog);
             }
         } finally {
             lock.unlock();
@@ -174,26 +187,23 @@ public class KafkaQueryChangeLogSource extends AbstractScheduledService implemen
             // Handle the deletes.
             for(final String deletedRyaInstance : deletedRyaInstances) {
                 // Remove the change log from the set of known logs.
-                final QueryChangeLog removed = knownChangeLogs.remove(deletedRyaInstance);
+                knownChangeLogs.remove(deletedRyaInstance);
 
-                // Notify the listeners of the update.
+                // Notify the listeners of the update so that they may close the previously provided change log.
                 for(final SourceListener listener : listeners) {
                     listener.notifyDelete(deletedRyaInstance);
                 }
-
-                // Ensure the change log is closed.
-                removed.close();
             }
 
             // Handle the adds.
             for(final String createdRyaInstance : createdRyaInstances) {
                 // Create and store the ChangeLog.
                 final String changeLogTopic = KafkaTopics.queryChangeLogTopic(createdRyaInstance);
-                final KafkaQueryChangeLog changeLog = KafkaQueryChangeLogFactory.make(kafkaBootstrapServer, changeLogTopic);
-                knownChangeLogs.put(createdRyaInstance, changeLog);
+                knownChangeLogs.put(createdRyaInstance, changeLogTopic);
 
                 // Notify the listeners of the update.
                 for(final SourceListener listener : listeners) {
+                    final KafkaQueryChangeLog changeLog = KafkaQueryChangeLogFactory.make(kafkaBootstrapServer, changeLogTopic);
                     listener.notifyCreate(createdRyaInstance, changeLog);
                 }
             }



[11/22] incubator-rya git commit: RYA-453 Implement the Query Manager's Daemon that controls the application.

Posted by pu...@apache.org.
RYA-453 Implement the Query Manager's Daemon that controls the application.



Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/16202ac7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/16202ac7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/16202ac7

Branch: refs/heads/master
Commit: 16202ac7d81a37d56f9a3a54f22f79bbea3fe8d5
Parents: e355f73
Author: kchilton2 <ke...@gmail.com>
Authored: Tue Jan 30 14:44:58 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:48 2018 -0500

----------------------------------------------------------------------
 extras/rya.streams/query-manager/pom.xml        |  5 +
 .../querymanager/QueryManagerDaemon.java        | 99 ++++++++++++++++++--
 .../xml/QueryManagerConfigUnmarshaller.java     | 10 +-
 .../xml/QueryManagerConfigMarshallerTest.java   | 13 ++-
 4 files changed, 110 insertions(+), 17 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/16202ac7/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
index 2141a3a..deaccdb 100644
--- a/extras/rya.streams/query-manager/pom.xml
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -47,6 +47,11 @@ under the License.
             <version>1.1.0</version>
         </dependency>
         
+        <dependency>
+            <groupId>com.beust</groupId>
+            <artifactId>jcommander</artifactId>
+        </dependency>
+        
         <!-- Test dependencies -->
         <dependency>
             <groupId>junit</groupId>

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/16202ac7/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
index 2ab0ad8..515d699 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryManagerDaemon.java
@@ -1,4 +1,4 @@
-/*
+/**
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -18,32 +18,117 @@
  */
 package org.apache.rya.streams.querymanager;
 
+import static java.util.Objects.requireNonNull;
+
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.concurrent.TimeUnit;
+
+import javax.xml.bind.JAXBException;
+
 import org.apache.commons.daemon.Daemon;
 import org.apache.commons.daemon.DaemonContext;
 import org.apache.commons.daemon.DaemonInitException;
+import org.apache.rya.streams.kafka.KafkaStreamsFactory;
+import org.apache.rya.streams.kafka.SingleThreadKafkaStreamsFactory;
+import org.apache.rya.streams.querymanager.kafka.KafkaQueryChangeLogSource;
+import org.apache.rya.streams.querymanager.kafka.LocalQueryExecutor;
+import org.apache.rya.streams.querymanager.xml.Kafka;
+import org.apache.rya.streams.querymanager.xml.QueryManagerConfig;
+import org.apache.rya.streams.querymanager.xml.QueryManagerConfig.PerformanceTunning.QueryChanngeLogDiscoveryPeriod;
+import org.apache.rya.streams.querymanager.xml.QueryManagerConfigUnmarshaller;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xml.sax.SAXException;
+
+import com.beust.jcommander.JCommander;
+import com.beust.jcommander.Parameter;
+import com.beust.jcommander.ParameterException;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
 
+/**
+ * JSVC integration code for a {@link QueryManager} to be used as a non-Windows daemon.
+ */
 @DefaultAnnotation(NonNull.class)
 public class QueryManagerDaemon implements Daemon {
+
+    private static final Logger log = LoggerFactory.getLogger(QueryManagerDaemon.class);
+
+    /**
+     * The default configuration file's path for the application.
+     */
+    private static final Path DEFAULT_CONFIGURATION_PATH = Paths.get("config/configuration.xml");
+
+    /**
+     * Command line parameters that are used by all commands that interact with Kafka.
+     */
+    class DaemonParameters {
+        @Parameter(names = {"--config", "-c"}, required = false, description = "The path to the application's configuration file.")
+        public String config;
+    }
+
+    private QueryManager manager = null;
+
     @Override
     public void init(final DaemonContext context) throws DaemonInitException, Exception {
-        System.out.println("Initializing Query Manager Daemon.");
+        requireNonNull(context);
+
+        // Parse the command line arguments for the configuration file to use.
+        final String[] args = context.getArguments();
+        final DaemonParameters params = new DaemonParameters();
+        try {
+            new JCommander(params).parse(args);
+        } catch(final ParameterException e) {
+            throw new DaemonInitException("Unable to parse the command line arguments.", e);
+        }
+        final Path configFile = params.config != null ? Paths.get(params.config) : DEFAULT_CONFIGURATION_PATH;
+        log.info("Loading the following configuration file: " + configFile);
+
+        // Unmarshall the configuration file into an object.
+        final QueryManagerConfig config;
+        try(InputStream stream = Files.newInputStream(configFile)) {
+            config = QueryManagerConfigUnmarshaller.unmarshall(stream);
+        } catch(final JAXBException | SAXException e) {
+            throw new DaemonInitException("Unable to marshall the configuration XML file: " + configFile, e);
+        }
+
+        // Read the source polling period from the configuration.
+        final QueryChanngeLogDiscoveryPeriod periodConfig = config.getPerformanceTunning().getQueryChanngeLogDiscoveryPeriod();
+        final long period = periodConfig.getValue().longValue();
+        final TimeUnit units = TimeUnit.valueOf( periodConfig.getUnits().toString() );
+        log.info("Query Change Log Polling Period: " + period + " " + units);
+        final Scheduler scheduler = Scheduler.newFixedRateSchedule(0, period, units);
+
+        // Initialize a QueryChangeLogSource.
+        final Kafka kafka = config.getQueryChangeLogSource().getKafka();
+        log.info("Kafka Source: " + kafka.getHostname() + ":" + kafka.getPort());
+        final QueryChangeLogSource source = new KafkaQueryChangeLogSource(kafka.getHostname(), kafka.getPort(), scheduler);
+
+        // Initialize a QueryExecutor.
+        final KafkaStreamsFactory streamsFactory = new SingleThreadKafkaStreamsFactory(kafka.getHostname() + ":" + kafka.getPort());
+        final QueryExecutor queryExecutor = new LocalQueryExecutor(streamsFactory);
+
+        // Initialize the QueryManager using the configured resources.
+        manager = new QueryManager(queryExecutor, source, scheduler);
     }
 
     @Override
     public void start() throws Exception {
-        System.out.println("Starting Query Manager Daemon.");
+        log.info("Starting the Rya Streams Query Manager Daemon.");
+        manager.startAndWait();
     }
 
     @Override
     public void stop() throws Exception {
-        System.out.println("Stopping Query Manager Daemon.");
+        log.info("Stopping the Rya Streams Query Manager Daemon.");
+        manager.stopAndWait();
     }
 
     @Override
-    public void destroy() {
-        System.out.println("Query Manager Daemon Destroyed.");
-    }
+    public void destroy() { }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/16202ac7/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java
index 834f0b9..39de24d 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigUnmarshaller.java
@@ -20,7 +20,7 @@ package org.apache.rya.streams.querymanager.xml;
 
 import static java.util.Objects.requireNonNull;
 
-import java.io.Reader;
+import java.io.InputStream;
 import java.net.URL;
 
 import javax.xml.XMLConstants;
@@ -49,13 +49,13 @@ public class QueryManagerConfigUnmarshaller {
     /**
      * Validates and unmarshalls XML into a {@link QueryManagerConfig} object.
      *
-     * @param xmlReader - Reads the XML that will be unmarshalled. (not null)
+     * @param xmlStream - Reads the XML that will be unmarshalled. (not null)
      * @return A {@link QueryManagerConfig} loaded with the XMLs values.
      * @throws SAXException Could not load the schema the XML will be validated against.
      * @throws JAXBException Could not unmarshal the XML into a POJO.
      */
-    public static QueryManagerConfig unmarshall(final Reader xmlReader) throws JAXBException, SAXException {
-        requireNonNull(xmlReader);
+    public static QueryManagerConfig unmarshall(final InputStream xmlStream) throws JAXBException, SAXException {
+        requireNonNull(xmlStream);
 
         // Get an input stream to the XSD file that is packaged inside of the jar.
         final URL schemaURL = ClassLoader.getSystemResource(XSD_PATH);
@@ -73,6 +73,6 @@ public class QueryManagerConfigUnmarshaller {
         unmarshaller.setSchema(schema);
 
         // Perform the unmarshal.
-        return (QueryManagerConfig) unmarshaller.unmarshal(xmlReader);
+        return (QueryManagerConfig) unmarshaller.unmarshal(xmlStream);
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/16202ac7/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
index 831c06b..f2b50ab 100644
--- a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/xml/QueryManagerConfigMarshallerTest.java
@@ -20,12 +20,15 @@ package org.apache.rya.streams.querymanager.xml;
 
 import static org.junit.Assert.assertNotNull;
 
-import java.io.StringReader;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
 
 import javax.xml.bind.UnmarshalException;
 
 import org.junit.Test;
 
+import com.google.common.base.Charsets;
+
 /**
  * Unit tests the methods of {@link QueryManagerConfigUnmarshaller}.
  */
@@ -50,8 +53,8 @@ public class QueryManagerConfigMarshallerTest {
                 "    </performanceTunning>\n" +
                 "</queryManagerConfig>";
 
-
-        final QueryManagerConfig config = QueryManagerConfigUnmarshaller.unmarshall(new StringReader(xml));
+        final InputStream xmlStream = new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8));
+        final QueryManagerConfig config = QueryManagerConfigUnmarshaller.unmarshall(xmlStream);
         assertNotNull(config);
     }
 
@@ -68,7 +71,7 @@ public class QueryManagerConfigMarshallerTest {
                 "    </queryChangeLogSource>\n" +
                 "</queryManagerConfig>";
 
-
-        QueryManagerConfigUnmarshaller.unmarshall(new StringReader(xml));
+        final InputStream xmlStream = new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8));
+        QueryManagerConfigUnmarshaller.unmarshall(xmlStream);
     }
 }
\ No newline at end of file


[03/22] incubator-rya git commit: Rya 454 added QueryExecutor interface

Posted by pu...@apache.org.
Rya 454 added QueryExecutor interface


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/eb07bf6e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/eb07bf6e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/eb07bf6e

Branch: refs/heads/master
Commit: eb07bf6eaaa822a2d4ebff3bd098ae6711f24efc
Parents: d6d6d04
Author: Andrew Smith <sm...@gmail.com>
Authored: Fri Jan 19 15:43:55 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:35 2018 -0500

----------------------------------------------------------------------
 .../rya/streams/querymanager/QueryExecutor.java | 95 ++++++++++++++++++++
 1 file changed, 95 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/eb07bf6e/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
new file mode 100644
index 0000000..e888879
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager;
+
+import java.util.Set;
+import java.util.UUID;
+
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.openrdf.model.Statement;
+
+import com.google.common.util.concurrent.Service;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * Represents the system that is responsible for ensuring active {@link StreamsQuery}s are
+ * being processed.
+ */
+@DefaultAnnotation(NonNull.class)
+public interface QueryExecutor extends Service {
+    /**
+     * Starts running a {@link StreamsQuery}.
+     *
+     * @param ryaInstanceName - The rya instance whose {@link Statement}s will be processed by the query. (not null)
+     * @param query - The query to run. (not null)
+     * @throws QueryExecutorException When the query fails to start.
+     */
+    public void startQuery(final String ryaInstanceName, final StreamsQuery query) throws QueryExecutorException;
+
+    /**
+     * Stops a {@link StreamsQuery}.
+     *
+     * @param queryID - The ID of the query to stop. (not null)
+     * @throws QueryExecutorException When the query fails to stop.
+     */
+    public void stopQuery(final UUID queryID) throws QueryExecutorException;
+
+    /**
+     * @return - A set of {@link UUID}s representing the current active queries.
+     * @throws QueryExecutorException Can't discover which queries are currently running.
+     */
+    public Set<UUID> getRunningQueryIds() throws QueryExecutorException;
+
+    /**
+     * Exception to be used by {@link QueryExecutor} when queries fail to start or stop.
+     */
+    public class QueryExecutorException extends Exception {
+        private static final long serialVersionUID = 1L;
+
+        /**
+         * Creates a new {@link QueryExecutorException}.
+         *
+         * @param message - The exception message.
+         * @param cause - The cause of this exception.
+         */
+        public QueryExecutorException(final String message, final Throwable cause) {
+            super(message, cause);
+        }
+
+        /**
+         * Creates a new {@link QueryExecutorException}.
+         *
+         * @param message - The exception message.
+         */
+        public QueryExecutorException(final String message) {
+            super(message);
+        }
+
+        /**
+         * Creates a new {@link QueryExecutorException}.
+         *
+         * @param cause - The cause of this exception.
+         */
+        public QueryExecutorException(final Throwable cause) {
+            super(cause);
+        }
+    }
+}


[05/22] incubator-rya git commit: RYA-455 stopAll queries for a rya instance

Posted by pu...@apache.org.
RYA-455 stopAll queries for a rya instance



Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/9e8a27c2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/9e8a27c2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/9e8a27c2

Branch: refs/heads/master
Commit: 9e8a27c2d73fc6a1fe517f95b21393d85431b1ac
Parents: 36af115
Author: Andrew Smith <sm...@gmail.com>
Authored: Tue Jan 23 15:44:32 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:39 2018 -0500

----------------------------------------------------------------------
 .../org/apache/rya/streams/querymanager/QueryExecutor.java   | 8 ++++++++
 1 file changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/9e8a27c2/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
index e888879..4572f08 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
@@ -53,6 +53,14 @@ public interface QueryExecutor extends Service {
     public void stopQuery(final UUID queryID) throws QueryExecutorException;
 
     /**
+     * Stops all {@link StreamsQuery} belonging to a specific rya instance.
+     *
+     * @param ryaInstanceName - The name of the rya instance to stop all queries for. (not null)
+     * @throws QueryExecutorException When the queries fails to stop.
+     */
+    public void stopAll(final String ryaInstanceName) throws QueryExecutorException;
+
+    /**
      * @return - A set of {@link UUID}s representing the current active queries.
      * @throws QueryExecutorException Can't discover which queries are currently running.
      */


[14/22] incubator-rya git commit: RYA-446 Making the Rya Streams Query Manager run as a service on CentOS 7.

Posted by pu...@apache.org.
RYA-446 Making the Rya Streams Query Manager run as a service on CentOS 7.


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/a342fe2a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/a342fe2a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/a342fe2a

Branch: refs/heads/master
Commit: a342fe2a88ab8ff64c2a7fc989a96ffbf793ee18
Parents: 4076804
Author: kchilton2 <ke...@gmail.com>
Authored: Thu Feb 1 18:31:41 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:53 2018 -0500

----------------------------------------------------------------------
 .../kafka/KafkaRyaStreamsClientFactory.java     |  9 +++-
 extras/rya.streams/query-manager/pom.xml        | 48 ++++++--------------
 .../src/assembly/binary-release.xml             | 30 ------------
 .../query-manager/src/main/README.txt           |  4 +-
 .../src/main/config/configuration.xml           |  2 +-
 .../src/main/scripts/rpm/postinstall.sh         | 21 +++++++++
 .../src/main/scripts/rpm/preremove.sh           | 21 +++++++++
 .../main/scripts/rya-streams-query-manager.sh   |  7 +--
 .../systemd/rya-streams-query-manager.service   | 11 +++--
 9 files changed, 77 insertions(+), 76 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaRyaStreamsClientFactory.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaRyaStreamsClientFactory.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaRyaStreamsClientFactory.java
index 9250d9d..0bf13d1 100644
--- a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaRyaStreamsClientFactory.java
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaRyaStreamsClientFactory.java
@@ -22,6 +22,7 @@ import static java.util.Objects.requireNonNull;
 
 import java.util.Properties;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.kafka.clients.CommonClientConfigs;
 import org.apache.kafka.clients.consumer.Consumer;
@@ -54,6 +55,8 @@ import org.apache.rya.streams.kafka.serialization.queries.QueryChangeSerializer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
 
@@ -64,6 +67,8 @@ import edu.umd.cs.findbugs.annotations.NonNull;
 public final class KafkaRyaStreamsClientFactory {
     private static final Logger log = LoggerFactory.getLogger(KafkaRyaStreamsClientFactory.class);
 
+    private static final Scheduler SCHEDULER = Scheduler.newFixedDelaySchedule(0, 5, TimeUnit.SECONDS);
+
     /**
      * Initialize a {@link RyaStreamsClient} that will interact with an instance of Rya Streams
      * that is backed by Kafka.
@@ -87,7 +92,7 @@ public final class KafkaRyaStreamsClientFactory {
                 fromStartConsumer(kafkaHostname, kafkaPort, StringDeserializer.class, QueryChangeDeserializer.class);
         final String changeLogTopic = KafkaTopics.queryChangeLogTopic(ryaInstance);
         final QueryChangeLog changeLog = new KafkaQueryChangeLog(queryProducer, queryConsumer, changeLogTopic);
-        final QueryRepository queryRepo = new InMemoryQueryRepository(changeLog);
+        final QueryRepository queryRepo = new InMemoryQueryRepository(changeLog, SCHEDULER);
 
         // Create the Rya Streams client that is backed by a Kafka Query Change Log.
         return new RyaStreamsClient(
@@ -106,7 +111,7 @@ public final class KafkaRyaStreamsClientFactory {
             @Override
             public void close() {
                 try {
-                    queryRepo.close();
+                    queryRepo.stopAndWait();
                 } catch (final Exception e) {
                     log.warn("Couldn't close a QueryRepository.", e);
                 }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
index e459814..d2ccbf5 100644
--- a/extras/rya.streams/query-manager/pom.xml
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -155,21 +155,6 @@ under the License.
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-assembly-plugin</artifactId>
                 <executions>
-                    <!-- The binary distribution of Rya Streams Query Manager. -->
-                    <execution>
-                        <id>create-binary-distribution</id>
-                        <goals>
-                            <goal>single</goal>
-                        </goals>
-                        <phase>package</phase>
-                        <configuration>
-                            <tarLongFileMode>gnu</tarLongFileMode>
-                            <descriptors>
-                                <descriptor>src/assembly/binary-release.xml</descriptor>
-                            </descriptors>
-                        </configuration>
-                    </execution>
-                    
                     <!-- Stage the files for the RPM construction. -->
                     <execution>
                         <id>stage-content-for-rpms</id>
@@ -213,6 +198,16 @@ under the License.
                             <defaultDirmode>755</defaultDirmode>
                             <defaultFilemode>644</defaultFilemode>
                             
+                            <!-- (Un)Install scripts that enable/disable the daemon.-->
+                            <postinstallScriptlet>
+                                <scriptFile>${rpm.staging.path}/bin/rpm/postinstall.sh</scriptFile>
+                                <fileEncoding>utf-8</fileEncoding>
+                            </postinstallScriptlet>
+                            <preremoveScriptlet>
+                                <scriptFile>${rpm.staging.path}/bin/rpm/preremove.sh</scriptFile>
+                                <fileEncoding>utf-8</fileEncoding>
+                            </preremoveScriptlet>
+                            
                             <!-- This project requires the Apache Commons Daemon applications. -->
                             <requires>
                                 <require>jsvc</require>
@@ -226,16 +221,14 @@ under the License.
                                         <!-- Copy over everything exception for the executable script. -->
                                         <source>
                                             <location>${rpm.staging.path}</location>
-                                            <includes>
-                                                <include>bin/systemd/rya-streams-query-manager.service</include>
-                                                <include>config/*</include>
-                                                <include>lib/*</include>
-                                                <include>README.txt</include>
-                                            </includes>
+                                            <excludes>
+                                                <exclude>bin/rpm/**</exclude>
+                                                <exclude>bin/rya-streams-query-manager.sh</exclude>
+                                            </excludes>
                                         </source>
                                     </sources>
                                 </mapping>
-                                
+
                                 <!-- Copy over the scripts with the correct execution permissions. -->
                                 <mapping>
                                     <directory>/opt/rya-streams-query-manager-${rpm.version}/bin</directory>
@@ -250,17 +243,6 @@ under the License.
                                         </source>
                                     </sources>
                                 </mapping>
-                                
-                                <!-- Symbolic link the service file after it has been copied over. -->
-                                <mapping>
-                                    <directory>/etc/systemd/system/</directory>
-                                    <sources>
-                                        <softlinkSource>
-                                            <location>/opt/rya-streams-query-manager-${rpm.version}/bin/systemd/rya-streams-query-manager.service</location>
-                                            <destination>rya-streams-query-manager.service</destination>
-                                        </softlinkSource>
-                                    </sources>
-                                </mapping>
                             </mappings>
                         </configuration>
                     </execution>

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/src/assembly/binary-release.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/assembly/binary-release.xml b/extras/rya.streams/query-manager/src/assembly/binary-release.xml
deleted file mode 100644
index 07e2de0..0000000
--- a/extras/rya.streams/query-manager/src/assembly/binary-release.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements.  See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership.  The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License.  You may obtain a copy of the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied.  See the License for the
-specific language governing permissions and limitations
-under the License.
--->
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" 
-          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
-    <id>bin</id>
-    <formats>
-        <format>tar.gz</format>
-    </formats>
-    <componentDescriptors>
-        <componentDescriptor>src/assembly/component-release.xml</componentDescriptor>
-    </componentDescriptors>
-</assembly>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/src/main/README.txt
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/README.txt b/extras/rya.streams/query-manager/src/main/README.txt
index 03f9c01..3b2dbfe 100644
--- a/extras/rya.streams/query-manager/src/main/README.txt
+++ b/extras/rya.streams/query-manager/src/main/README.txt
@@ -42,10 +42,10 @@ Java 8
     
  3. Update the configuration file:
     Replace "[Kafka Broker Hostname]" with the IP address of the Kafka broker.
-    Replace "[Kafka Broker Port]" with the port of the Kafka broker (usually 9092)
+    Replace the Kafka port if using something other than the default of 9092.
     
  4. Start the service:
-    systemctl start rya-streams-query-manager
+    systemctl start rya-streams-query-manager.service
     
 ### Uninstallation ###
  1. Get the name of the RPM you want to uninstall:

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/src/main/config/configuration.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/config/configuration.xml b/extras/rya.streams/query-manager/src/main/config/configuration.xml
index a5e3fb6..96da501 100644
--- a/extras/rya.streams/query-manager/src/main/config/configuration.xml
+++ b/extras/rya.streams/query-manager/src/main/config/configuration.xml
@@ -26,7 +26,7 @@ under the License.
     <queryChangeLogSource>
         <kafka>
             <hostname>[Kafka Broker Hostname]</hostname>
-            <port>[Kafka Broker Port]</port>
+            <port>9092</port>
         </kafka>
     </queryChangeLogSource>
     

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/src/main/scripts/rpm/postinstall.sh
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/scripts/rpm/postinstall.sh b/extras/rya.streams/query-manager/src/main/scripts/rpm/postinstall.sh
new file mode 100644
index 0000000..83dbb9e
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/scripts/rpm/postinstall.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+systemctl enable /opt/rya-streams-query-manager-${rpm.version}/bin/systemd/rya-streams-query-manager.service
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/src/main/scripts/rpm/preremove.sh
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/scripts/rpm/preremove.sh b/extras/rya.streams/query-manager/src/main/scripts/rpm/preremove.sh
new file mode 100644
index 0000000..20a0169
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/scripts/rpm/preremove.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+systemctl disable rya-streams-query-manager.service 
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh b/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh
index daa1ae5..ddf61e6 100644
--- a/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh
+++ b/extras/rya.streams/query-manager/src/main/scripts/rya-streams-query-manager.sh
@@ -28,7 +28,7 @@ EXEC="/usr/bin/jsvc"
 PROJECT_HOME=$(dirname $(cd $(dirname $0) && pwd))
 
 # This classpath must contain the commons-daemon jar as well as the jar we're executing.
-CLASS_PATH="$PROJECT_HOME/lib/commons-daemon-1.1.0.jar:$PROJECT_HOME/lib/${project.artifactId}-${project.version}-shaded.jar:$PROJECT_HOME/config/log4j.xml"
+CLASS_PATH="$PROJECT_HOME/lib/commons-daemon-1.1.0.jar:$PROJECT_HOME/lib/${project.artifactId}-${project.version}-shaded.jar"
 
 # The fully qualified name of the class to execute. This class must implement the Daemon interface.
 DAEMON_CLASS=org.apache.rya.streams.querymanager.QueryManagerDaemon
@@ -50,8 +50,9 @@ start ()
         exit 1
     else
         echo "Starting the $DESC."
-        $EXEC -cp $CLASS_PATH -user root -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $1 $DAEMON_CLASS \
-            -c "$PROJECT_HOME/config/configuration.xml"
+        $EXEC -cp $CLASS_PATH -user root -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID \
+              -Dlog4j.configuration="file://$PROJECT_HOME/config/log4j.xml" \
+              $DAEMON_CLASS -c "$PROJECT_HOME/config/configuration.xml"
     fi
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a342fe2a/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service b/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
index 5ff40b6..0709879 100644
--- a/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
+++ b/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
@@ -18,14 +18,15 @@
 #
 [Unit]
 Description=Rya Streams Query Manager Service
+After=network.target
 
 [Service]
+Type=forking
 PIDFile=/var/run/rya-streams-query-manager.pid
-ExecStart=/opt/rya-streams-query-manager/rya-query-manager.sh start
-ExecStop=/opt/rya-streams-query-manager/rya-query-manager.sh stop
-ExecReload=/opt/rya-streams-query-manager/rya-query-manager.sh restart
-Type=oneshot
+ExecStart=/opt/rya-streams-query-manager-${rpm.version}/bin/rya-streams-query-manager.sh start
+ExecStop=/opt/rya-streams-query-manager-${rpm.version}/bin/rya-streams-query-manager.sh stop
+ExecReload=/opt/rya-streams-query-manager-${rpm.version}/bin/rya-streams-query-manager.sh restart
 Restart=always
 
 [Install]
-Alias=rya-streams-query-manager
\ No newline at end of file
+WantedBy=multi-user.target
\ No newline at end of file


[13/22] incubator-rya git commit: RYA-446 Service unit file for systemd

Posted by pu...@apache.org.
RYA-446 Service unit file for systemd


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/40768044
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/40768044
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/40768044

Branch: refs/heads/master
Commit: 407680445d8546ade982c5ed4d5f94cf48864521
Parents: 3b05a0b
Author: Andrew Smith <sm...@gmail.com>
Authored: Thu Feb 1 16:04:48 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:51 2018 -0500

----------------------------------------------------------------------
 .../systemd/rya-streams-query-manager.service       | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/40768044/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service b/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
index 0ec41c5..5ff40b6 100644
--- a/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
+++ b/extras/rya.streams/query-manager/src/main/scripts/systemd/rya-streams-query-manager.service
@@ -16,14 +16,16 @@
 # specific language governing permissions and limitations
 # under the License.
 #
-
-TODO This will be the service file installed to CentOS 7 for systemd integration.
-
-[Units]
-TODO
+[Unit]
+Description=Rya Streams Query Manager Service
 
 [Service]
-TODO
+PIDFile=/var/run/rya-streams-query-manager.pid
+ExecStart=/opt/rya-streams-query-manager/rya-query-manager.sh start
+ExecStop=/opt/rya-streams-query-manager/rya-query-manager.sh stop
+ExecReload=/opt/rya-streams-query-manager/rya-query-manager.sh restart
+Type=oneshot
+Restart=always
 
 [Install]
-TODO
\ No newline at end of file
+Alias=rya-streams-query-manager
\ No newline at end of file


[04/22] incubator-rya git commit: Rya 452 Updated QueryRepository

Posted by pu...@apache.org.
Rya 452 Updated QueryRepository

Updated QueryRepository to be a Service
Updated InMemoryQueryRepository to be an AbstractScheduledService
Added listeners to InMemoryQueryRepository

Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/36af1153
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/36af1153
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/36af1153

Branch: refs/heads/master
Commit: 36af1153758c943e08808b720adece86278de41f
Parents: eb07bf6
Author: Andrew Smith <sm...@gmail.com>
Authored: Tue Jan 23 15:20:50 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:37 2018 -0500

----------------------------------------------------------------------
 .../api/queries/InMemoryQueryRepository.java    |  90 ++++++++-
 .../api/queries/QueryChangeLogListener.java     |  41 ++++
 .../streams/api/queries/QueryRepository.java    |  38 +++-
 .../queries/InMemoryQueryRepositoryTest.java    | 194 ++++++++++++++-----
 .../streams/client/command/AddQueryCommand.java |   8 +-
 .../client/command/DeleteQueryCommand.java      |   7 +-
 .../client/command/ListQueriesCommand.java      |   7 +-
 .../streams/client/command/RunQueryCommand.java |   9 +-
 .../client/command/StreamResultsCommand.java    |   7 +-
 .../client/command/AddQueryCommandIT.java       |  11 +-
 .../client/command/DeleteQueryCommandIT.java    |  11 +-
 .../client/command/ListQueryCommandIT.java      |  11 +-
 .../client/command/RunQueryCommandIT.java       |   5 +-
 .../kafka/interactor/KafkaRunQueryIT.java       |   4 +-
 14 files changed, 349 insertions(+), 94 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
index f4b7b25..dca040f 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/InMemoryQueryRepository.java
@@ -20,7 +20,9 @@ package org.apache.rya.streams.api.queries;
 
 import static java.util.Objects.requireNonNull;
 
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
@@ -33,6 +35,8 @@ import org.apache.rya.streams.api.queries.QueryChangeLog.QueryChangeLogException
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.util.concurrent.AbstractScheduledService;
+
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
 import info.aduna.iteration.CloseableIteration;
@@ -46,7 +50,7 @@ import info.aduna.iteration.CloseableIteration;
  * Thread safe.
  */
 @DefaultAnnotation(NonNull.class)
-public class InMemoryQueryRepository implements QueryRepository {
+public class InMemoryQueryRepository extends AbstractScheduledService implements QueryRepository {
     private static final Logger LOG = LoggerFactory.getLogger(InMemoryQueryRepository.class);
 
     private final ReentrantLock lock = new ReentrantLock();
@@ -67,20 +71,34 @@ public class InMemoryQueryRepository implements QueryRepository {
     private final Map<UUID, StreamsQuery> queriesCache = new HashMap<>();
 
     /**
+     * The listeners to be notified when new QueryChangeLogs come in.
+     */
+    private final List<QueryChangeLogListener> listeners = new ArrayList<>();
+
+    /**
+     * The {@link Scheduler} the repository uses to periodically poll for query updates.
+     */
+    private final Scheduler scheduler;
+
+    /**
      * Constructs an instance of {@link InMemoryQueryRepository}.
      *
      * @param changeLog - The change log that this repository will maintain and be based on. (not null)
+     * @param scheduler - The {@link Scheduler} this service uses to periodically check for query updates. (not null)
      */
-    public InMemoryQueryRepository(final QueryChangeLog changeLog) {
+    public InMemoryQueryRepository(final QueryChangeLog changeLog, final Scheduler scheduler) {
         this.changeLog = requireNonNull(changeLog);
+        this.scheduler = requireNonNull(scheduler);
     }
 
     @Override
-    public StreamsQuery add(final String query, final boolean isActive) throws QueryRepositoryException {
+    public StreamsQuery add(final String query, final boolean isActive)
+            throws QueryRepositoryException, IllegalStateException {
         requireNonNull(query);
 
         lock.lock();
         try {
+            checkState();
             // First record the change to the log.
             final UUID queryId = UUID.randomUUID();
             final QueryChange change = QueryChange.create(queryId, query, isActive);
@@ -100,11 +118,12 @@ public class InMemoryQueryRepository implements QueryRepository {
     }
 
     @Override
-    public Optional<StreamsQuery> get(final UUID queryId) throws QueryRepositoryException {
+    public Optional<StreamsQuery> get(final UUID queryId) throws QueryRepositoryException, IllegalStateException {
         requireNonNull(queryId);
 
         lock.lock();
         try {
+            checkState();
             // Update the cache to represent what is currently in the log.
             updateCache();
 
@@ -115,11 +134,13 @@ public class InMemoryQueryRepository implements QueryRepository {
     }
 
     @Override
-    public void updateIsActive(final UUID queryId, final boolean isActive) throws QueryRepositoryException {
+    public void updateIsActive(final UUID queryId, final boolean isActive)
+            throws QueryRepositoryException, IllegalStateException {
         requireNonNull(queryId);
 
         lock.lock();
         try {
+            checkState();
             // Update the cache to represent what is currently in the log.
             updateCache();
 
@@ -140,11 +161,12 @@ public class InMemoryQueryRepository implements QueryRepository {
     }
 
     @Override
-    public void delete(final UUID queryId) throws QueryRepositoryException {
+    public void delete(final UUID queryId) throws QueryRepositoryException, IllegalStateException {
         requireNonNull(queryId);
 
         lock.lock();
         try {
+            checkState();
             // First record the change to the log.
             final QueryChange change = QueryChange.delete(queryId);
             changeLog.write(change);
@@ -157,9 +179,10 @@ public class InMemoryQueryRepository implements QueryRepository {
     }
 
     @Override
-    public Set<StreamsQuery> list() throws QueryRepositoryException {
+    public Set<StreamsQuery> list() throws QueryRepositoryException, IllegalStateException {
         lock.lock();
         try {
+            checkState();
             // Update the cache to represent what is currently in the log.
             updateCache();
 
@@ -174,7 +197,8 @@ public class InMemoryQueryRepository implements QueryRepository {
     }
 
     @Override
-    public void close() throws Exception {
+    protected void shutDown() throws Exception {
+        super.shutDown();
         lock.lock();
         try {
             changeLog.close();
@@ -229,6 +253,8 @@ public class InMemoryQueryRepository implements QueryRepository {
                         break;
                 }
 
+                listeners.forEach(listener -> listener.notify(entry));
+
                 cachePosition = Optional.of( entry.getPosition() );
             }
 
@@ -247,4 +273,52 @@ public class InMemoryQueryRepository implements QueryRepository {
             }
         }
     }
+
+    @Override
+    protected void runOneIteration() throws Exception {
+        lock.lock();
+        try {
+            updateCache();
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    protected Scheduler scheduler() {
+        return scheduler;
+    }
+
+    @Override
+    public Set<StreamsQuery> subscribe(final QueryChangeLogListener listener) {
+        //locks to prevent the current state from changing while subscribing.
+        lock.lock();
+        try {
+            listeners.add(listener);
+
+            //return the current state of the query repository
+            return queriesCache.values()
+                    .stream()
+                    .collect(Collectors.toSet());
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    public void unsubscribe(final QueryChangeLogListener listener) {
+        lock.lock();
+        try {
+            listeners.remove(listener);
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    private void checkState() {
+        if (!super.isRunning() && !listeners.isEmpty()) {
+            throw new IllegalStateException(
+                    "The Query Repository is subscribed to, but the service has not been started.");
+        }
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java
new file mode 100644
index 0000000..2b61227
--- /dev/null
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryChangeLogListener.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.api.queries;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * Listener to be notified when {@link QueryChange}s occur on a {@link QueryChangeLog}.
+ */
+@DefaultAnnotation(NonNull.class)
+public interface QueryChangeLogListener {
+    /**
+     * Notifies the listener that a query change event has occurred in the change log.
+     * <p>
+     * <b>Note:</b>
+     * <p>
+     * The QueryRepository blocks when notifying this listener.  Long lasting operations
+     * should not be performed within this function.  Doing so will block all operations
+     * on the repository.
+     *
+     * @param queryChangeEvent - The event that occurred. (not null)
+     */
+    public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent);
+}

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
index fd51b2f..4d8b2db 100644
--- a/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
+++ b/extras/rya.streams/api/src/main/java/org/apache/rya/streams/api/queries/QueryRepository.java
@@ -25,14 +25,20 @@ import java.util.UUID;
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.exception.RyaStreamsException;
 
+import com.google.common.util.concurrent.Service;
+
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
 
 /**
  * Repository for adding, deleting, and listing active queries in Rya Streams.
+ *
+ * This service only needs to be started if it is being subscribed to. An
+ * {@link IllegalStateException} will be thrown if the service is subscribed to
+ * and used without being started.
  */
 @DefaultAnnotation(NonNull.class)
-public interface QueryRepository extends AutoCloseable {
+public interface QueryRepository extends Service {
 
     /**
      * Adds a new query to Rya Streams.
@@ -42,8 +48,9 @@ public interface QueryRepository extends AutoCloseable {
      *   otherwise {@code false}.
      * @return The {@link StreamsQuery} used in Rya Streams.
      * @throws QueryRepositoryException Could not add the query.
+     * @throws IllegalStateException The Service has not been started, but has been subscribed to.
      */
-    public StreamsQuery add(final String query, boolean isActive) throws QueryRepositoryException;
+    public StreamsQuery add(final String query, boolean isActive) throws QueryRepositoryException, IllegalStateException;
 
     /**
      * Updates the isActive state of a {@link StreamsQuery}. Setting this value to {@code true}
@@ -53,8 +60,9 @@ public interface QueryRepository extends AutoCloseable {
      * @param queryId - Identifies which query will be updated. (not null)
      * @param isActive - The new isActive state for the query.
      * @throws QueryRepositoryException If the query does not exist or something else caused the change to fail.
+     * @throws IllegalStateException The Service has not been started, but has been subscribed to.
      */
-    public void updateIsActive(UUID queryId, boolean isActive) throws QueryRepositoryException;
+    public void updateIsActive(UUID queryId, boolean isActive) throws QueryRepositoryException, IllegalStateException;
 
     /**
      * Get an existing query from Rya Streams.
@@ -62,24 +70,42 @@ public interface QueryRepository extends AutoCloseable {
      * @param queryId - Identifies which query will be fetched.
      * @return the {@link StreamsQuery} for the id if one exists; otherwise empty.
      * @throws QueryRepositoryException The query could not be fetched.
+     * @throws IllegalStateException The Service has not been started, but has been subscribed to.
      */
-    public Optional<StreamsQuery> get(UUID queryId) throws QueryRepositoryException;
+    public Optional<StreamsQuery> get(UUID queryId) throws QueryRepositoryException, IllegalStateException;
 
     /**
      * Removes an existing query from Rya Streams.
      *
      * @param queryID - The {@link UUID} of the query to remove. (not null)
      * @throws QueryRepositoryException Could not delete the query.
+     * @throws IllegalStateException The Service has not been started, but has been subscribed to.
      */
-    public void delete(UUID queryID) throws QueryRepositoryException;
+    public void delete(UUID queryID) throws QueryRepositoryException, IllegalStateException;
 
     /**
      * Lists all existing queries in Rya Streams.
      *
      * @return - A List of the current {@link StreamsQuery}s
      * @throws QueryRepositoryException The {@link StreamsQuery}s could not be listed.
+     * @throws IllegalStateException The Service has not been started, but has been subscribed to.
+     */
+    public Set<StreamsQuery> list() throws QueryRepositoryException, IllegalStateException;
+
+    /**
+     * Subscribes a {@link QueryChangeLogListener} to the {@link QueryRepository}.
+     *
+     * @param listener - The {@link QueryChangeLogListener} to subscribe to this {@link QueryRepository}. (not null)
+     * @return The current state of the repository in the form of {@link StreamsQuery}s.
+     */
+    public Set<StreamsQuery> subscribe(final QueryChangeLogListener listener);
+
+    /**
+     * Unsubscribe a {@link QueryChangeLogListener} from the {@link QueryRepository}.
+     *
+     * @param listener - The {@link QueryChangeLogListener} to unsubscribe from this {@link QueryRepository}. (not null)
      */
-    public Set<StreamsQuery> list() throws QueryRepositoryException;
+    public void unsubscribe(final QueryChangeLogListener listener);
 
     /**
      * A function of {@link QueryRepository} was unable to perform a function.

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
index 22e616d..76c3216 100644
--- a/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
+++ b/extras/rya.streams/api/src/test/java/org/apache/rya/streams/api/queries/InMemoryQueryRepositoryTest.java
@@ -20,6 +20,7 @@ package org.apache.rya.streams.api.queries;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -27,56 +28,62 @@ import java.util.HashSet;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.queries.QueryChangeLog.QueryChangeLogException;
 import org.junit.Test;
 
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
 /**
  * Unit tests the methods of {@link InMemoryQueryRepository}.
  */
 public class InMemoryQueryRepositoryTest {
+    private static final Scheduler SCHEDULE = Scheduler.newFixedRateSchedule(0L, 100, TimeUnit.MILLISECONDS);
 
     @Test
     public void canReadAddedQueries() throws Exception {
         // Setup a totally in memory QueryRepository.
-        try(final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog() )) {
-            // Add some queries to it.
-            final Set<StreamsQuery> expected = new HashSet<>();
-            expected.add( queries.add("query 1", true) );
-            expected.add( queries.add("query 2", false) );
-            expected.add( queries.add("query 3", true) );
-
-            // Show they are in the list of all queries.
-            final Set<StreamsQuery> stored = queries.list();
-            assertEquals(expected, stored);
-        }
+        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
+        // Add some queries to it.
+        final Set<StreamsQuery> expected = new HashSet<>();
+        expected.add( queries.add("query 1", true) );
+        expected.add( queries.add("query 2", false) );
+        expected.add( queries.add("query 3", true) );
+
+        // Show they are in the list of all queries.
+        final Set<StreamsQuery> stored = queries.list();
+        assertEquals(expected, stored);
     }
 
     @Test
     public void deletedQueriesDisappear() throws Exception {
         // Setup a totally in memory QueryRepository.
-        try(final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog() )) {
-            // Add some queries to it. The second one we will delete.
-            final Set<StreamsQuery> expected = new HashSet<>();
-            expected.add( queries.add("query 1", true) );
-            final UUID deletedMeId = queries.add("query 2", false).getQueryId();
-            expected.add( queries.add("query 3", true) );
-
-            // Delete the second query.
-            queries.delete( deletedMeId );
-
-            // Show only queries 1 and 3 are in the list.
-            final Set<StreamsQuery> stored = queries.list();
-            assertEquals(expected, stored);
-        }
+        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
+        // Add some queries to it. The second one we will delete.
+        final Set<StreamsQuery> expected = new HashSet<>();
+        expected.add( queries.add("query 1", true) );
+        final UUID deletedMeId = queries.add("query 2", false).getQueryId();
+        expected.add( queries.add("query 3", true) );
+
+        // Delete the second query.
+        queries.delete( deletedMeId );
+
+        // Show only queries 1 and 3 are in the list.
+        final Set<StreamsQuery> stored = queries.list();
+        assertEquals(expected, stored);
     }
 
     @Test
     public void initializedWithPopulatedChangeLog() throws Exception {
         // Setup a totally in memory QueryRepository. Hold onto the change log so that we can use it again later.
         final QueryChangeLog changeLog = new InMemoryQueryChangeLog();
-        try(final QueryRepository queries = new InMemoryQueryRepository( changeLog )) {
+        final QueryRepository queries = new InMemoryQueryRepository( changeLog, SCHEDULE );
+        try {
+            queries.startAndWait();
             // Add some queries and deletes to it.
             final Set<StreamsQuery> expected = new HashSet<>();
             expected.add( queries.add("query 1", true) );
@@ -85,11 +92,16 @@ public class InMemoryQueryRepositoryTest {
             queries.delete( deletedMeId );
 
             // Create a new totally in memory QueryRepository.
-            try(final QueryRepository initializedQueries = new InMemoryQueryRepository( changeLog )) {
+            final QueryRepository initializedQueries = new InMemoryQueryRepository( changeLog, SCHEDULE );
+            try {
                 // Listing the queries should work using an initialized change log.
                 final Set<StreamsQuery> stored = initializedQueries.list();
                 assertEquals(expected, stored);
+            } finally {
+                queries.stop();
             }
+        } finally {
+            queries.stop();
         }
     }
 
@@ -100,50 +112,132 @@ public class InMemoryQueryRepositoryTest {
         when(changeLog.readFromStart()).thenThrow(new QueryChangeLogException("Mocked exception."));
 
         // Create the QueryRepository and invoke one of the methods.
-        try(final QueryRepository queries = new InMemoryQueryRepository( changeLog )) {
-            queries.list();
-        }
+        final QueryRepository queries = new InMemoryQueryRepository( changeLog, SCHEDULE );
+        queries.list();
     }
 
     @Test
     public void get_present() throws Exception {
         // Setup a totally in memory QueryRepository.
-        try(final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog() )) {
-            // Add a query to it.
-            final StreamsQuery query = queries.add("query 1", true);
+        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
+        // Add a query to it.
+        final StreamsQuery query = queries.add("query 1", true);
 
-            // Show the fetched query matches the expected ones.
-            final Optional<StreamsQuery> fetched = queries.get(query.getQueryId());
-            assertEquals(query, fetched.get());
-        }
+        // Show the fetched query matches the expected ones.
+        final Optional<StreamsQuery> fetched = queries.get(query.getQueryId());
+        assertEquals(query, fetched.get());
     }
 
     @Test
     public void get_notPresent() throws Exception {
         // Setup a totally in memory QueryRepository.
-        try(final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog() )) {
-            // Fetch a query that was never added to the repository.
-            final Optional<StreamsQuery> query = queries.get(UUID.randomUUID());
+        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
+        // Fetch a query that was never added to the repository.
+        final Optional<StreamsQuery> query = queries.get(UUID.randomUUID());
 
-            // Show it could not be found.
-            assertFalse(query.isPresent());
-        }
+        // Show it could not be found.
+        assertFalse(query.isPresent());
     }
 
     @Test
     public void update() throws Exception {
         // Setup a totally in memory QueryRepository.
-        try(final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog() )) {
+        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
+        // Add a query to it.
+        final StreamsQuery query = queries.add("query 1", true);
+
+        // Change the isActive state of that query.
+        queries.updateIsActive(query.getQueryId(), false);
+
+        // Show the fetched query matches the expected one.
+        final Optional<StreamsQuery> fetched = queries.get(query.getQueryId());
+        final StreamsQuery expected = new StreamsQuery(query.getQueryId(), query.getSparql(), false);
+        assertEquals(expected, fetched.get());
+    }
+
+    @Test
+    public void updateListenerNotify() throws Exception {
+        // Setup a totally in memory QueryRepository.
+        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), SCHEDULE );
+        try {
+            queries.startAndWait();
+
             // Add a query to it.
             final StreamsQuery query = queries.add("query 1", true);
 
-            // Change the isActive state of that query.
-            queries.updateIsActive(query.getQueryId(), false);
+            final Set<StreamsQuery> existing = queries.subscribe(new QueryChangeLogListener() {
+                @Override
+                public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {
+                    final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(1L,
+                            QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                    assertEquals(expected, queryChangeEvent);
+                }
+            });
+
+            assertEquals(Sets.newHashSet(query), existing);
+
+            queries.add("query 2", true);
+        } finally {
+            queries.stop();
+        }
+    }
 
-            // Show the fetched query matches the expected one.
-            final Optional<StreamsQuery> fetched = queries.get(query.getQueryId());
-            final StreamsQuery expected = new StreamsQuery(query.getQueryId(), query.getSparql(), false);
-            assertEquals(expected, fetched.get());
+    @Test
+    public void updateListenerNotify_multiClient() throws Exception {
+        // Setup a totally in memory QueryRepository.
+        final QueryChangeLog changeLog = new InMemoryQueryChangeLog();
+        final QueryRepository queries = new InMemoryQueryRepository( changeLog, SCHEDULE );
+        final QueryRepository queries2 = new InMemoryQueryRepository( changeLog, SCHEDULE );
+
+        try {
+            queries.startAndWait();
+            queries2.startAndWait();
+
+            //show listener on repo that query was added to is being notified of the new query.
+            final CountDownLatch repo1Latch = new CountDownLatch(1);
+            queries.subscribe(new QueryChangeLogListener() {
+                @Override
+                public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {
+                    final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
+                            QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                    assertEquals(expected, queryChangeEvent);
+                    repo1Latch.countDown();
+                }
+            });
+
+            //show listener not on the repo that query was added to is being notified as well.
+            final CountDownLatch repo2Latch = new CountDownLatch(1);
+            queries2.subscribe(new QueryChangeLogListener() {
+                @Override
+                public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {
+                    final ChangeLogEntry<QueryChange> expected = new ChangeLogEntry<QueryChange>(0L,
+                            QueryChange.create(queryChangeEvent.getEntry().getQueryId(), "query 2", true));
+                    assertEquals(expected, queryChangeEvent);
+                    repo2Latch.countDown();
+                }
+            });
+
+            queries.add("query 2", true);
+
+            assertTrue(repo1Latch.await(5, TimeUnit.SECONDS));
+            assertTrue(repo2Latch.await(5, TimeUnit.SECONDS));
+        } catch(final InterruptedException e ) {
+            System.out.println("PING");
+        } finally {
+            queries.stop();
+            queries2.stop();
         }
     }
+
+    @Test(expected = IllegalStateException.class)
+    public void subscribe_notStarted() throws Exception {
+        // Setup a totally in memory QueryRepository.
+        final QueryRepository queries = new InMemoryQueryRepository(new InMemoryQueryChangeLog(), SCHEDULE);
+        queries.subscribe(new QueryChangeLogListener() {
+            @Override
+            public void notify(final ChangeLogEntry<QueryChange> queryChangeEvent) {}
+        });
+
+        queries.add("query 2", true);
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
index 275a975..9273c33 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/AddQueryCommand.java
@@ -20,6 +20,8 @@ package org.apache.rya.streams.client.command;
 
 import static java.util.Objects.requireNonNull;
 
+import java.util.concurrent.TimeUnit;
+
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.exception.RyaStreamsException;
 import org.apache.rya.streams.api.interactor.AddQuery;
@@ -35,6 +37,7 @@ import com.beust.jcommander.JCommander;
 import com.beust.jcommander.Parameter;
 import com.beust.jcommander.ParameterException;
 import com.google.common.base.Strings;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
@@ -115,8 +118,11 @@ public class AddQueryCommand implements RyaStreamsCommand {
         final String topic = KafkaTopics.queryChangeLogTopic(params.ryaInstance);
         final QueryChangeLog queryChangeLog = KafkaQueryChangeLogFactory.make(bootstrapServers, topic);
 
+        //The AddQuery command doesn't use the scheduled service feature.
+        final Scheduler scheduler = Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS);
+        final QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog, scheduler);
         // Execute the add query command.
-        try(QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog)) {
+        try {
             final AddQuery addQuery = new DefaultAddQuery(queryRepo);
             try {
                 final StreamsQuery query = addQuery.addQuery(params.query, Boolean.parseBoolean(params.isActive));

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/DeleteQueryCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/DeleteQueryCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/DeleteQueryCommand.java
index 2aeb90c..0d96df0 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/DeleteQueryCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/DeleteQueryCommand.java
@@ -21,6 +21,7 @@ package org.apache.rya.streams.client.command;
 import static java.util.Objects.requireNonNull;
 
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.rya.streams.api.exception.RyaStreamsException;
 import org.apache.rya.streams.api.interactor.DeleteQuery;
@@ -36,6 +37,7 @@ import com.beust.jcommander.JCommander;
 import com.beust.jcommander.Parameter;
 import com.beust.jcommander.ParameterException;
 import com.google.common.base.Strings;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
@@ -113,8 +115,11 @@ public class DeleteQueryCommand implements RyaStreamsCommand {
         final String topic = KafkaTopics.queryChangeLogTopic(params.ryaInstance);
         final QueryChangeLog queryChangeLog = KafkaQueryChangeLogFactory.make(bootstrapServers, topic);
 
+        //The DeleteQuery command doesn't use the scheduled service feature.
+        final Scheduler scheduler = Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS);
+        final QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog, scheduler);
         // Execute the delete query command.
-        try(QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog)) {
+        try {
             final DeleteQuery deleteQuery = new DefaultDeleteQuery(queryRepo);
             try {
                 deleteQuery.delete(UUID.fromString(params.queryId));

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
index 670007b..cd78975 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/ListQueriesCommand.java
@@ -21,6 +21,7 @@ package org.apache.rya.streams.client.command;
 import static java.util.Objects.requireNonNull;
 
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.exception.RyaStreamsException;
@@ -35,6 +36,7 @@ import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLogFactory;
 
 import com.beust.jcommander.JCommander;
 import com.beust.jcommander.ParameterException;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
@@ -83,8 +85,11 @@ public class ListQueriesCommand implements RyaStreamsCommand {
         final String topic = KafkaTopics.queryChangeLogTopic(params.ryaInstance);
         final QueryChangeLog queryChangeLog = KafkaQueryChangeLogFactory.make(bootstrapServers, topic);
 
+        //The ListQueries command doesn't use the scheduled service feature.
+        final Scheduler scheduler = Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS);
+        final QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog, scheduler);
         // Execute the list queries command.
-        try(QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog)) {
+        try {
             final ListQueries listQueries = new DefaultListQueries(queryRepo);
             try {
                 final Set<StreamsQuery> queries = listQueries.all();

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
index 8f7f162..ddaf647 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/RunQueryCommand.java
@@ -24,6 +24,7 @@ import java.util.HashSet;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.rya.streams.api.entity.StreamsQuery;
 import org.apache.rya.streams.api.queries.InMemoryQueryRepository;
@@ -39,6 +40,7 @@ import com.beust.jcommander.JCommander;
 import com.beust.jcommander.Parameter;
 import com.beust.jcommander.ParameterException;
 import com.google.common.base.Strings;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
@@ -117,8 +119,11 @@ public class RunQueryCommand implements RyaStreamsCommand {
         final String topic = KafkaTopics.queryChangeLogTopic(params.ryaInstance);
         final QueryChangeLog queryChangeLog = KafkaQueryChangeLogFactory.make(bootstrapServers, topic);
 
+        //The RunQuery command doesn't use the scheduled service feature.
+        final Scheduler scheduler = Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS);
+        final QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog, scheduler);
         // Look up the query to be executed from the change log.
-        try(QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog)) {
+        try {
             try {
                 final UUID queryId = UUID.fromString( params.queryId );
                 final Optional<StreamsQuery> query = queryRepo.get(queryId);
@@ -145,7 +150,7 @@ public class RunQueryCommand implements RyaStreamsCommand {
             } catch(final Exception e) {
                 throw new ExecutionException("Could not execute the Run Query command.", e);
             }
-        } catch(final ArgumentsException | ExecutionException e) {
+        } catch(final ExecutionException e) {
             // Rethrow the exceptions that are advertised by execute.
             throw e;
         } catch (final Exception e) {

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
index 7c548f1..3612dd0 100644
--- a/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
+++ b/extras/rya.streams/client/src/main/java/org/apache/rya/streams/client/command/StreamResultsCommand.java
@@ -22,6 +22,7 @@ import static java.util.Objects.requireNonNull;
 
 import java.util.Optional;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.rya.streams.api.entity.QueryResultStream;
@@ -45,6 +46,7 @@ import com.beust.jcommander.JCommander;
 import com.beust.jcommander.Parameter;
 import com.beust.jcommander.ParameterException;
 import com.google.common.base.Strings;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
 import edu.umd.cs.findbugs.annotations.NonNull;
@@ -132,9 +134,12 @@ public class StreamResultsCommand implements RyaStreamsCommand {
             throw new ArgumentsException("Invalid Query ID " + params.queryId);
         }
 
+        //The DeleteQuery command doesn't use the scheduled service feature.
+        final Scheduler scheduler = Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS);
+        final QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog, scheduler);
         // Fetch the SPARQL of the query whose results will be streamed.
         final String sparql;
-        try(QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog)) {
+        try {
             final Optional<StreamsQuery> sQuery = queryRepo.get(queryId);
             if(!sQuery.isPresent()) {
                 throw new ExecutionException("Could not read the results for query with ID " + queryId +

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
index 8b4f074..3bfbadc 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/AddQueryCommandIT.java
@@ -22,6 +22,7 @@ import static org.junit.Assert.assertEquals;
 
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.producer.Producer;
@@ -38,11 +39,12 @@ import org.apache.rya.streams.kafka.serialization.queries.QueryChangeDeserialize
 import org.apache.rya.streams.kafka.serialization.queries.QueryChangeSerializer;
 import org.apache.rya.test.kafka.KafkaTestInstanceRule;
 import org.apache.rya.test.kafka.KafkaTestUtil;
-import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
 /**
  * integration Test for adding a new query through a command.
  */
@@ -64,12 +66,7 @@ public class AddQueryCommandIT {
         final Producer<?, QueryChange> queryProducer = KafkaTestUtil.makeProducer(kafka, StringSerializer.class, QueryChangeSerializer.class);
         final Consumer<?, QueryChange>queryConsumer = KafkaTestUtil.fromStartConsumer(kafka, StringDeserializer.class, QueryChangeDeserializer.class);
         final QueryChangeLog changeLog = new KafkaQueryChangeLog(queryProducer, queryConsumer, changeLogTopic);
-        queryRepo = new InMemoryQueryRepository(changeLog);
-    }
-
-    @After
-    public void cleanup() throws Exception {
-        queryRepo.close();
+        queryRepo = new InMemoryQueryRepository(changeLog, Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS));
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
index 6083543..7bec080 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/DeleteQueryCommandIT.java
@@ -23,6 +23,7 @@ import static org.junit.Assert.assertNotEquals;
 
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.producer.Producer;
@@ -39,11 +40,12 @@ import org.apache.rya.streams.kafka.serialization.queries.QueryChangeDeserialize
 import org.apache.rya.streams.kafka.serialization.queries.QueryChangeSerializer;
 import org.apache.rya.test.kafka.KafkaTestInstanceRule;
 import org.apache.rya.test.kafka.KafkaTestUtil;
-import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
 /**
  * Integration Test for deleting a query from Rya Streams through a command.
  */
@@ -66,12 +68,7 @@ public class DeleteQueryCommandIT {
         final Producer<?, QueryChange> queryProducer = KafkaTestUtil.makeProducer(kafka, StringSerializer.class, QueryChangeSerializer.class);
         final Consumer<?, QueryChange>queryConsumer = KafkaTestUtil.fromStartConsumer(kafka, StringDeserializer.class, QueryChangeDeserializer.class);
         final QueryChangeLog changeLog = new KafkaQueryChangeLog(queryProducer, queryConsumer, changeLogTopic);
-        queryRepo = new InMemoryQueryRepository(changeLog);
-    }
-
-    @After
-    public void cleanup() throws Exception {
-        queryRepo.close();
+        queryRepo = new InMemoryQueryRepository(changeLog, Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS));
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
index 1399142..f6ceb75 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/ListQueryCommandIT.java
@@ -19,6 +19,7 @@
 package org.apache.rya.streams.client.command;
 
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.producer.Producer;
@@ -34,11 +35,12 @@ import org.apache.rya.streams.kafka.serialization.queries.QueryChangeDeserialize
 import org.apache.rya.streams.kafka.serialization.queries.QueryChangeSerializer;
 import org.apache.rya.test.kafka.KafkaTestInstanceRule;
 import org.apache.rya.test.kafka.KafkaTestUtil;
-import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
 /**
  * integration Test for listing queries through a command.
  */
@@ -60,12 +62,7 @@ public class ListQueryCommandIT {
         final Producer<?, QueryChange> queryProducer = KafkaTestUtil.makeProducer(kafka, StringSerializer.class, QueryChangeSerializer.class);
         final Consumer<?, QueryChange>queryConsumer = KafkaTestUtil.fromStartConsumer(kafka, StringDeserializer.class, QueryChangeDeserializer.class);
         final QueryChangeLog changeLog = new KafkaQueryChangeLog(queryProducer, queryConsumer, changeLogTopic);
-        queryRepo = new InMemoryQueryRepository(changeLog);
-    }
-
-    @After
-    public void cleanup() throws Exception {
-        queryRepo.close();
+        queryRepo = new InMemoryQueryRepository(changeLog, Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS));
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
index 3389d6b..7e3b8bc 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
@@ -23,6 +23,7 @@ import static org.junit.Assert.assertEquals;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.producer.Producer;
@@ -56,6 +57,7 @@ import org.openrdf.model.impl.ValueFactoryImpl;
 import org.openrdf.query.impl.MapBindingSet;
 
 import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 /**
  * Integration tests the methods of {@link RunQueryCommand}.
@@ -81,7 +83,7 @@ public class RunQueryCommandIT {
         final Producer<?, QueryChange> queryProducer = KafkaTestUtil.makeProducer(kafka, StringSerializer.class, QueryChangeSerializer.class);
         final Consumer<?, QueryChange>queryConsumer = KafkaTestUtil.fromStartConsumer(kafka, StringDeserializer.class, QueryChangeDeserializer.class);
         final QueryChangeLog changeLog = new KafkaQueryChangeLog(queryProducer, queryConsumer, changeLogTopic);
-        queryRepo = new InMemoryQueryRepository(changeLog);
+        queryRepo = new InMemoryQueryRepository(changeLog, Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS));
 
         // Initialize the Statements Producer and the Results Consumer.
         stmtProducer = KafkaTestUtil.makeProducer(kafka, StringSerializer.class, VisibilityStatementSerializer.class);
@@ -92,7 +94,6 @@ public class RunQueryCommandIT {
     public void cleanup() throws Exception{
         stmtProducer.close();
         resultConsumer.close();
-        queryRepo.close();
     }
 
     @Test(expected = ExecutionException.class)

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/36af1153/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
index 9a773f0..5dbd27f 100644
--- a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
+++ b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/interactor/KafkaRunQueryIT.java
@@ -23,6 +23,7 @@ import static org.junit.Assert.assertEquals;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.producer.Producer;
@@ -52,6 +53,7 @@ import org.openrdf.model.impl.ValueFactoryImpl;
 import org.openrdf.query.impl.MapBindingSet;
 
 import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
 
 /**
  * Integration tests the methods of {@link KafkaRunQuery}.
@@ -83,7 +85,7 @@ public class KafkaRunQueryIT {
         final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
 
         // This query is completely in memory, so it doesn't need to be closed.
-        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog() );
+        final QueryRepository queries = new InMemoryQueryRepository( new InMemoryQueryChangeLog(), Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS) );
 
         // Add the query to the query repository.
         final StreamsQuery sQuery = queries.add("SELECT * WHERE { ?person <urn:worksAt> ?business . }", true);


[22/22] incubator-rya git commit: RYA-466 Updated regexes to not conflict on binding names. Closes #279

Posted by pu...@apache.org.
RYA-466 Updated regexes to not conflict on binding names.  Closes #279


Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/770bd7e4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/770bd7e4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/770bd7e4

Branch: refs/heads/master
Commit: 770bd7e4ac971b6737651266247129fc5346b5cb
Parents: 010c692
Author: Andrew Smith <sm...@gmail.com>
Authored: Thu Mar 1 15:20:23 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 13:01:31 2018 -0500

----------------------------------------------------------------------
 .../org/apache/rya/api/utils/QueryInvestigator.java   | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/770bd7e4/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
----------------------------------------------------------------------
diff --git a/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java b/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
index a6c93e9..54f0010 100644
--- a/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
+++ b/common/rya.api/src/main/java/org/apache/rya/api/utils/QueryInvestigator.java
@@ -20,10 +20,9 @@ package org.apache.rya.api.utils;
 
 import static java.util.Objects.requireNonNull;
 
+import java.util.regex.Pattern;
+
 import org.openrdf.query.MalformedQueryException;
-import org.openrdf.query.parser.ParsedGraphQuery;
-import org.openrdf.query.parser.ParsedQuery;
-import org.openrdf.query.parser.QueryParserUtil;
 import org.openrdf.query.parser.sparql.SPARQLParser;
 
 import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
@@ -51,10 +50,10 @@ public class QueryInvestigator {
 
         try {
             // Constructs are queries, so try to create a ParsedQuery.
-            final ParsedQuery parsedQuery = PARSER.parseQuery(sparql, null);
+            PARSER.parseQuery(sparql, null);
 
             // Check to see if the SPARQL looks like a CONSTRUCT query.
-            return parsedQuery instanceof ParsedGraphQuery;
+            return Pattern.matches("[\\s\\S]*?construct\\s*?\\{[\\s\\S]*?\\}[\\s\\S]*?where\\s*\\{[\\s\\S]*?\\}", sparql.toLowerCase());
 
         } catch(final MalformedQueryException queryE) {
             try {
@@ -84,8 +83,9 @@ public class QueryInvestigator {
         try {
             // Inserts are updated, so try to create a ParsedUpdate.
             PARSER.parseUpdate(sparql, null);
-            final String strippedOperation = QueryParserUtil.removeSPARQLQueryProlog(sparql.toLowerCase());
-            return strippedOperation.startsWith("insert");
+
+            // Check to see if the SPARQL looks like an INSERT query.
+            return Pattern.matches("[\\s\\S]*?insert\\s*?\\{[\\s\\S]*?\\}[\\s\\S]*?where\\s*\\{[\\s\\S]*?\\}", sparql.toLowerCase());
         } catch(final MalformedQueryException updateE) {
             try {
                 // Maybe it's a query.


[07/22] incubator-rya git commit: RYA-450 Implemented a Kafka backed QueryChangeLogSource.

Posted by pu...@apache.org.
RYA-450 Implemented a Kafka backed QueryChangeLogSource.



Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/ee29450d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/ee29450d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/ee29450d

Branch: refs/heads/master
Commit: ee29450da821e3d61455322a046fa9a271df1d02
Parents: c1ccde8
Author: kchilton2 <ke...@gmail.com>
Authored: Tue Jan 23 16:17:06 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:43 2018 -0500

----------------------------------------------------------------------
 .../apache/rya/streams/kafka/KafkaTopics.java   |  28 +-
 .../rya/streams/kafka/KafkaTopicsTest.java      |  53 ++++
 extras/rya.streams/query-manager/pom.xml        |  23 +-
 .../kafka/KafkaQueryChangeLogSource.java        | 209 ++++++++++++++
 .../kafka/KafkaQueryChangeLogSourceIT.java      | 277 +++++++++++++++++++
 .../rya/test/kafka/EmbeddedKafkaInstance.java   |   1 +
 .../rya/test/kafka/KafkaTestInstanceRule.java   |  52 ++++
 7 files changed, 638 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/ee29450d/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
index 3e0df50..095465c 100644
--- a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaTopics.java
@@ -1,4 +1,4 @@
-/*
+/**
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -20,6 +20,7 @@ package org.apache.rya.streams.kafka;
 
 import static java.util.Objects.requireNonNull;
 
+import java.util.Optional;
 import java.util.Properties;
 import java.util.Set;
 import java.util.UUID;
@@ -40,6 +41,8 @@ import kafka.utils.ZkUtils;
 @DefaultAnnotation(NonNull.class)
 public class KafkaTopics {
 
+    private static final String QUERY_CHANGE_LOG_TOPIC_SUFFIX = "-QueryChangeLog";
+
     /**
      * Creates the Kafka topic name that is used for a specific instance of Rya's {@link QueryChangeLog}.
      *
@@ -48,7 +51,28 @@ public class KafkaTopics {
      */
     public static String queryChangeLogTopic(final String ryaInstance) {
         requireNonNull(ryaInstance);
-        return ryaInstance + "-QueryChangeLog";
+        return ryaInstance + QUERY_CHANGE_LOG_TOPIC_SUFFIX;
+    }
+
+    /**
+     * Get the Rya instance name from a Kafka topic name that has been used for a {@link QueryChnageLog}.
+     * <p/>
+     * This is the inverse function of {@link #queryChangeLogTopic(String)}.
+     *
+     * @param changeLogTopic - The topic to evaluate. (not null)
+     * @return If the topic is well formatted, then the Rya instance name that was part of the topic name.
+     */
+    public static Optional<String> getRyaInstance(final String changeLogTopic) {
+        requireNonNull(changeLogTopic);
+
+        // Return absent if the provided topic does not represent a query change log topic.
+        if(!changeLogTopic.endsWith(QUERY_CHANGE_LOG_TOPIC_SUFFIX)) {
+            return Optional.empty();
+        }
+
+        // Everything before the suffix is the Rya instance name.
+        final int endIndex = changeLogTopic.length() - QUERY_CHANGE_LOG_TOPIC_SUFFIX.length();
+        return Optional.of( changeLogTopic.substring(0, endIndex) );
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/ee29450d/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java
new file mode 100644
index 0000000..a057de7
--- /dev/null
+++ b/extras/rya.streams/kafka/src/test/java/org/apache/rya/streams/kafka/KafkaTopicsTest.java
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.kafka;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+import java.util.Optional;
+
+import org.junit.Test;
+
+/**
+ * Unit tests the methods of {@link KafkaTopics}.
+ */
+public class KafkaTopicsTest {
+
+    @Test
+    public void getRyaInstance_wellFormattedTopic() {
+        // Make a topic name using a Rya instance name.
+        final String ryaInstance = "test";
+        final String topicName = KafkaTopics.queryChangeLogTopic(ryaInstance);
+
+        // Show the rya instance name is able to be extracted from the topic.
+        final Optional<String> resolvedRyaInstance = KafkaTopics.getRyaInstance(topicName);
+        assertEquals(ryaInstance, resolvedRyaInstance.get());
+    }
+
+    @Test
+    public void getRyaInstance_invalidTopicName() {
+        // Make up an invalid topic name.
+        final String invalidTopic = "thisIsABadTopicName";
+
+        // Show there is no Rya Instance name in it.
+        final Optional<String> ryaInstance = KafkaTopics.getRyaInstance(invalidTopic);
+        assertFalse( ryaInstance.isPresent() );
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/ee29450d/extras/rya.streams/query-manager/pom.xml
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/pom.xml b/extras/rya.streams/query-manager/pom.xml
index 76e521d..d321ab5 100644
--- a/extras/rya.streams/query-manager/pom.xml
+++ b/extras/rya.streams/query-manager/pom.xml
@@ -37,15 +37,32 @@ under the License.
         <!-- Rya dependencies -->
         <dependency>
             <groupId>org.apache.rya</groupId>
-            <artifactId>rya.streams.client</artifactId>
+            <artifactId>rya.streams.kafka</artifactId>
         </dependency>
-
+        
         <!-- Apache Daemon dependencies -->
         <dependency>
             <groupId>commons-daemon</groupId>
             <artifactId>commons-daemon</artifactId>
             <version>1.1.0</version>
         </dependency>
+        
+        <!-- Test dependencies -->
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.rya</groupId>
+            <artifactId>rya.test.kafka</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-all</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
     <build>
         <!-- Add the XSD directory as a resource so that it will be packaged in the jar. 
@@ -121,4 +138,4 @@ under the License.
             </plugin>
         </plugins>
      </build>
-</project>
\ No newline at end of file
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/ee29450d/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
new file mode 100644
index 0000000..32305f5
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSource.java
@@ -0,0 +1,209 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager.kafka;
+
+import static java.util.Objects.requireNonNull;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map.Entry;
+import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.stream.Collectors;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.rya.streams.api.queries.QueryChangeLog;
+import org.apache.rya.streams.kafka.KafkaTopics;
+import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLog;
+import org.apache.rya.streams.kafka.queries.KafkaQueryChangeLogFactory;
+import org.apache.rya.streams.querymanager.QueryChangeLogSource;
+
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.AbstractScheduledService;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * Represents a Kafka Server that manages {@link KafkaQueryChangeLog}s.
+ * <p/>
+ * Thread safe.
+ */
+@DefaultAnnotation(NonNull.class)
+public class KafkaQueryChangeLogSource extends AbstractScheduledService implements QueryChangeLogSource {
+
+    /**
+     * Ensures thread safe interactions with this object.
+     */
+    private final ReentrantLock lock = new ReentrantLock();
+
+    /**
+     * Used by the service to configure how often it polls the Kafka Server for topics.
+     */
+    private final Scheduler scheduler;
+
+    /**
+     * Which Kafka Server this source represents.
+     */
+    private final String kafkaBootstrapServer;
+
+    /**
+     * Listeners that need to be notified when logs are created/deleted.
+     */
+    private final Set<SourceListener> listeners = new HashSet<>();
+
+    /**
+     * Maps Rya instance name to a Query Change Log for that instance. This map is used to keep
+     * track of how the change logs change over time within the Kafka Server.
+     */
+    private final HashMap<String, QueryChangeLog> knownChangeLogs = new HashMap<>();
+
+    /**
+     * A consumer that is used to poll the Kafka Server for topics.
+     */
+    private KafkaConsumer<String, String> listTopicsConsumer;
+
+    /**
+     * Constructs an instance of {@link KafkaQueryChangeLogSource}.
+     *
+     * @param kafkaHostname - The hostname of the Kafka Server that is the source. (not null)
+     * @param kafkaPort - The port of the Kafka Server that is the source. (not null)
+     * @param scheduler - How frequently this source will poll the Kafka Server for topics. (not null)
+     */
+    public KafkaQueryChangeLogSource(
+            final String kafkaHostname,
+            final int kafkaPort,
+            final Scheduler scheduler) {
+        kafkaBootstrapServer = requireNonNull(kafkaHostname) + ":" + kafkaPort;
+        this.scheduler = requireNonNull(scheduler);
+    }
+
+    @Override
+    protected void startUp() throws Exception {
+        // Setup the consumer that is used to list topics for the source.
+        final Properties consumerProperties = new Properties();
+        consumerProperties.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaBootstrapServer);
+        consumerProperties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
+        consumerProperties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+        consumerProperties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+        listTopicsConsumer = new KafkaConsumer<>(consumerProperties);
+    }
+
+    @Override
+    protected void shutDown() throws Exception {
+        // Shut down the consumer that's used to list topics.
+        listTopicsConsumer.close();
+
+        // Shut down all of the change logs that were created within this class.
+        for(final QueryChangeLog changeLog : knownChangeLogs.values()) {
+            changeLog.close();
+        }
+    }
+
+    @Override
+    public void subscribe(final SourceListener listener) {
+        requireNonNull(listener);
+        lock.lock();
+        try {
+            // Add the listener to the list of known listeners.
+            listeners.add(listener);
+
+            // Notify it with everything that already exists.
+            for(final Entry<String, QueryChangeLog> entry : knownChangeLogs.entrySet()) {
+                listener.notifyCreate(entry.getKey(), entry.getValue());
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    public void unsubscribe(final SourceListener listener) {
+        requireNonNull(listener);
+        lock.lock();
+        try {
+            // Remove the listener from the list of known listeners.
+            listeners.remove(listener);
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    protected void runOneIteration() throws Exception {
+        lock.lock();
+        try {
+            // Get the list of topics from the Kafka Server.
+            final Set<String> changeLogTopics = new HashSet<>( listTopicsConsumer.listTopics().keySet() );
+
+            // Remove all topics that are not valid Rya Query Change Log topic names.
+            changeLogTopics.removeIf( topic -> !KafkaTopics.getRyaInstance(topic).isPresent() );
+
+            // Extract the Rya instance names from the change log topics.
+            final Set<String> ryaInstances = changeLogTopics.stream()
+                    .map(topic -> KafkaTopics.getRyaInstance(topic).get() )
+                    .collect(Collectors.toSet());
+
+            // Any Rya instances that are in the old set of topics, but not the new one, have been deleted.
+            final Set<String> deletedRyaInstances = new HashSet<>( Sets.difference(knownChangeLogs.keySet(), ryaInstances) );
+
+            // Any Rya instances that are in the new set of topics, but not the old set, have been created.
+            final Set<String> createdRyaInstances = new HashSet<>( Sets.difference(ryaInstances, knownChangeLogs.keySet()) );
+
+            // Handle the deletes.
+            for(final String deletedRyaInstance : deletedRyaInstances) {
+                // Remove the change log from the set of known logs.
+                final QueryChangeLog removed = knownChangeLogs.remove(deletedRyaInstance);
+
+                // Notify the listeners of the update.
+                for(final SourceListener listener : listeners) {
+                    listener.notifyDelete(deletedRyaInstance);
+                }
+
+                // Ensure the change log is closed.
+                removed.close();
+            }
+
+            // Handle the adds.
+            for(final String createdRyaInstance : createdRyaInstances) {
+                // Create and store the ChangeLog.
+                final String changeLogTopic = KafkaTopics.queryChangeLogTopic(createdRyaInstance);
+                final KafkaQueryChangeLog changeLog = KafkaQueryChangeLogFactory.make(kafkaBootstrapServer, changeLogTopic);
+                knownChangeLogs.put(createdRyaInstance, changeLog);
+
+                // Notify the listeners of the update.
+                for(final SourceListener listener : listeners) {
+                    listener.notifyCreate(createdRyaInstance, changeLog);
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    protected Scheduler scheduler() {
+        return scheduler;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/ee29450d/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSourceIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSourceIT.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSourceIT.java
new file mode 100644
index 0000000..5914b78
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/KafkaQueryChangeLogSourceIT.java
@@ -0,0 +1,277 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager.kafka;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.rya.streams.api.queries.QueryChangeLog;
+import org.apache.rya.streams.kafka.KafkaTopics;
+import org.apache.rya.streams.querymanager.QueryChangeLogSource;
+import org.apache.rya.streams.querymanager.QueryChangeLogSource.SourceListener;
+import org.apache.rya.test.kafka.KafkaTestInstanceRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import com.google.common.util.concurrent.AbstractScheduledService.Scheduler;
+
+/**
+ * Integration tests the methods of {@link KafkaQueryChangeLogSource}.
+ */
+public class KafkaQueryChangeLogSourceIT {
+
+    @Rule
+    public KafkaTestInstanceRule kafka = new KafkaTestInstanceRule(false);
+
+    @Before
+    public void clearTopics() throws InterruptedException {
+        kafka.deleteAllTopics();
+    }
+
+    @Test
+    public void discoverExistingLogs() throws Exception {
+        // Create a valid Query Change Log topic.
+        final String ryaInstance = UUID.randomUUID().toString();
+        final String topic = KafkaTopics.queryChangeLogTopic(ryaInstance);
+        kafka.createTopic(topic);
+
+        // Create the source.
+        final QueryChangeLogSource source = new KafkaQueryChangeLogSource(
+                kafka.getKafkaHostname(),
+                Integer.parseInt( kafka.getKafkaPort() ),
+                Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS));
+
+        // Register a listener that counts down a latch if it sees the new topic.
+        final CountDownLatch created = new CountDownLatch(1);
+        source.subscribe(new SourceListener() {
+            @Override
+            public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
+                assertEquals(ryaInstance, ryaInstanceName);
+                created.countDown();
+            }
+
+            @Override
+            public void notifyDelete(final String ryaInstanceName) { }
+        });
+
+        try {
+            // Start the source.
+            source.startAndWait();
+
+            // If the latch isn't counted down, then fail the test.
+            assertTrue( created.await(5, TimeUnit.SECONDS) );
+
+        } finally {
+            source.stopAndWait();
+        }
+    }
+
+    @Test
+    public void discoverNewLogs() throws Exception {
+        // Create the source.
+        final QueryChangeLogSource source = new KafkaQueryChangeLogSource(
+                kafka.getKafkaHostname(),
+                Integer.parseInt( kafka.getKafkaPort() ),
+                Scheduler.newFixedRateSchedule(0, 100, TimeUnit.MILLISECONDS));
+
+        // Register a listener that counts down a latch if it sees the new topic.
+        final String ryaInstance = UUID.randomUUID().toString();
+        final CountDownLatch created = new CountDownLatch(1);
+        source.subscribe(new SourceListener() {
+            @Override
+            public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
+                assertEquals(ryaInstance, ryaInstanceName);
+                created.countDown();
+            }
+
+            @Override
+            public void notifyDelete(final String ryaInstanceName) { }
+        });
+
+        try {
+            // Start the source.
+            source.startAndWait();
+
+            // Wait twice the polling duration to ensure it iterates at least once.
+            Thread.sleep(200);
+
+            // Create a valid Query Change Log topic.
+            final String topic = KafkaTopics.queryChangeLogTopic(ryaInstance);
+            kafka.createTopic(topic);
+
+            // If the latch isn't counted down, then fail the test.
+            assertTrue( created.await(5, TimeUnit.SECONDS) );
+        } finally {
+            source.stopAndWait();
+        }
+    }
+
+    @Test
+    public void discoverLogDeletions() throws Exception {
+        // Create a valid Query Change Log topic.
+        final String ryaInstance = UUID.randomUUID().toString();
+        final String topic = KafkaTopics.queryChangeLogTopic(ryaInstance);
+        kafka.createTopic(topic);
+
+        // Create the source.
+        final QueryChangeLogSource source = new KafkaQueryChangeLogSource(
+                kafka.getKafkaHostname(),
+                Integer.parseInt( kafka.getKafkaPort() ),
+                Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS));
+
+        // Register a listener that uses latches to indicate when the topic is created and deleted.
+        final CountDownLatch created = new CountDownLatch(1);
+        final CountDownLatch deleted = new CountDownLatch(1);
+        source.subscribe(new SourceListener() {
+            @Override
+            public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
+                assertEquals(ryaInstance, ryaInstanceName);
+                created.countDown();
+            }
+
+            @Override
+            public void notifyDelete(final String ryaInstanceName) {
+                assertEquals(ryaInstance, ryaInstanceName);
+                deleted.countDown();
+            }
+        });
+
+        try {
+            // Start the source
+            source.startAndWait();
+
+            // Wait for it to indicate the topic was created.
+            assertTrue( created.await(5, TimeUnit.SECONDS) );
+
+            // Delete the topic.
+            kafka.deleteTopic(topic);
+
+            // If the latch isn't counted down, then fail the test.
+            assertTrue( deleted.await(5, TimeUnit.SECONDS) );
+
+        } finally {
+            source.stopAndWait();
+        }
+    }
+
+    @Test
+    public void newListenerReceivesAllKnownLogs() throws Exception {
+        // Create a valid Query Change Log topic.
+        final String ryaInstance = UUID.randomUUID().toString();
+        final String topic = KafkaTopics.queryChangeLogTopic(ryaInstance);
+        kafka.createTopic(topic);
+
+        // Create the source.
+        final QueryChangeLogSource source = new KafkaQueryChangeLogSource(
+                kafka.getKafkaHostname(),
+                Integer.parseInt( kafka.getKafkaPort() ),
+                Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS));
+
+        // Register a listener that counts down a latch if it sees the new topic.
+        final CountDownLatch created = new CountDownLatch(1);
+        source.subscribe(new SourceListener() {
+            @Override
+            public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
+                assertEquals(ryaInstance, ryaInstanceName);
+                created.countDown();
+            }
+
+            @Override
+            public void notifyDelete(final String ryaInstanceName) { }
+        });
+
+        try {
+            // Start the source
+            source.startAndWait();
+
+            // Wait for that first listener to indicate the topic was created. This means that one has been cached.
+            assertTrue( created.await(5, TimeUnit.SECONDS) );
+
+            // Register a second listener that counts down when that same topic is encountered. This means the
+            // newly subscribed listener was notified with the already known change log.
+            final CountDownLatch newListenerCreated = new CountDownLatch(1);
+            source.subscribe(new SourceListener() {
+                @Override
+                public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
+                    assertEquals(ryaInstance, ryaInstanceName);
+                    newListenerCreated.countDown();
+                }
+
+                @Override
+                public void notifyDelete(final String ryaInstanceName) { }
+            });
+            assertTrue( newListenerCreated.await(5, TimeUnit.SECONDS) );
+
+        } finally {
+            source.stopAndWait();
+        }
+    }
+
+    @Test
+    public void unsubscribedDoesNotReceiveNotifications() throws Exception {
+        // Create the source.
+        final QueryChangeLogSource source = new KafkaQueryChangeLogSource(
+                kafka.getKafkaHostname(),
+                Integer.parseInt( kafka.getKafkaPort() ),
+                Scheduler.newFixedRateSchedule(0, 100, TimeUnit.MILLISECONDS));
+
+        try {
+            // Start the source.
+            source.startAndWait();
+
+            // Create a listener that flips a boolean to true when it is notified.
+            final AtomicBoolean notified = new AtomicBoolean(false);
+            final SourceListener listener = new SourceListener() {
+                @Override
+                public void notifyCreate(final String ryaInstanceName, final QueryChangeLog log) {
+                    notified.set(true);
+                }
+
+                @Override
+                public void notifyDelete(final String ryaInstanceName) {
+                    notified.set(true);
+                }
+            };
+
+            // Register and then unregister it.
+            source.subscribe(listener);
+            source.unsubscribe(listener);
+
+            // Create a topic.
+            final String ryaInstance = UUID.randomUUID().toString();
+            final String topic = KafkaTopics.queryChangeLogTopic(ryaInstance);
+            kafka.createTopic(topic);
+
+            //Wait longer than the polling time for the listener to be notified.
+            Thread.sleep(300);
+
+            // Show the boolean was never flipped to true.
+            assertFalse(notified.get());
+        } finally {
+            source.stopAndWait();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/ee29450d/test/kafka/src/main/java/org/apache/rya/test/kafka/EmbeddedKafkaInstance.java
----------------------------------------------------------------------
diff --git a/test/kafka/src/main/java/org/apache/rya/test/kafka/EmbeddedKafkaInstance.java b/test/kafka/src/main/java/org/apache/rya/test/kafka/EmbeddedKafkaInstance.java
index c7c5929..3810d4f 100644
--- a/test/kafka/src/main/java/org/apache/rya/test/kafka/EmbeddedKafkaInstance.java
+++ b/test/kafka/src/main/java/org/apache/rya/test/kafka/EmbeddedKafkaInstance.java
@@ -75,6 +75,7 @@ public class EmbeddedKafkaInstance {
         brokerProps.setProperty(KafkaConfig$.MODULE$.PortProp(), brokerPort);
         brokerProps.setProperty(KafkaConfig$.MODULE$.ZkConnectProp(), zookeperConnect);
         brokerProps.setProperty(KafkaConfig$.MODULE$.LogDirsProp(), Files.createTempDirectory(getClass().getSimpleName() + "-").toAbsolutePath().toString());
+        brokerProps.setProperty(KafkaConfig$.MODULE$.DeleteTopicEnableProp(), "true");
         final KafkaConfig config = new KafkaConfig(brokerProps);
         final Time mock = new MockTime();
         kafkaServer = TestUtils.createServer(config, mock);

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/ee29450d/test/kafka/src/main/java/org/apache/rya/test/kafka/KafkaTestInstanceRule.java
----------------------------------------------------------------------
diff --git a/test/kafka/src/main/java/org/apache/rya/test/kafka/KafkaTestInstanceRule.java b/test/kafka/src/main/java/org/apache/rya/test/kafka/KafkaTestInstanceRule.java
index 252c288..50ba4ea 100644
--- a/test/kafka/src/main/java/org/apache/rya/test/kafka/KafkaTestInstanceRule.java
+++ b/test/kafka/src/main/java/org/apache/rya/test/kafka/KafkaTestInstanceRule.java
@@ -19,9 +19,15 @@
 package org.apache.rya.test.kafka;
 
 import java.util.Properties;
+import java.util.Set;
+import java.util.UUID;
 
 import org.I0Itec.zkclient.ZkClient;
 import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.serialization.StringDeserializer;
 import org.junit.rules.ExternalResource;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -97,6 +103,52 @@ public class KafkaTestInstanceRule extends ExternalResource {
     }
 
     /**
+     * Marks a topic for deletion. You may have to wait some time for the delete to actually complete.
+     *
+     * @param topicName - The topic that will be deleted. (not null)
+     */
+    public void deleteTopic(final String topicName) {
+        ZkUtils zkUtils = null;
+        try {
+            logger.info("Deleting Kafka Topic: '{}'", topicName);
+            zkUtils = ZkUtils.apply(new ZkClient(kafkaInstance.getZookeeperConnect(), 30000, 30000, ZKStringSerializer$.MODULE$), false);
+            AdminUtils.deleteTopic(zkUtils, topicName);
+        }
+        finally {
+            if(zkUtils != null) {
+                zkUtils.close();
+            }
+        }
+    }
+
+    /**
+     * Delete all of the topics that are in the embedded Kafka instance.
+     *
+     * @throws InterruptedException Interrupted while waiting for the topics to be deleted.
+     */
+    public void deleteAllTopics() throws InterruptedException {
+        // Setup the consumer that is used to list topics for the source.
+        final Properties consumerProperties = createBootstrapServerConfig();
+        consumerProperties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID().toString());
+        consumerProperties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+        consumerProperties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+
+        try(final Consumer<String, String> listTopicsConsumer = new KafkaConsumer<>(consumerProperties)) {
+            // Mark all existing topics for deletion.
+            Set<String> topics = listTopicsConsumer.listTopics().keySet();
+            for(final String topic : topics) {
+                deleteTopic(topic);
+            }
+
+            // Loop and wait until they are all gone.
+            while(!topics.isEmpty()) {
+                Thread.sleep(100);
+                topics = listTopicsConsumer.listTopics().keySet();
+            }
+        }
+    }
+
+    /**
      * @return A new Property object containing the correct value for Kafka's
      *         {@link CommonClientConfigs#BOOTSTRAP_SERVERS_CONFIG}.
      */


[09/22] incubator-rya git commit: RYA-456 Implement a Single Node implementation of QueryExecutor.

Posted by pu...@apache.org.
RYA-456 Implement a Single Node implementation of QueryExecutor.



Project: http://git-wip-us.apache.org/repos/asf/incubator-rya/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-rya/commit/a11ca4a2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-rya/tree/a11ca4a2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-rya/diff/a11ca4a2

Branch: refs/heads/master
Commit: a11ca4a2b1fd73ba754b1c2495b061e67c06ab0e
Parents: a31e256
Author: kchilton2 <ke...@gmail.com>
Authored: Fri Jan 26 15:55:59 2018 -0500
Committer: Valiyil <Pu...@parsons.com>
Committed: Fri Mar 9 12:59:45 2018 -0500

----------------------------------------------------------------------
 .../client/command/RunQueryCommandIT.java       |   3 +-
 .../rya/streams/kafka/KafkaStreamsFactory.java  |  57 ++++
 .../kafka/SingleThreadKafkaStreamsFactory.java  |  90 ++++++
 .../rya/streams/querymanager/QueryExecutor.java |  19 +-
 .../querymanager/kafka/LocalQueryExecutor.java  | 187 ++++++++++++
 .../kafka/LocalQueryExecutorIT.java             | 148 +++++++++
 .../kafka/LocalQueryExecutorTest.java           | 299 +++++++++++++++++++
 7 files changed, 795 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a11ca4a2/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
index 7e3b8bc..5d63f32 100644
--- a/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
+++ b/extras/rya.streams/client/src/test/java/org/apache/rya/streams/client/command/RunQueryCommandIT.java
@@ -91,7 +91,8 @@ public class RunQueryCommandIT {
     }
 
     @After
-    public void cleanup() throws Exception{
+    public void cleanup() throws Exception {
+        queryRepo.stopAndWait();
         stmtProducer.close();
         resultConsumer.close();
     }

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a11ca4a2/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaStreamsFactory.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaStreamsFactory.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaStreamsFactory.java
new file mode 100644
index 0000000..bd8ff1e
--- /dev/null
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/KafkaStreamsFactory.java
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.kafka;
+
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.rya.streams.api.entity.StreamsQuery;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * Builds {@link KafkaStreams} objects that are able to process a specific {@link StreamsQuery}.
+ */
+@DefaultAnnotation(NonNull.class)
+public interface KafkaStreamsFactory {
+
+    /**
+     * Builds a {@link KafkaStreams} object  that is able to process a specific {@link StreamsQuery}.
+     *
+     * @param ryaInstance - The Rya Instance the streams job is for. (not null)
+     * @param query - Defines the query that will be executed. (not null)
+     * @return A {@link KafkaStreams} object that will process the provided query.
+     * @throws KafkaStreamsFactoryException Unable to create a {@link KafkaStreams} object from the provided values.
+     */
+    public KafkaStreams make(String ryaInstance, StreamsQuery query) throws KafkaStreamsFactoryException;
+
+    /**
+     * A {@link KafkaStreamsFactory} could not create a {@link KafkaStreams} object.
+     */
+    public static class KafkaStreamsFactoryException extends Exception {
+        private static final long serialVersionUID = 1L;
+
+        public KafkaStreamsFactoryException(final String message) {
+            super(message);
+        }
+
+        public KafkaStreamsFactoryException(final String message, final Throwable cause) {
+            super(message, cause);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a11ca4a2/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
new file mode 100644
index 0000000..7ab7e90
--- /dev/null
+++ b/extras/rya.streams/kafka/src/main/java/org/apache/rya/streams/kafka/SingleThreadKafkaStreamsFactory.java
@@ -0,0 +1,90 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.kafka;
+
+import static java.util.Objects.requireNonNull;
+
+import java.util.Properties;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.kafka.streams.StreamsConfig;
+import org.apache.kafka.streams.processor.TopologyBuilder;
+import org.apache.rya.api.function.projection.RandomUUIDFactory;
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.kafka.topology.TopologyBuilderFactory;
+import org.apache.rya.streams.kafka.topology.TopologyBuilderFactory.TopologyBuilderException;
+import org.apache.rya.streams.kafka.topology.TopologyFactory;
+import org.openrdf.query.MalformedQueryException;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+
+/**
+ * Creates {@link KafkaStreams} objects that are able to process {@link StreamsQuery}s
+ * using a single thread of execution starting from the earliest point in within the
+ * input topic. The Application ID used by the client is based on the Query ID of the
+ * query that is being executed so that this job may resume where it left off if it
+ * is stopped.
+ */
+@DefaultAnnotation(NonNull.class)
+public class SingleThreadKafkaStreamsFactory implements KafkaStreamsFactory {
+
+    private final TopologyBuilderFactory topologyFactory = new TopologyFactory();
+
+    private final String bootstrapServersConfig;
+
+    /**
+     * Constructs an instance of {@link SingleThreadKafkaStreamsFactory}.
+     *
+     * @param bootstrapServersConfig - Configures which Kafka cluster the jobs will interact with. (not null)
+     */
+    public SingleThreadKafkaStreamsFactory(final String bootstrapServersConfig) {
+        this.bootstrapServersConfig = requireNonNull(bootstrapServersConfig);
+    }
+
+    @Override
+    public KafkaStreams make(final String ryaInstance, final StreamsQuery query) throws KafkaStreamsFactoryException {
+        requireNonNull(ryaInstance);
+        requireNonNull(query);
+
+        // Setup the Kafka Stream program.
+        final Properties streamsProps = new Properties();
+
+        // Configure the Kafka servers that will be talked to.
+        streamsProps.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServersConfig);
+
+        // Use the Query ID as the Application ID to ensure we resume where we left off the last time this command was run.
+        streamsProps.put(StreamsConfig.APPLICATION_ID_CONFIG, "RyaStreams-Query-" + query.getQueryId());
+
+        // Always start at the beginning of the input topic.
+        streamsProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+
+        // Setup the topology that processes the Query.
+        final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
+        final String resultsTopic = KafkaTopics.queryResultsTopic(query.getQueryId());
+
+        try {
+            final TopologyBuilder topologyBuilder = topologyFactory.build(query.getSparql(), statementsTopic, resultsTopic, new RandomUUIDFactory());
+            return new KafkaStreams(topologyBuilder, new StreamsConfig(streamsProps));
+        } catch (MalformedQueryException | TopologyBuilderException e) {
+            throw new KafkaStreamsFactoryException("Could not create a KafkaStreams processing topology for query " + query.getQueryId(), e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a11ca4a2/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
index 4572f08..bcee796 100644
--- a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/QueryExecutor.java
@@ -1,4 +1,4 @@
-/*
+/**
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -35,36 +35,41 @@ import edu.umd.cs.findbugs.annotations.NonNull;
  */
 @DefaultAnnotation(NonNull.class)
 public interface QueryExecutor extends Service {
+
     /**
      * Starts running a {@link StreamsQuery}.
      *
      * @param ryaInstanceName - The rya instance whose {@link Statement}s will be processed by the query. (not null)
      * @param query - The query to run. (not null)
      * @throws QueryExecutorException When the query fails to start.
+     * @throws IllegalStateException The service has not been started yet.
      */
-    public void startQuery(final String ryaInstanceName, final StreamsQuery query) throws QueryExecutorException;
+    public void startQuery(final String ryaInstanceName, final StreamsQuery query) throws QueryExecutorException, IllegalStateException;
 
     /**
      * Stops a {@link StreamsQuery}.
      *
      * @param queryID - The ID of the query to stop. (not null)
      * @throws QueryExecutorException When the query fails to stop.
+     * @throws IllegalStateException The service has not been started yet.
      */
-    public void stopQuery(final UUID queryID) throws QueryExecutorException;
+    public void stopQuery(final UUID queryID) throws QueryExecutorException, IllegalStateException;
 
     /**
      * Stops all {@link StreamsQuery} belonging to a specific rya instance.
      *
      * @param ryaInstanceName - The name of the rya instance to stop all queries for. (not null)
      * @throws QueryExecutorException When the queries fails to stop.
+     * @throws IllegalStateException The service has not been started yet.
      */
-    public void stopAll(final String ryaInstanceName) throws QueryExecutorException;
+    public void stopAll(final String ryaInstanceName) throws QueryExecutorException, IllegalStateException;
 
     /**
-     * @return - A set of {@link UUID}s representing the current active queries.
+     * @return A set of {@link UUID}s representing the current active queries.
      * @throws QueryExecutorException Can't discover which queries are currently running.
+     * @throws IllegalStateException The service has not been started yet.
      */
-    public Set<UUID> getRunningQueryIds() throws QueryExecutorException;
+    public Set<UUID> getRunningQueryIds() throws QueryExecutorException, IllegalStateException;
 
     /**
      * Exception to be used by {@link QueryExecutor} when queries fail to start or stop.
@@ -100,4 +105,4 @@ public interface QueryExecutor extends Service {
             super(cause);
         }
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a11ca4a2/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
new file mode 100644
index 0000000..947a215
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/main/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutor.java
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager.kafka;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.kafka.KafkaStreamsFactory;
+import org.apache.rya.streams.kafka.KafkaStreamsFactory.KafkaStreamsFactoryException;
+import org.apache.rya.streams.querymanager.QueryExecutor;
+
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Multimap;
+import com.google.common.util.concurrent.AbstractIdleService;
+
+import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
+import edu.umd.cs.findbugs.annotations.NonNull;
+import kafka.consumer.KafkaStream;
+
+/**
+ * A {@link QueryExecutor} that runs a {@link KafkaStreams} job within its own JVM every
+ * time {@link #startQuery(String, StreamsQuery)} is invoked.
+ * <p/>
+ * This executor may run out of JVM resources if it is used to execute too many queries.
+ */
+@DefaultAnnotation(NonNull.class)
+public class LocalQueryExecutor extends AbstractIdleService implements QueryExecutor {
+
+    /**
+     * Provides thread safety when interacting with this class.
+     */
+    public static ReentrantLock lock = new ReentrantLock();
+
+    /**
+     * Lookup the Rya Instance of a specific Query Id.
+     */
+    private final Map<UUID, String> ryaInstanceById = new HashMap<>();
+
+    /**
+     * Lookup the Query IDs that are running for a specific Rya Instance.
+     */
+    private final Multimap<String, UUID> idByRyaInstance = HashMultimap.create();
+
+    /**
+     * Lookup the executing {@link KafkaStreams} job for a running Query Id.
+     */
+    private final Map<UUID, KafkaStreams> byQueryId = new HashMap<>();
+
+    /**
+     * Builds the {@link KafkaStreams} objects that execute {@link KafkaStream}s.
+     */
+    private final KafkaStreamsFactory streamsFactory;
+
+    /**
+     * Constructs an instance of {@link LocalQueryExecutor}.
+     *
+     * @param streamsFactory - Builds the {@link KafkaStreams} objects that execute {@link KafkaStream}s. (not null)
+     */
+    public LocalQueryExecutor(final KafkaStreamsFactory streamsFactory) {
+        this.streamsFactory = requireNonNull(streamsFactory);
+    }
+
+    @Override
+    protected void startUp() throws Exception {
+        // Nothing to do.
+    }
+
+    @Override
+    protected void shutDown() throws Exception {
+        // Stop all of the running queries.
+        for(final KafkaStreams job : byQueryId.values()) {
+            job.close();
+        }
+    }
+
+    @Override
+    public void startQuery(final String ryaInstance, final StreamsQuery query) throws QueryExecutorException {
+        requireNonNull(ryaInstance);
+        requireNonNull(query);
+        checkState(state() == State.RUNNING, "The service must be RUNNING to execute this method.");
+
+        lock.lock();
+        try {
+            // Setup the Kafka Streams job that will execute.
+            final KafkaStreams streams = streamsFactory.make(ryaInstance, query);
+            streams.start();
+
+            // Mark which Rya Instance the Query ID is for.
+            ryaInstanceById.put(query.getQueryId(), ryaInstance);
+
+            // Add the Query ID to the collection of running queries for the Rya instance.
+            idByRyaInstance.put(ryaInstance, query.getQueryId());
+
+            // Add the running Kafka Streams job for the Query ID.
+            byQueryId.put(query.getQueryId(), streams);
+
+        } catch (final KafkaStreamsFactoryException e) {
+            throw new QueryExecutorException("Could not start query " + query.getQueryId(), e);
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    public void stopQuery(final UUID queryId) throws QueryExecutorException {
+        requireNonNull(queryId);
+        checkState(state() == State.RUNNING, "The service must be RUNNING to execute this method.");
+
+        lock.lock();
+        try {
+            if(byQueryId.containsKey(queryId)) {
+                // Stop the job from running.
+                final KafkaStreams streams = byQueryId.get(queryId);
+                streams.close();
+
+                // Remove it from the Rya Instance Name lookup.
+                final String ryaInstance = ryaInstanceById.remove(queryId);
+
+                // Remove it from the collection of running queries for the Rya Instance.
+                idByRyaInstance.remove(ryaInstance, queryId);
+
+                // Remove it from the running Kafka Streams job lookup.
+                byQueryId.remove(queryId);
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    public void stopAll(final String ryaInstanceName) throws QueryExecutorException {
+        requireNonNull(ryaInstanceName);
+        checkState(state() == State.RUNNING, "The service must be RUNNING to execute this method.");
+
+        lock.lock();
+        try {
+            if(idByRyaInstance.containsKey(ryaInstanceName)) {
+                // A defensive copy of the queries so that we may remove them from the maps.
+                final Set<UUID> queryIds = new HashSet<>( idByRyaInstance.get(ryaInstanceName) );
+
+                // Stop each of them.
+                for(final UUID queryId : queryIds) {
+                    stopQuery(queryId);
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    @Override
+    public Set<UUID> getRunningQueryIds() throws QueryExecutorException {
+        lock.lock();
+        checkState(state() == State.RUNNING, "The service must be RUNNING to execute this method.");
+
+        try {
+            return new HashSet<>( byQueryId.keySet() );
+        } finally {
+            lock.unlock();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a11ca4a2/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
new file mode 100644
index 0000000..3cbe894
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorIT.java
@@ -0,0 +1,148 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager.kafka;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.rya.api.model.VisibilityBindingSet;
+import org.apache.rya.api.model.VisibilityStatement;
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.api.interactor.LoadStatements;
+import org.apache.rya.streams.kafka.KafkaStreamsFactory;
+import org.apache.rya.streams.kafka.KafkaTopics;
+import org.apache.rya.streams.kafka.SingleThreadKafkaStreamsFactory;
+import org.apache.rya.streams.kafka.interactor.KafkaLoadStatements;
+import org.apache.rya.streams.kafka.serialization.VisibilityBindingSetDeserializer;
+import org.apache.rya.streams.kafka.serialization.VisibilityStatementSerializer;
+import org.apache.rya.streams.querymanager.QueryExecutor;
+import org.apache.rya.test.kafka.KafkaTestInstanceRule;
+import org.apache.rya.test.kafka.KafkaTestUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.openrdf.model.ValueFactory;
+import org.openrdf.model.impl.ValueFactoryImpl;
+import org.openrdf.query.impl.MapBindingSet;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Integration tests the methods of {@link LocalQueryExecutor}.
+ */
+public class LocalQueryExecutorIT {
+
+    private final String ryaInstance = UUID.randomUUID().toString();
+
+    private Producer<String, VisibilityStatement> stmtProducer = null;
+    private Consumer<String, VisibilityBindingSet> resultConsumer = null;
+
+    @Rule
+    public KafkaTestInstanceRule kafka = new KafkaTestInstanceRule(false);
+
+    @Before
+    public void setup() {
+        // Make sure the topic that the change log uses exists.
+        final String changeLogTopic = KafkaTopics.queryChangeLogTopic("" + ryaInstance);
+        kafka.createTopic(changeLogTopic);
+
+        // Initialize the Statements Producer and the Results Consumer.
+        stmtProducer = KafkaTestUtil.makeProducer(kafka, StringSerializer.class, VisibilityStatementSerializer.class);
+        resultConsumer = KafkaTestUtil.fromStartConsumer(kafka, StringDeserializer.class, VisibilityBindingSetDeserializer.class);
+    }
+
+    @After
+    public void cleanup() throws Exception {
+        stmtProducer.close();
+        resultConsumer.close();
+    }
+
+    @Test
+    public void runQuery() throws Exception {
+        // Test values.
+        final String ryaInstance = "rya";
+        final StreamsQuery sQuery = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?person <urn:worksAt> ?business . }", true);
+
+        // Create the statements that will be loaded.
+        final ValueFactory vf = new ValueFactoryImpl();
+        final List<VisibilityStatement> statements = new ArrayList<>();
+        statements.add(new VisibilityStatement(vf.createStatement(
+                vf.createURI("urn:Alice"),
+                vf.createURI("urn:worksAt"),
+                vf.createURI("urn:BurgerJoint")), "a"));
+        statements.add(new VisibilityStatement(vf.createStatement(
+                vf.createURI("urn:Bob"),
+                vf.createURI("urn:worksAt"),
+                vf.createURI("urn:TacoShop")), "a"));
+        statements.add(new VisibilityStatement(vf.createStatement(
+                vf.createURI("urn:Charlie"),
+                vf.createURI("urn:worksAt"),
+                vf.createURI("urn:TacoShop")), "a"));
+
+        // Create the expected results.
+        final List<VisibilityBindingSet> expected = new ArrayList<>();
+        MapBindingSet bs = new MapBindingSet();
+        bs.addBinding("person", vf.createURI("urn:Alice"));
+        bs.addBinding("business", vf.createURI("urn:BurgerJoint"));
+        expected.add(new VisibilityBindingSet(bs, "a"));
+        bs = new MapBindingSet();
+        bs.addBinding("person", vf.createURI("urn:Bob"));
+        bs.addBinding("business", vf.createURI("urn:TacoShop"));
+        expected.add(new VisibilityBindingSet(bs, "a"));
+        bs = new MapBindingSet();
+        bs.addBinding("person", vf.createURI("urn:Charlie"));
+        bs.addBinding("business", vf.createURI("urn:TacoShop"));
+        expected.add(new VisibilityBindingSet(bs, "a"));
+
+        // Start the executor that will be tested.
+        final String kafkaServers = kafka.getKafkaHostname() + ":" + kafka.getKafkaPort();
+        final KafkaStreamsFactory jobFactory = new SingleThreadKafkaStreamsFactory(kafkaServers);
+        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        executor.startAndWait();
+        try {
+            // Start the query.
+            executor.startQuery(ryaInstance, sQuery);
+
+            // Wait for the program to start.
+            Thread.sleep(5000);
+
+            // Write some statements to the program.
+            final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
+            final LoadStatements loadStatements = new KafkaLoadStatements(statementsTopic, stmtProducer);
+            loadStatements.fromCollection(statements);
+
+            // Read the output of the streams program.
+            final String resultsTopic = KafkaTopics.queryResultsTopic(sQuery.getQueryId());
+            resultConsumer.subscribe( Lists.newArrayList(resultsTopic) );
+            final List<VisibilityBindingSet> results = KafkaTestUtil.pollForResults(500, 6, 3, resultConsumer);
+            assertEquals(expected, results);
+
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-rya/blob/a11ca4a2/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
----------------------------------------------------------------------
diff --git a/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
new file mode 100644
index 0000000..0df5794
--- /dev/null
+++ b/extras/rya.streams/query-manager/src/test/java/org/apache/rya/streams/querymanager/kafka/LocalQueryExecutorTest.java
@@ -0,0 +1,299 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.rya.streams.querymanager.kafka;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Set;
+import java.util.UUID;
+
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.rya.streams.api.entity.StreamsQuery;
+import org.apache.rya.streams.kafka.KafkaStreamsFactory;
+import org.apache.rya.streams.querymanager.QueryExecutor;
+import org.junit.Test;
+
+import com.google.common.collect.Sets;
+
+/**
+ * Unit tests the methods of {@link LocalQueryExecutor}.
+ */
+public class LocalQueryExecutorTest {
+
+    @Test(expected = IllegalStateException.class)
+    public void startQuery_serviceNotStarted() throws Exception {
+        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        executor.startQuery("rya", new StreamsQuery(UUID.randomUUID(), "query", true));
+    }
+
+    @Test
+    public void startQuery() throws Exception {
+        // Test values.
+        final String ryaInstance = "rya";
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+
+        // Mock the streams factory so that we can tell if the start function is invoked by the executor.
+        final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
+        final KafkaStreams queryJob = mock(KafkaStreams.class);
+        when(jobFactory.make(eq(ryaInstance), eq(query))).thenReturn(queryJob);
+
+        // Start the executor that will be tested.
+        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        executor.startAndWait();
+        try {
+            // Tell the executor to start the query.
+            executor.startQuery(ryaInstance, query);
+
+            // Show a job was started for that query's ID.
+            verify(queryJob).start();
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+
+    @Test(expected = IllegalStateException.class)
+    public void stopQuery_serviceNotStarted() throws Exception {
+        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        executor.stopQuery(UUID.randomUUID());
+    }
+
+    @Test
+    public void stopQuery_queryNotRunning() throws Exception {
+        // Start an executor.
+        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        executor.startAndWait();
+        try {
+            // Try to stop a query that was never stareted.
+            executor.stopQuery(UUID.randomUUID());
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+
+    @Test
+    public void stopQuery() throws Exception {
+        // Test values.
+        final String ryaInstance = "rya";
+        final StreamsQuery query = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+
+        // Mock the streams factory so that we can tell if the stop function is invoked by the executor.
+        final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
+        final KafkaStreams queryJob = mock(KafkaStreams.class);
+        when(jobFactory.make(eq(ryaInstance), eq(query))).thenReturn(queryJob);
+
+        // Start the executor that will be tested.
+        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        executor.startAndWait();
+        try {
+            // Tell the executor to start the query.
+            executor.startQuery(ryaInstance, query);
+
+            // Tell the executor to stop the query.
+            executor.stopQuery(query.getQueryId());
+
+            // Show a job was stopped for that query's ID.
+            verify(queryJob).close();
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+
+    @Test(expected = IllegalStateException.class)
+    public void stopAll_serviceNotStarted() throws Exception {
+        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        executor.stopAll("rya");
+    }
+
+    @Test
+    public void stopAll_noneForThatRyaInstance() throws Exception {
+        // Test values.
+        final String ryaInstance = "rya";
+        final StreamsQuery query1= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query2= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+
+        // Mock the streams factory so that we can tell if the stop function is invoked by the executor.
+        final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
+        final KafkaStreams queryJob1 = mock(KafkaStreams.class);
+        final KafkaStreams queryJob2 = mock(KafkaStreams.class);
+        when(jobFactory.make(eq(ryaInstance), eq(query1))).thenReturn(queryJob1);
+        when(jobFactory.make(eq(ryaInstance), eq(query2))).thenReturn(queryJob2);
+
+        // Start the executor that will be tested.
+        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        executor.startAndWait();
+        try {
+            // Tell the executor to start the queries.
+            executor.startQuery(ryaInstance, query1);
+            executor.startQuery(ryaInstance, query2);
+
+            // Verify both are running.
+            verify(queryJob1).start();
+            verify(queryJob2).start();
+
+            // Tell the executor to stop queries running under rya2.
+            executor.stopAll("someOtherRyaInstance");
+
+            // Show none of the queries were stopped.
+            verify(queryJob1, never()).close();
+            verify(queryJob2, never()).close();
+
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+
+    @Test
+    public void stopAll() throws Exception {
+        // Test values.
+        final String ryaInstance1 = "rya1";
+        final StreamsQuery query1= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final String ryaInstance2 = "rya2";
+        final StreamsQuery query2= new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+
+        // Mock the streams factory so that we can tell if the stop function is invoked by the executor.
+        final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
+        final KafkaStreams queryJob1 = mock(KafkaStreams.class);
+        when(jobFactory.make(eq(ryaInstance1), eq(query1))).thenReturn(queryJob1);
+        final KafkaStreams queryJob2 = mock(KafkaStreams.class);
+        when(jobFactory.make(eq(ryaInstance2), eq(query2))).thenReturn(queryJob2);
+
+        // Start the executor that will be tested.
+        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        executor.startAndWait();
+        try {
+            // Tell the executor to start the queries.
+            executor.startQuery(ryaInstance1, query1);
+            executor.startQuery(ryaInstance2, query2);
+
+            // Verify both are running.
+            verify(queryJob1).start();
+            verify(queryJob2).start();
+
+            // Tell the executor to stop queries running under rya2.
+            executor.stopAll(ryaInstance2);
+
+            // Show the first query is still running, but the second isn't.
+            verify(queryJob1, never()).close();
+            verify(queryJob2).close();
+
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+
+    @Test(expected = IllegalStateException.class)
+    public void getRunningQueryIds_serviceNotStarted() throws Exception {
+        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        executor.getRunningQueryIds();
+    }
+
+    @Test
+    public void getRunningQueryIds_noneStarted() throws Exception {
+        // Start an executor.
+        final QueryExecutor executor = new LocalQueryExecutor(mock(KafkaStreamsFactory.class));
+        executor.startAndWait();
+        try {
+            // Get the list of running queries.
+            final Set<UUID> runningQueries = executor.getRunningQueryIds();
+
+            // Show no queries are reported as running.
+            assertTrue(runningQueries.isEmpty());
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+
+    @Test
+    public void getRunningQueryIds_noneStopped() throws Exception {
+        // Test values.
+        final String ryaInstance = "rya";
+        final StreamsQuery query1 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query2 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query3 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+
+        // Mock the streams factory so that we can figure out what is started.
+        final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
+        when(jobFactory.make(eq(ryaInstance), eq(query1))).thenReturn(mock(KafkaStreams.class));
+        when(jobFactory.make(eq(ryaInstance), eq(query2))).thenReturn(mock(KafkaStreams.class));
+        when(jobFactory.make(eq(ryaInstance), eq(query3))).thenReturn(mock(KafkaStreams.class));
+
+        // Start the executor that will be tested.
+        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        executor.startAndWait();
+        try {
+            // Start the queries.
+            executor.startQuery(ryaInstance, query1);
+            executor.startQuery(ryaInstance, query2);
+            executor.startQuery(ryaInstance, query3);
+
+            // All of those query IDs should be reported as running.
+            final Set<UUID> expected = Sets.newHashSet(
+                    query1.getQueryId(),
+                    query2.getQueryId(),
+                    query3.getQueryId());
+            assertEquals(expected, executor.getRunningQueryIds());
+
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+
+    @Test
+    public void getRunningQueryIds_stoppedNoLongerListed() throws Exception {
+        // Test values.
+        final String ryaInstance = "rya";
+        final StreamsQuery query1 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query2 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+        final StreamsQuery query3 = new StreamsQuery(UUID.randomUUID(), "SELECT * WHERE { ?a ?b ?c. }", true);
+
+        // Mock the streams factory so that we can figure out what is started.
+        final KafkaStreamsFactory jobFactory = mock(KafkaStreamsFactory.class);
+        when(jobFactory.make(eq(ryaInstance), eq(query1))).thenReturn(mock(KafkaStreams.class));
+        when(jobFactory.make(eq(ryaInstance), eq(query2))).thenReturn(mock(KafkaStreams.class));
+        when(jobFactory.make(eq(ryaInstance), eq(query3))).thenReturn(mock(KafkaStreams.class));
+
+        // Start the executor that will be tested.
+        final QueryExecutor executor = new LocalQueryExecutor(jobFactory);
+        executor.startAndWait();
+        try {
+            // Start the queries.
+            executor.startQuery(ryaInstance, query1);
+            executor.startQuery(ryaInstance, query2);
+            executor.startQuery(ryaInstance, query3);
+
+            // Stop the second query.
+            executor.stopQuery(query2.getQueryId());
+
+            // Only the first and third queries are running.
+            final Set<UUID> expected = Sets.newHashSet(
+                    query1.getQueryId(),
+                    query3.getQueryId());
+            assertEquals(expected, executor.getRunningQueryIds());
+
+        } finally {
+            executor.stopAndWait();
+        }
+    }
+}
\ No newline at end of file