Parcourir la source

AMBARI-16963: JDBC implementation of hive view. (dipayanb)

Dipayan Bhowmick il y a 9 ans
Parent
commit
f3df025227
100 fichiers modifiés avec 7159 ajouts et 0 suppressions
  1. 369 0
      contrib/views/hive-next/pom.xml
  2. 54 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/BaseService.java
  3. 40 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/ConnectionDelegate.java
  4. 123 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/ConnectionFactory.java
  5. 100 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/ConnectionSystem.java
  6. 118 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/HelpService.java
  7. 144 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/HiveJdbcConnectionDelegate.java
  8. 50 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/HiveViewImpl.java
  9. 98 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/PropertyValidator.java
  10. 36 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/TestBean.java
  11. 192 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/AsyncJdbcConnector.java
  12. 92 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/AsyncQueryExecutor.java
  13. 54 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/DeathWatch.java
  14. 47 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/GetResultHolder.java
  15. 51 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/HiveActor.java
  16. 305 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/JdbcConnector.java
  17. 109 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/LogAggregator.java
  18. 438 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/OperationController.java
  19. 219 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/ResultSetIterator.java
  20. 174 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/SyncJdbcConnector.java
  21. 32 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/YarnAtsParser.java
  22. 32 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AdvanceCursor.java
  23. 48 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AssignResultSet.java
  24. 46 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AssignStatement.java
  25. 52 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AsyncJob.java
  26. 56 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/Connect.java
  27. 22 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/CursorReset.java
  28. 73 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/DDLJob.java
  29. 38 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ExecuteJob.java
  30. 23 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ExecuteQuery.java
  31. 42 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/FetchError.java
  32. 42 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/FetchResult.java
  33. 60 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/GetColumnMetadataJob.java
  34. 22 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/GetMoreLogs.java
  35. 63 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/HiveJob.java
  36. 53 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/HiveMessage.java
  37. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/JobExecutionCompleted.java
  38. 44 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/JobRejected.java
  39. 38 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/JobSubmitted.java
  40. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/LogAggregationFinished.java
  41. 34 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/RegisterActor.java
  42. 22 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ResetCursor.java
  43. 47 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ResultReady.java
  44. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/StartLogAggregation.java
  45. 27 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/SyncJob.java
  46. 46 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/AsyncExecutionFailed.java
  47. 31 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/ExecutionFailed.java
  48. 37 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/Failure.java
  49. 31 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/FetchFailed.java
  50. 22 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/Next.java
  51. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/NoMoreItems.java
  52. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/NoResult.java
  53. 43 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/Result.java
  54. 33 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/ResultSetHolder.java
  55. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/CleanUp.java
  56. 52 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/DestroyConnector.java
  57. 53 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/FreeConnector.java
  58. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/InactivityCheck.java
  59. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/KeepAlive.java
  60. 21 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/TerminateInactivityCheck.java
  61. 84 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/backgroundjobs/BackgroundJobController.java
  62. 36 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/AsyncJobRunner.java
  63. 115 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/AsyncJobRunnerImpl.java
  64. 45 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ColumnDescription.java
  65. 74 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ColumnDescriptionExtended.java
  66. 53 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ColumnDescriptionShort.java
  67. 51 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ConnectionConfig.java
  68. 30 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/Cursor.java
  69. 36 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/DDLDelegator.java
  70. 242 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/DDLDelegatorImpl.java
  71. 110 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/EmptyCursor.java
  72. 31 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveAuthCredentials.java
  73. 27 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveAuthRequiredException.java
  74. 25 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveClientAuthRequiredException.java
  75. 25 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveClientException.java
  76. 25 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveClientRuntimeException.java
  77. 153 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/NonPersistentCursor.java
  78. 87 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/PersistentCursor.java
  79. 74 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/Row.java
  80. 28 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/exceptions/NotConnectedException.java
  81. 23 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/AsyncExecutionFailure.java
  82. 25 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/AsyncExecutionSuccess.java
  83. 59 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/Connectable.java
  84. 25 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ConnectionException.java
  85. 94 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ConnectionProperties.java
  86. 37 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ConnectionSupplier.java
  87. 37 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ContextSupplier.java
  88. 42 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/DataStorageSupplier.java
  89. 62 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/DefaultSupplier.java
  90. 78 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/Either.java
  91. 59 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HdfsApiSupplier.java
  92. 109 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveConnectionWrapper.java
  93. 71 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveQuery.java
  94. 160 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveResult.java
  95. 53 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveTask.java
  96. 118 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveTaskMessage.java
  97. 172 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/DataStoreStorage.java
  98. 23 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/IStorageFactory.java
  99. 132 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/InstanceKeyValueStorage.java
  100. 163 0
      contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/KeyValueStorage.java

+ 369 - 0
contrib/views/hive-next/pom.xml

@@ -0,0 +1,369 @@
+<!--
+   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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.ambari.contrib.views</groupId>
+  <artifactId>hive-jdbc</artifactId>
+  <version>2.0.0.0-SNAPSHOT</version>
+  <name>Hive</name>
+
+  <parent>
+    <groupId>org.apache.ambari.contrib.views</groupId>
+    <artifactId>ambari-contrib-views</artifactId>
+    <version>2.0.0.0-SNAPSHOT</version>
+  </parent>
+
+  <repositories>
+    <repository>
+      <id>repository.apache.org</id>
+      <name>Apache Snapshot repo</name>
+      <url>https://repository.apache.org/content/groups/snapshots</url>
+    </repository>
+  </repositories>
+
+  <dependencies>
+    <dependency>
+      <groupId>com.jayway.jsonpath</groupId>
+      <artifactId>json-path</artifactId>
+      <version>2.0.0</version>
+    </dependency>
+      <dependency>
+      <groupId>com.google.inject</groupId>
+      <artifactId>guice</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>com.sun.jersey.contribs</groupId>
+      <artifactId>jersey-multipart</artifactId>
+      <version>1.18</version>
+    </dependency>
+    <dependency>
+      <groupId>com.sun.jersey</groupId>
+      <artifactId>jersey-client</artifactId>
+      <version>1.8</version>
+    </dependency>
+    <dependency>
+      <groupId>com.sun.jersey</groupId>
+      <artifactId>jersey-core</artifactId>
+      <version>1.18.1</version>
+    </dependency>
+    <dependency>
+      <groupId>com.sun.jersey</groupId>
+      <artifactId>jersey-json</artifactId>
+      <version>1.9</version>
+    </dependency>
+    <dependency>
+      <groupId>com.googlecode.json-simple</groupId>
+      <artifactId>json-simple</artifactId>
+      <version>1.1.1</version>
+    </dependency>
+    <dependency>
+      <groupId>commons-configuration</groupId>
+      <artifactId>commons-configuration</artifactId>
+      <version>1.6</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-csv</artifactId>
+      <version>1.0</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-collections4</artifactId>
+      <version>4.0</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.ambari</groupId>
+      <artifactId>ambari-views</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>com.google.code.gson</groupId>
+      <artifactId>gson</artifactId>
+      <version>2.2.2</version>
+    </dependency>
+    <dependency>
+      <groupId>javax.servlet</groupId>
+      <artifactId>javax.servlet-api</artifactId>
+      <version>3.0.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-api</artifactId>
+      <version>1.7.5</version>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-simple</artifactId>
+      <version>1.7.5</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-hdfs</artifactId>
+      <version>${hadoop.version}</version>
+        <exclusions>
+            <exclusion>
+                <groupId>tomcat</groupId>
+                <artifactId>jasper-runtime</artifactId>
+            </exclusion>
+        </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-common</artifactId>
+      <version>${hadoop.version}</version>
+        <exclusions>
+            <exclusion>
+                <groupId>tomcat</groupId>
+                <artifactId>jasper-runtime</artifactId>
+            </exclusion>
+        </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-mapreduce-client-common</artifactId>
+      <version>${hadoop.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-mapreduce-client-core</artifactId>
+      <version>${hadoop.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-yarn-client</artifactId>
+      <version>${hadoop.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>javax.ws.rs</groupId>
+      <artifactId>javax.ws.rs-api</artifactId>
+      <version>2.0</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hive</groupId>
+      <artifactId>hive-jdbc</artifactId>
+      <version>${hive-version}</version>
+    </dependency>
+    <dependency>
+      <groupId>commons-cli</groupId>
+      <artifactId>commons-cli</artifactId>
+      <version>1.2</version>
+    </dependency>
+    <dependency>
+      <groupId>commons-lang</groupId>
+      <artifactId>commons-lang</artifactId>
+      <version>2.2</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.thrift</groupId>
+      <artifactId>libthrift</artifactId>
+      <version>0.9.0</version>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.easymock</groupId>
+      <artifactId>easymock</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>com.typesafe.akka</groupId>
+      <artifactId>akka-testkit_2.11</artifactId>
+      <version>2.3.15</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-minicluster</artifactId>
+      <version>${hadoop.version}</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.ambari.contrib.views</groupId>
+      <artifactId>ambari-views-utils</artifactId>
+      <version>2.0.0.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>commons-validator</groupId>
+      <artifactId>commons-validator</artifactId>
+      <version>1.4.0</version>
+    </dependency>
+    <dependency>
+      <groupId>commons-io</groupId>
+      <artifactId>commons-io</artifactId>
+      <version>2.4</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.httpcomponents</groupId>
+      <artifactId>httpclient</artifactId>
+      <version>4.5.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.httpcomponents</groupId>
+      <artifactId>httpcore</artifactId>
+      <version>4.4.3</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-csv</artifactId>
+      <version>1.1</version>
+    </dependency>
+    <dependency>
+      <groupId>com.typesafe.akka</groupId>
+      <artifactId>akka-actor_2.11</artifactId>
+      <version>2.3.15</version>
+    </dependency>
+  </dependencies>
+
+  <properties>
+    <ambari.dir>${project.parent.parent.parent.basedir}</ambari.dir>
+    <hive-version>2.1.0-SNAPSHOT</hive-version>
+    <ambari.version>1.3.0.0-SNAPSHOT</ambari.version>
+  </properties>
+  <build>
+    <plugins>
+
+      <!-- Building frontend -->
+      <plugin>
+        <groupId>com.github.eirslett</groupId>
+        <artifactId>frontend-maven-plugin</artifactId>
+        <version>0.0.16</version>
+        <configuration>
+          <nodeVersion>v0.12.2</nodeVersion>
+          <npmVersion>1.4.8</npmVersion>
+          <workingDirectory>src/main/resources/ui/hive-web/</workingDirectory>
+        </configuration>
+        <executions>
+          <execution>
+            <id>install node and npm</id>
+            <phase>generate-sources</phase>
+            <goals>
+              <goal>install-node-and-npm</goal>
+            </goals>
+          </execution>
+          <execution>
+            <id>npm install</id>
+            <phase>generate-sources</phase>
+            <goals>
+              <goal>npm</goal>
+            </goals>
+            <configuration>
+              <arguments>install --python="${project.basedir}/../src/main/unix/ambari-python-wrap" --unsafe-perm</arguments>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <artifactId>exec-maven-plugin</artifactId>
+        <groupId>org.codehaus.mojo</groupId>
+        <version>1.3.2</version>
+        <executions>
+          <execution>
+            <id>Hive build</id>
+            <phase>generate-sources</phase>
+            <goals>
+              <goal>exec</goal>
+            </goals>
+            <configuration>
+              <workingDirectory>${basedir}/src/main/resources/ui/hive-web</workingDirectory>
+              <executable>node/node</executable>
+              <arguments>
+                <argument>node_modules/.bin/ember</argument>
+                <argument>build</argument>
+              </arguments>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <version>3.1</version>
+        <configuration>
+          <source>1.7</source>
+          <target>1.7</target>
+        </configuration>
+      </plugin>
+      <plugin>
+        <artifactId>maven-dependency-plugin</artifactId>
+        <executions>
+          <execution>
+            <phase>generate-resources</phase>
+            <goals>
+              <goal>copy-dependencies</goal>
+            </goals>
+            <configuration>
+              <outputDirectory>${project.build.directory}/lib</outputDirectory>
+              <includeScope>runtime</includeScope>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+       <groupId>org.vafer</groupId>
+       <artifactId>jdeb</artifactId>
+       <version>1.0.1</version>
+       <executions>
+           <execution>
+               <phase>none</phase>
+               <goals>
+                   <goal>jdeb</goal>
+               </goals>
+           </execution>
+       </executions>
+       <configuration>
+           <submodules>false</submodules>
+       </configuration>
+     </plugin>
+    </plugins>
+    <resources>
+      <resource>
+        <directory>src/main/resources</directory>
+        <filtering>false</filtering>
+        <includes>
+          <include>META-INF/**/*</include>
+          <include>view.xml</include>
+          <include>view.log4j.properties</include>
+          <include>application.conf</include>
+        </includes>
+      </resource>
+      <resource>
+        <directory>src/main/resources/ui/hive-web/dist</directory>
+        <filtering>false</filtering>
+      </resource>
+      <resource>
+        <directory>src/main/resources/ui/hive-web/bower_components/polestar</directory>
+        <filtering>false</filtering>
+        <targetPath>polestar</targetPath>
+      </resource>
+      <resource>
+        <directory>src/main/resources/ui/hive-web/bower_components/voyager</directory>
+        <filtering>false</filtering>
+        <targetPath>voyager</targetPath>
+      </resource>
+      <resource>
+        <targetPath>WEB-INF/lib</targetPath>
+        <filtering>false</filtering>
+        <directory>target/lib</directory>
+      </resource>
+    </resources>
+  </build>
+</project>

+ 54 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/BaseService.java

@@ -0,0 +1,54 @@
+/**
+ * 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.ambari.view.hive2;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.utils.SharedObjectsFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Inject;
+
+
+/**
+ * Parent service
+ */
+public class BaseService {
+  @Inject
+  protected ViewContext context;
+
+  protected final static Logger LOG =
+      LoggerFactory.getLogger(BaseService.class);
+
+  private SharedObjectsFactory sharedObjectsFactory;
+  public SharedObjectsFactory getSharedObjectsFactory() {
+    if (sharedObjectsFactory == null) {
+      sharedObjectsFactory = new SharedObjectsFactory(context);
+    }
+    return sharedObjectsFactory;
+  }
+
+  public void setSharedObjectsFactory(SharedObjectsFactory sharedObjectsFactory) {
+    this.sharedObjectsFactory = sharedObjectsFactory;
+  }
+
+  public BaseService() {
+//    Thread.currentThread().setContextClassLoader(null);
+  }
+}

+ 40 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/ConnectionDelegate.java

@@ -0,0 +1,40 @@
+/*
+ * 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.ambari.view.hive2;
+
+import com.google.common.base.Optional;
+import org.apache.ambari.view.hive2.actor.message.DDLJob;
+import org.apache.ambari.view.hive2.actor.message.GetColumnMetadataJob;
+import org.apache.ambari.view.hive2.actor.message.HiveJob;
+import org.apache.ambari.view.hive2.internal.HiveResult;
+import org.apache.hive.jdbc.HiveConnection;
+import org.apache.hive.jdbc.HiveStatement;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+public interface ConnectionDelegate {
+  Optional<ResultSet> execute(HiveConnection connection, DDLJob job) throws SQLException;
+  Optional<ResultSet> executeSync(HiveConnection connection, DDLJob job) throws SQLException;
+  Optional<ResultSet> getColumnMetadata(HiveConnection connection, GetColumnMetadataJob job) throws SQLException;
+  Optional<ResultSet> getCurrentResultSet();
+  Optional<HiveStatement> getCurrentStatement();
+  void closeResultSet();
+  void closeStatement();
+}

+ 123 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/ConnectionFactory.java

@@ -0,0 +1,123 @@
+/*
+ * 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.ambari.view.hive2;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.collect.FluentIterable;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.client.ConnectionConfig;
+
+import java.util.List;
+
+public class ConnectionFactory {
+
+  private static String ZK_HIVE_DYN_SERVICE_DISCOVERY_KEY = "hive.server2.support.dynamic.service.discovery";
+  private static String ZK_HIVE_NAMESPACE_KEY = "hive.server2.zookeeper.namespace";
+  private static String ZK_HIVE_QUORUM = "hive.zookeeper.quorum";
+
+  private static String AMBARI_HIVE_SERVICE_NAME = "HIVE";
+  private static String AMBARI_HIVESERVER_COMPONENT_NAME = "HIVE_SERVER";
+
+  private static String HIVE_SITE = "hive-site";
+  private static String HIVE_INTERACTIVE_SITE = "hive-interactive-site";
+
+  private static String HIVE_JDBC_URL_KEY = "hive.jdbc.url";
+  private static final String HIVE_SESSION_PARAMS = "hive.session.params";
+
+  private static String BINARY_PORT_KEY = "hive.server2.thrift.port";
+  private static String HTTP_PORT_KEY = "hive.server2.thrift.http.port";
+  private static String HIVE_TRANSPORT_MODE_KEY = "hive.server2.transport.mode";
+  private static String HTTP_PATH_KEY = "hive.server2.thrift.http.path";
+
+
+  public static ConnectionConfig create(ViewContext context) {
+    String jdbcUrl;
+    if (context.getCluster() == null) {
+      jdbcUrl = getConnectFromCustom(context);
+    } else {
+      if (zookeeperConfigured(context)) {
+        jdbcUrl = getFromClusterZookeeperConfig(context);
+      } else {
+        jdbcUrl = getFromHiveConfiguration(context);
+      }
+    }
+
+    String userName = context.getUsername();
+    return new ConnectionConfig(userName, "", jdbcUrl);
+  }
+
+  private static String getFromHiveConfiguration(ViewContext context) {
+    String transportMode = context.getCluster().getConfigurationValue(HIVE_SITE, HIVE_TRANSPORT_MODE_KEY);
+    String binaryPort = context.getCluster().getConfigurationValue(HIVE_SITE, BINARY_PORT_KEY);
+    String httpPort = context.getCluster().getConfigurationValue(HIVE_SITE, HTTP_PORT_KEY);
+    String pathKey = context.getCluster().getConfigurationValue(HIVE_SITE, HTTP_PATH_KEY);
+    List<String> hiveHosts = context.getCluster().getHostsForServiceComponent(AMBARI_HIVE_SERVICE_NAME, AMBARI_HIVESERVER_COMPONENT_NAME);
+    String sessionParams = context.getProperties().get(HIVE_SESSION_PARAMS);
+
+    boolean isBinary = transportMode.equalsIgnoreCase("binary");
+    final String port = isBinary ? binaryPort : httpPort;
+
+    List<String> hostPorts = FluentIterable.from(hiveHosts).transform(new Function<String, String>() {
+      @Override
+      public String apply(String input) {
+        return input + ":" + port;
+      }
+    }).toList();
+
+    String concatHostPorts = Joiner.on(",").join(hostPorts);
+
+    StringBuilder builder = new StringBuilder();
+    builder.append("jdbc:hive2://")
+      .append(concatHostPorts)
+      .append(";")
+      .append(sessionParams);
+
+    if (!isBinary) {
+      builder.append(";").append("transportMode=http;httpPath=").append(pathKey);
+    }
+
+    return builder.toString();
+  }
+
+  private static String getFromClusterZookeeperConfig(ViewContext context) {
+    String quorum = context.getCluster().getConfigurationValue(HIVE_SITE, ZK_HIVE_QUORUM);
+    if (quorum == null) {
+      quorum = context.getCluster().getConfigurationValue(HIVE_INTERACTIVE_SITE, ZK_HIVE_QUORUM);
+    }
+
+    String namespace = context.getCluster().getConfigurationValue(HIVE_SITE, ZK_HIVE_NAMESPACE_KEY);
+    if (namespace == null) {
+      namespace = context.getCluster().getConfigurationValue(HIVE_INTERACTIVE_SITE, ZK_HIVE_NAMESPACE_KEY);
+    }
+    return String.format("jdbc:hive2://%s/;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=%s", quorum, namespace);
+  }
+
+  private static boolean zookeeperConfigured(ViewContext context) {
+    boolean fromHiveSite = Boolean.valueOf(context.getCluster().getConfigurationValue(HIVE_SITE, ZK_HIVE_DYN_SERVICE_DISCOVERY_KEY));
+    boolean fromHiveInteractiveSite = Boolean.valueOf(context.getCluster().getConfigurationValue(HIVE_INTERACTIVE_SITE, ZK_HIVE_DYN_SERVICE_DISCOVERY_KEY));
+    return fromHiveInteractiveSite || fromHiveSite;
+  }
+
+  private static String getConnectFromCustom(ViewContext context) {
+    String jdbcUrl = context.getProperties().get(HIVE_JDBC_URL_KEY);
+    String hiveSessionParams = context.getProperties().get(HIVE_SESSION_PARAMS);
+    return jdbcUrl + ";" + hiveSessionParams;
+  }
+}

+ 100 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/ConnectionSystem.java

@@ -0,0 +1,100 @@
+/*
+ * 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.ambari.view.hive2;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Props;
+import com.typesafe.config.Config;
+import com.typesafe.config.ConfigFactory;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.actor.DeathWatch;
+import org.apache.ambari.view.hive2.actor.OperationController;
+import org.apache.ambari.view.hive2.internal.ConnectionSupplier;
+import org.apache.ambari.view.hive2.internal.DataStorageSupplier;
+import org.apache.ambari.view.hive2.internal.HdfsApiSupplier;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+public class ConnectionSystem {
+
+  private static final String ACTOR_CONF_FILE = "application.conf";
+  private static final String ACTOR_SYSTEM_NAME = "HiveViewActorSystem";
+  private ActorSystem actorSystem = null;
+  private static volatile ConnectionSystem instance = null;
+  private static final Object lock = new Object();
+  private static Map<String, ActorRef> operationControllerMap = new HashMap<>();
+
+  private ConnectionSystem() {
+    this.actorSystem = ActorSystem.create(ACTOR_SYSTEM_NAME);;
+  }
+
+  public static ConnectionSystem getInstance() {
+    if(instance == null) {
+      synchronized (lock) {
+        if(instance == null) {
+          instance = new ConnectionSystem();
+        }
+      }
+    }
+    return instance;
+  }
+
+  private ActorRef createOperationController() {
+    ActorRef deathWatch = actorSystem.actorOf(Props.create(DeathWatch.class));
+    return actorSystem.actorOf(
+      Props.create(OperationController.class, actorSystem,deathWatch,
+        new ConnectionSupplier(), new DataStorageSupplier(), new HdfsApiSupplier()));
+  }
+
+  public ActorSystem getActorSystem() {
+    return actorSystem;
+  }
+
+  /**
+   * Returns one operationController per View Instance
+   * @param context
+   * @return operationController Instance
+   */
+  public ActorRef getOperationController(ViewContext context) {
+    String instanceName = context.getInstanceName();
+    ActorRef ref = operationControllerMap.get(instanceName);
+    if(ref == null) {
+      synchronized (lock) {
+        ref = operationControllerMap.get(instanceName);
+        if(ref == null) {
+          ref = createOperationController();
+          operationControllerMap.put(instanceName, ref);
+        }
+      }
+    }
+    return ref;
+  }
+
+  public void shutdown() {
+    if(!actorSystem.isTerminated()) {
+      actorSystem.shutdown();
+    }
+  }
+}

+ 118 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/HelpService.java

@@ -0,0 +1,118 @@
+/**
+ * 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.ambari.view.hive2;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.ViewResourceHandler;
+import org.apache.ambari.view.hive2.resources.files.FileService;
+import org.apache.ambari.view.hive2.resources.jobs.atsJobs.ATSParserFactory;
+import org.apache.ambari.view.hive2.resources.jobs.atsJobs.ATSRequestsDelegateImpl;
+import org.json.simple.JSONObject;
+
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+/**
+ * Help service
+ */
+public class HelpService extends BaseService {
+  @Inject
+  ViewContext context;
+
+  @Inject
+  protected ViewResourceHandler handler;
+
+  /**
+   * Constructor
+   */
+  public HelpService() {
+    super();
+  }
+
+  /**
+   * Version
+   * @return version
+   */
+  @GET
+  @Path("/version")
+  @Produces(MediaType.TEXT_PLAIN)
+  public Response version(){
+    return Response.ok("0.0.1-SNAPSHOT").build();
+  }
+
+  // ================================================================================
+  // Smoke tests
+  // ================================================================================
+
+  /**
+   * HDFS Status
+   * @return status
+   */
+  @GET
+  @Path("/hdfsStatus")
+  @Produces(MediaType.APPLICATION_JSON)
+  public Response hdfsStatus(){
+    FileService.hdfsSmokeTest(context);
+    return getOKResponse();
+  }
+
+  /**
+   * ATS Status
+   * @return status
+   */
+  @GET
+  @Path("/atsStatus")
+  @Produces(MediaType.APPLICATION_JSON)
+  public Response atsStatus() {
+    try {
+      ATSRequestsDelegateImpl atsimpl = new ATSRequestsDelegateImpl(context, ATSParserFactory.getATSUrl(context));
+      atsimpl.checkATSStatus();
+      return getOKResponse();
+    }catch (Exception e){
+      throw new WebApplicationException(e);
+    }
+  }
+
+  private Response getOKResponse() {
+    JSONObject response = new JSONObject();
+    response.put("message", "OK");
+    response.put("trace", null);
+    response.put("status", "200");
+    return Response.ok().entity(response).type(MediaType.APPLICATION_JSON).build();
+  }
+
+  /**
+   * Version
+   * @return version
+   */
+  @GET
+  @Path("/test")
+  @Produces(MediaType.TEXT_PLAIN)
+  public Response testStorage(){
+    TestBean test = new TestBean();
+    test.someData = "hello world";
+    getSharedObjectsFactory().getStorage().store(TestBean.class, test);
+    return Response.ok("OK").build();
+  }
+}

+ 144 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/HiveJdbcConnectionDelegate.java

@@ -0,0 +1,144 @@
+/*
+ * 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.ambari.view.hive2;
+
+import com.google.common.base.Optional;
+import org.apache.ambari.view.hive2.actor.message.DDLJob;
+import org.apache.ambari.view.hive2.actor.message.GetColumnMetadataJob;
+import org.apache.ambari.view.hive2.actor.message.HiveJob;
+import org.apache.ambari.view.hive2.actor.message.job.Result;
+import org.apache.ambari.view.hive2.internal.HiveResult;
+import org.apache.hive.jdbc.HiveConnection;
+import org.apache.hive.jdbc.HiveStatement;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+public class HiveJdbcConnectionDelegate implements ConnectionDelegate {
+
+  private ResultSet currentResultSet;
+  private HiveStatement currentStatement;
+  private String atsGuid;
+
+  @Override
+  public Optional<ResultSet> execute(HiveConnection connection, DDLJob job) throws SQLException {
+
+    try {
+      Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
+      currentStatement = (HiveStatement) statement;
+
+      for (String syncStatement : job.getSyncStatements()) {
+        // we don't care about the result
+        // fail all if one fails
+        statement.execute(syncStatement);
+      }
+
+      HiveStatement hiveStatement = (HiveStatement) statement;
+      boolean result = hiveStatement.executeAsync(job.getAsyncStatement());
+      atsGuid = hiveStatement.getYarnATSGuid();
+      if (result) {
+        // query has a result set
+        ResultSet resultSet = hiveStatement.getResultSet();
+        currentResultSet = resultSet;
+        Optional<ResultSet> resultSetOptional = Optional.of(resultSet);
+        return resultSetOptional;
+
+      }
+      return Optional.absent();
+
+    } catch (SQLException e) {
+      // Close the statement on any error
+      currentStatement.close();
+      throw e;
+    }
+  }
+
+  @Override
+  public Optional<ResultSet> executeSync(HiveConnection connection, DDLJob job) throws SQLException {
+    try {
+      Statement statement = connection.createStatement();
+      currentStatement = (HiveStatement) statement;
+
+      boolean hasResultSet = false;
+      for (String syncStatement : job.getStatements()) {
+        // we don't care about the result
+        // fail all if one fails
+        hasResultSet = statement.execute(syncStatement);
+      }
+
+      if (hasResultSet) {
+        ResultSet resultSet = statement.getResultSet();
+        //HiveResult result = new HiveResult(resultSet);
+        return Optional.of(resultSet);
+      } else {
+        return Optional.absent();
+      }
+    } catch (SQLException e) {
+      // Close the statement on any error
+      currentStatement.close();
+      throw e;
+    }
+  }
+
+
+  @Override
+  public Optional<ResultSet> getColumnMetadata(HiveConnection connection, GetColumnMetadataJob job) throws SQLException {
+    DatabaseMetaData metaData = connection.getMetaData();
+    ResultSet resultSet = metaData.getColumns("", job.getSchemaPattern(), job.getTablePattern(), job.getColumnPattern());
+    currentResultSet = resultSet;
+    return Optional.of(resultSet);
+  }
+
+  @Override
+  public Optional<ResultSet> getCurrentResultSet() {
+    return Optional.fromNullable(currentResultSet);
+  }
+
+  @Override
+  public Optional<HiveStatement> getCurrentStatement() {
+    return Optional.fromNullable(currentStatement);
+  }
+
+  @Override
+  public void closeResultSet() {
+
+    try {
+      if (currentResultSet != null) {
+        currentResultSet.close();
+      }
+    } catch (SQLException e) {
+      // Cannot do anything here
+    }
+  }
+
+  @Override
+  public void closeStatement()  {
+    try {
+      if (currentStatement != null) {
+        currentStatement.close();
+      }
+    } catch (SQLException e) {
+      // cannot do anything here
+    }
+  }
+
+
+}

+ 50 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/HiveViewImpl.java

@@ -0,0 +1,50 @@
+/**
+ * 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.ambari.view.hive2;
+
+import org.apache.ambari.view.View;
+import org.apache.ambari.view.ViewDefinition;
+import org.apache.ambari.view.ViewInstanceDefinition;
+import org.apache.ambari.view.hive2.utils.SharedObjectsFactory;
+import org.apache.ambari.view.utils.UserLocal;
+
+
+public class HiveViewImpl implements View {
+  @Override
+  public void onDeploy(ViewDefinition definition) {
+
+  }
+
+  @Override
+  public void onCreate(ViewInstanceDefinition definition) {
+
+  }
+
+  @Override
+  public void onDestroy(ViewInstanceDefinition definition) {
+    SharedObjectsFactory.dropInstanceCache(definition.getInstanceName());
+  }
+
+  @Override
+  public void onUpdate(ViewInstanceDefinition definition) {
+    //drop all cached connection for instance
+    UserLocal.dropInstanceCache(definition.getInstanceName());
+    SharedObjectsFactory.dropInstanceCache(definition.getInstanceName());
+  }
+}

+ 98 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/PropertyValidator.java

@@ -0,0 +1,98 @@
+/**
+ * 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.ambari.view.hive2;
+
+import org.apache.ambari.view.ViewInstanceDefinition;
+import org.apache.ambari.view.utils.ambari.ValidatorUtils;
+import org.apache.ambari.view.validation.ValidationResult;
+import org.apache.ambari.view.validation.Validator;
+
+public class PropertyValidator implements Validator {
+
+  public static final String WEBHDFS_URL = "webhdfs.url";
+  public static final String HIVE_PORT = "hive.port";
+  public static final String YARN_ATS_URL = "yarn.ats.url";
+  public static final String HIVE_SESSION_PARAMS = "hive.session.params";
+
+  @Override
+  public ValidationResult validateInstance(ViewInstanceDefinition viewInstanceDefinition, ValidationContext validationContext) {
+    return null;
+  }
+
+  @Override
+  public ValidationResult validateProperty(String property, ViewInstanceDefinition viewInstanceDefinition, ValidationContext validationContext) {
+    // Validate non cluster associated properties
+    if (property.equals(HIVE_SESSION_PARAMS)) {
+      String auth = viewInstanceDefinition.getPropertyMap().get(HIVE_SESSION_PARAMS);
+
+      if (auth != null && !auth.isEmpty()) {
+        for(String param : auth.split(";")) {
+          String[] keyvalue = param.split("=");
+          if (keyvalue.length != 2) {
+            return new InvalidPropertyValidationResult(false, "Can not parse session param " + param + " in " + auth);
+          }
+        }
+      }
+    }
+
+    // if associated with cluster, no need to validate associated properties
+    Long cluster = viewInstanceDefinition.getClusterHandle();
+    if (cluster != null) {
+      return ValidationResult.SUCCESS;
+    }
+
+    // Cluster associated properties
+    if (property.equals(WEBHDFS_URL)) {
+      String webhdfsUrl = viewInstanceDefinition.getPropertyMap().get(WEBHDFS_URL);
+      if (!ValidatorUtils.validateHdfsURL(webhdfsUrl)) {
+        return new InvalidPropertyValidationResult(false, "Must be valid URL");
+      }
+    }
+
+    if (property.equals(YARN_ATS_URL)) {
+      String atsUrl = viewInstanceDefinition.getPropertyMap().get(YARN_ATS_URL);
+      if (!ValidatorUtils.validateHttpURL(atsUrl)) {
+        return new InvalidPropertyValidationResult(false, "Must be valid URL");
+      }
+    }
+
+    return ValidationResult.SUCCESS;
+  }
+
+  public static class InvalidPropertyValidationResult implements ValidationResult {
+    private boolean valid;
+    private String detail;
+
+    public InvalidPropertyValidationResult(boolean valid, String detail) {
+      this.valid = valid;
+      this.detail = detail;
+    }
+
+    @Override
+    public boolean isValid() {
+      return valid;
+    }
+
+    @Override
+    public String getDetail() {
+      return detail;
+    }
+  }
+
+}

+ 36 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/TestBean.java

@@ -0,0 +1,36 @@
+/**
+ * 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.ambari.view.hive2;
+
+import org.apache.ambari.view.hive2.persistence.utils.Indexed;
+
+public class TestBean implements Indexed {
+  public String someData;
+  public String id;
+
+  @Override
+  public String getId() {
+    return id;
+  }
+
+  @Override
+  public void setId(String id) {
+    this.id = id;
+  }
+}

+ 192 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/AsyncJdbcConnector.java

@@ -0,0 +1,192 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.PoisonPill;
+import akka.actor.Props;
+import com.google.common.base.Optional;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.actor.message.RegisterActor;
+import org.apache.ambari.view.hive2.persistence.Storage;
+import org.apache.ambari.view.hive2.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.Job;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.JobImpl;
+import org.apache.ambari.view.hive2.ConnectionDelegate;
+import org.apache.ambari.view.hive2.actor.message.AsyncJob;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.ResultReady;
+import org.apache.ambari.view.hive2.actor.message.job.AsyncExecutionFailed;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.InactivityCheck;
+import org.apache.ambari.view.hive2.actor.message.StartLogAggregation;
+import org.apache.ambari.view.hive2.internal.Either;
+import org.apache.ambari.view.utils.hdfs.HdfsApi;
+import org.apache.hive.jdbc.HiveConnection;
+import org.apache.hive.jdbc.HiveStatement;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+
+public class AsyncJdbcConnector extends JdbcConnector {
+
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  private ActorRef logAggregator = null;
+  private ActorRef asyncQueryExecutor = null;
+  private ActorRef resultSetActor = null;
+
+
+  public AsyncJdbcConnector(ViewContext viewContext, HdfsApi hdfsApi, ActorSystem system, ActorRef parent,ActorRef deathWatch, ConnectionDelegate connectionDelegate, Storage storage) {
+    super(viewContext, hdfsApi, system, parent,deathWatch, connectionDelegate, storage);
+  }
+
+  @Override
+  protected void handleJobMessage(HiveMessage message) {
+    Object job = message.getMessage();
+    if (job instanceof AsyncJob) {
+      LOG.debug("Executing async job " + message.toString());
+      execute((AsyncJob) job);
+    }
+  }
+
+  @Override
+  protected boolean isAsync() {
+    return true;
+  }
+
+  @Override
+  protected void cleanUpChildren() {
+    if(logAggregator != null && !logAggregator.isTerminated()) {
+      LOG.debug("Sending poison pill to log aggregator");
+      logAggregator.tell(PoisonPill.getInstance(), self());
+    }
+
+    if(asyncQueryExecutor != null && !asyncQueryExecutor.isTerminated()) {
+      LOG.debug("Sending poison pill to Async Query Executor");
+      asyncQueryExecutor.tell(PoisonPill.getInstance(), self());
+    }
+
+    if(resultSetActor != null && !resultSetActor.isTerminated()) {
+      LOG.debug("Sending poison pill to Resultset Actor");
+      resultSetActor.tell(PoisonPill.getInstance(), self());
+    }
+  }
+
+  @Override
+  protected void notifyFailure() {
+    AsyncExecutionFailed failure = new AsyncExecutionFailed(jobId,username,"Cannot connect to hive");
+    parent.tell(failure, self());
+  }
+
+  private void execute(AsyncJob message) {
+    this.executing = true;
+    this.jobId = message.getJobId();
+    updateJobStatus(jobId,Job.JOB_STATE_INITIALIZED);
+    if (connectable == null) {
+      notifyAndCleanUp();
+      return;
+    }
+
+    Optional<HiveConnection> connectionOptional = connectable.getConnection();
+    if (!connectionOptional.isPresent()) {
+      notifyAndCleanUp();
+      return;
+    }
+
+    try {
+      Optional<ResultSet> resultSetOptional = connectionDelegate.execute(connectionOptional.get(), message);
+      Optional<HiveStatement> currentStatement = connectionDelegate.getCurrentStatement();
+      // There should be a result set, which either has a result set, or an empty value
+      // for operations which do not return anything
+
+      logAggregator = getContext().actorOf(
+        Props.create(LogAggregator.class, system, hdfsApi, currentStatement.get(), message.getLogFile())
+        .withDispatcher("akka.actor.misc-dispatcher"), message.getUsername() + ":" + message.getJobId() + "-logAggregator"
+      );
+      deathWatch.tell(new RegisterActor(logAggregator),self());
+
+      updateGuidInJob(jobId, currentStatement.get());
+      updateJobStatus(jobId,Job.JOB_STATE_RUNNING);
+
+      if (resultSetOptional.isPresent()) {
+        // Start a result set aggregator on the same context, a notice to the parent will kill all these as well
+        // tell the result holder to assign the result set for further operations
+        resultSetActor = getContext().actorOf(Props.create(ResultSetIterator.class, self(),
+          resultSetOptional.get(),storage).withDispatcher("akka.actor.result-dispatcher"),
+          "ResultSetActor:ResultSetIterator:JobId:"+ jobId+":" + UUID.randomUUID().toString());
+        deathWatch.tell(new RegisterActor(resultSetActor),self());
+        parent.tell(new ResultReady(jobId,username, Either.<ActorRef, ActorRef>left(resultSetActor)), self());
+
+        // Start a actor to query ATS
+      } else {
+        // Case when this is an Update/query with no results
+        // Wait for operation to complete and add results;
+
+        ActorRef asyncQueryExecutor = getContext().actorOf(
+                Props.create(AsyncQueryExecutor.class, parent, currentStatement.get(),storage,jobId,username)
+                  .withDispatcher("akka.actor.result-dispatcher"),
+                message.getUsername() + ":" + message.getJobId() + "-asyncQueryExecutor");
+        deathWatch.tell(new RegisterActor(asyncQueryExecutor),self());
+        parent.tell(new ResultReady(jobId,username, Either.<ActorRef, ActorRef>right(asyncQueryExecutor)), self());
+
+      }
+      // Start a actor to query log
+      logAggregator.tell(new StartLogAggregation(), self());
+
+
+    } catch (SQLException e) {
+      // update the error on the log
+      AsyncExecutionFailed failure = new AsyncExecutionFailed(message.getJobId(),username,
+              e.getMessage(), e);
+      updateJobStatus(jobId,Job.JOB_STATE_ERROR);
+      parent.tell(failure, self());
+      // Update the operation controller to write an error on tshe right side
+      LOG.error("Caught SQL excpetion for job-"+message,e);
+
+    }
+
+    // Start Inactivity timer to close the statement
+    this.inactivityScheduler = system.scheduler().schedule(
+      Duration.Zero(), Duration.create(15 * 1000, TimeUnit.MILLISECONDS),
+      this.self(), new InactivityCheck(), system.dispatcher(), null);
+  }
+
+  private void notifyAndCleanUp() {
+    updateJobStatus(jobId, Job.JOB_STATE_ERROR);
+    notifyFailure();
+    cleanUp();
+  }
+
+  private void updateJobStatus(String jobId, String jobState) {
+    JobImpl job = null;
+    try {
+      job = storage.load(JobImpl.class, jobId);
+    } catch (ItemNotFound itemNotFound) {
+      itemNotFound.printStackTrace();
+    }
+    job.setStatus(jobState);
+    storage.store(JobImpl.class, job);
+  }
+}

+ 92 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/AsyncQueryExecutor.java

@@ -0,0 +1,92 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import org.apache.ambari.view.hive2.actor.message.ExecuteQuery;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.job.AsyncExecutionFailed;
+import org.apache.ambari.view.hive2.actor.message.job.ExecutionFailed;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.CleanUp;
+import org.apache.ambari.view.hive2.internal.AsyncExecutionSuccess;
+import org.apache.ambari.view.hive2.persistence.Storage;
+import org.apache.ambari.view.hive2.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.Job;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.JobImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.SQLException;
+import java.sql.Statement;
+
+public class AsyncQueryExecutor extends HiveActor {
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  private Statement statement;
+  private final Storage storage;
+  private final String jobId;
+  private final ActorRef parent;
+  private final String userName;
+
+  public AsyncQueryExecutor(ActorRef parent, Statement statement, Storage storage, String jobId,String userName) {
+    this.statement = statement;
+    this.storage = storage;
+    this.jobId = jobId;
+    this.parent = parent;
+    this.userName = userName;
+  }
+
+  @Override
+  public void handleMessage(HiveMessage hiveMessage) {
+    Object message = hiveMessage.getMessage();
+
+    if (message instanceof ExecuteQuery) {
+      executeQuery();
+    }
+
+  }
+
+  private void executeQuery() {
+    JobImpl job = null;
+    try {
+      job = storage.load(JobImpl.class, jobId);
+      statement.getUpdateCount();
+      LOG.info("Job execution successful. Setting status in db.");
+      job.setStatus(Job.JOB_STATE_FINISHED);
+      storage.store(JobImpl.class, job);
+      sender().tell(new AsyncExecutionSuccess(), self());
+
+    } catch (SQLException e) {
+      job.setStatus(Job.JOB_STATE_ERROR);
+      sender().tell(new AsyncExecutionFailed(jobId,userName, e.getMessage(), e), self());
+      storage.store(JobImpl.class, job);
+    } catch (ItemNotFound itemNotFound) {
+      sender().tell(new AsyncExecutionFailed(jobId,userName, "Cannot load job", itemNotFound), self());
+    } finally {
+      // We can clean up this connection here
+      parent.tell(new CleanUp(), self());
+    }
+
+  }
+
+
+}
+
+
+

+ 54 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/DeathWatch.java

@@ -0,0 +1,54 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import akka.actor.Terminated;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.RegisterActor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Date;
+
+public class DeathWatch extends HiveActor {
+
+    private final static Logger LOG =
+            LoggerFactory.getLogger(DeathWatch.class);
+
+    @Override
+    void handleMessage(HiveMessage hiveMessage) {
+        Object message = hiveMessage.getMessage();
+        if(message instanceof RegisterActor){
+            RegisterActor registerActor = (RegisterActor) message;
+            ActorRef actorRef = registerActor.getActorRef();
+            this.getContext().watch(actorRef);
+            LOG.info("Registered new actor "+ actorRef);
+            LOG.info("Registration for {} at {}", actorRef,new Date());
+        }
+        if(message instanceof Terminated){
+            Terminated terminated = (Terminated) message;
+            ActorRef actor = terminated.actor();
+            LOG.info("Received deathwatch for actor "+ actor);
+            LOG.info("Termination for {} at {}", actor,new Date());
+
+        }
+
+    }
+}

+ 47 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/GetResultHolder.java

@@ -0,0 +1,47 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+public class GetResultHolder {
+
+    private String jobId;
+    private String userName;
+
+    public GetResultHolder(String jobId, String userName) {
+        this.jobId = jobId;
+        this.userName = userName;
+    }
+
+
+    public String getJobId() {
+        return jobId;
+    }
+
+    public String getUserName() {
+        return userName;
+    }
+
+    @Override
+    public String toString() {
+        return "GetResultHolder{" +
+                "jobId='" + jobId + '\'' +
+                ", userName='" + userName + '\'' +
+                '}';
+    }
+}

+ 51 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/HiveActor.java

@@ -0,0 +1,51 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.UntypedActor;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class HiveActor extends UntypedActor {
+
+    private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+    @Override
+    final public void onReceive(Object message) throws Exception {
+        HiveMessage hiveMessage = new HiveMessage(message);
+        /*if(LOG.isDebugEnabled()){
+            LOG.debug("Received message: " + message.getClass().getName() + ", generated id: " + hiveMessage.getId() +
+                    " sent by: " + sender() + ", recieved by" + self());
+        }*/
+
+        handleMessage(hiveMessage);
+
+        /*if(LOG.isDebugEnabled()){
+            LOG.debug("Message submitted: " + hiveMessage.getId());
+
+        }*/
+
+    }
+
+    abstract void handleMessage(HiveMessage hiveMessage);
+
+
+
+}

+ 305 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/JdbcConnector.java

@@ -0,0 +1,305 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Cancellable;
+import akka.actor.PoisonPill;
+import com.google.common.base.Optional;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.ConnectionDelegate;
+import org.apache.ambari.view.hive2.actor.message.Connect;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.JobExecutionCompleted;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.CleanUp;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.DestroyConnector;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.FreeConnector;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.InactivityCheck;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.KeepAlive;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.TerminateInactivityCheck;
+import org.apache.ambari.view.hive2.internal.Connectable;
+import org.apache.ambari.view.hive2.internal.ConnectionException;
+import org.apache.ambari.view.hive2.persistence.Storage;
+import org.apache.ambari.view.hive2.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.JobImpl;
+import org.apache.ambari.view.hive2.utils.HiveActorConfiguration;
+import org.apache.ambari.view.utils.hdfs.HdfsApi;
+import org.apache.hive.jdbc.HiveStatement;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+import java.util.concurrent.TimeUnit;
+
+
+/**
+ * Wraps one Jdbc connection per user, per instance. This is used to delegate execute the statements and
+ * creates child actors to delegate the resultset extraction, YARN/ATS querying for ExecuteJob info and Log Aggregation
+ */
+public abstract class JdbcConnector extends HiveActor {
+
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  /**
+   * Interval for maximum inactivity allowed
+   */
+  private final static long MAX_INACTIVITY_INTERVAL = 5 * 60 * 1000;
+
+  /**
+   * Interval for maximum inactivity allowed before termination
+   */
+  private static final long MAX_TERMINATION_INACTIVITY_INTERVAL = 10 * 60 * 1000;
+
+  protected final ViewContext viewContext;
+  protected final ActorSystem system;
+  protected final Storage storage;
+
+  /**
+   * Keeps track of the timestamp when the last activity has happened. This is
+   * used to calculate the inactivity period and take lifecycle decisions based
+   * on it.
+   */
+  private long lastActivityTimestamp;
+
+  /**
+   * Akka scheduler to tick at an interval to deal with inactivity of this actor
+   */
+  protected Cancellable inactivityScheduler;
+
+  /**
+   * Akka scheduler to tick at an interval to deal with the inactivity after which
+   * the actor should be killed and connectable should be released
+   */
+  protected Cancellable terminateActorScheduler;
+
+  protected Connectable connectable = null;
+  protected final ActorRef deathWatch;
+  protected final ConnectionDelegate connectionDelegate;
+  protected final ActorRef parent;
+  protected final HdfsApi hdfsApi;
+
+  /**
+   * true if the actor is currently executing any job.
+   */
+  protected boolean executing = false;
+
+  /**
+   * true if the currently executing job is async job.
+   */
+  private boolean async = true;
+
+  /**
+   * Returns the timeout configurations.
+   */
+  private final HiveActorConfiguration actorConfiguration;
+  protected String username;
+  protected String jobId;
+
+  public JdbcConnector(ViewContext viewContext, HdfsApi hdfsApi, ActorSystem system, ActorRef parent, ActorRef deathWatch,
+                       ConnectionDelegate connectionDelegate, Storage storage) {
+    this.viewContext = viewContext;
+    this.hdfsApi = hdfsApi;
+    this.system = system;
+    this.parent = parent;
+    this.deathWatch = deathWatch;
+    this.connectionDelegate = connectionDelegate;
+    this.storage = storage;
+    this.lastActivityTimestamp = System.currentTimeMillis();
+    actorConfiguration = new HiveActorConfiguration(viewContext);
+  }
+
+  @Override
+  public void handleMessage(HiveMessage hiveMessage) {
+    Object message = hiveMessage.getMessage();
+    if (message instanceof InactivityCheck) {
+      checkInactivity();
+    } else if (message instanceof TerminateInactivityCheck) {
+      checkTerminationInactivity();
+    } else if (message instanceof KeepAlive) {
+      keepAlive();
+    } else if (message instanceof CleanUp) {
+      cleanUp();
+    } else if (message instanceof JobExecutionCompleted) {
+      jobExecutionCompleted();
+    } else {
+      handleNonLifecycleMessage(hiveMessage);
+    }
+  }
+
+  private void handleNonLifecycleMessage(HiveMessage hiveMessage) {
+    Object message = hiveMessage.getMessage();
+    keepAlive();
+    if (message instanceof Connect) {
+      connect((Connect) message);
+    } else {
+      handleJobMessage(hiveMessage);
+    }
+
+  }
+
+  protected abstract void handleJobMessage(HiveMessage message);
+
+  protected abstract boolean isAsync();
+
+  protected abstract void notifyFailure();
+
+  protected abstract void cleanUpChildren();
+
+  private void keepAlive() {
+    lastActivityTimestamp = System.currentTimeMillis();
+  }
+
+  private void jobExecutionCompleted() {
+    // Set is executing as false so that the inactivity checks can finish cleanup
+    // after timeout
+    LOG.info("Job execution completed for user: {}. Results are ready to be fetched", username);
+    this.executing = false;
+  }
+
+  protected Optional<String> getJobId() {
+    return Optional.fromNullable(jobId);
+  }
+
+  protected Optional<String> getUsername() {
+    return Optional.fromNullable(username);
+  }
+
+  private void connect(Connect message) {
+    this.username = message.getUsername();
+    // check the connectable
+    if (connectable == null) {
+      connectable = message.getConnectable();
+    }
+    // make the connectable to Hive
+    try {
+      if (!connectable.isOpen()) {
+        connectable.connect();
+      }
+    } catch (ConnectionException e) {
+      // set up job failure
+      // notify parent about job failure
+      this.notifyFailure();
+      cleanUp();
+      return;
+    }
+
+    this.terminateActorScheduler = system.scheduler().schedule(
+      Duration.Zero(), Duration.create(60 * 1000, TimeUnit.MILLISECONDS),
+      this.getSelf(), new TerminateInactivityCheck(), system.dispatcher(), null);
+
+  }
+
+  protected void updateGuidInJob(String jobId, HiveStatement statement) {
+    String yarnAtsGuid = statement.getYarnATSGuid();
+    try {
+      JobImpl job = storage.load(JobImpl.class, jobId);
+      job.setGuid(yarnAtsGuid);
+      storage.store(JobImpl.class, job);
+    } catch (ItemNotFound itemNotFound) {
+      // Cannot do anything if the job is not present
+    }
+  }
+
+  private void checkInactivity() {
+    LOG.info("Inactivity check, executing status: {}", executing);
+    if (executing) {
+      keepAlive();
+      return;
+    }
+    long current = System.currentTimeMillis();
+    if ((current - lastActivityTimestamp) > actorConfiguration.getInactivityTimeout(MAX_INACTIVITY_INTERVAL)) {
+      // Stop all the sub-actors created
+      cleanUp();
+    }
+  }
+
+  private void checkTerminationInactivity() {
+    if (!isAsync()) {
+      // Should not terminate if job is sync. Will terminate after the job is finished.
+      stopTeminateInactivityScheduler();
+      return;
+    }
+
+    LOG.info("Termination check, executing status: {}", executing);
+    if (executing) {
+      keepAlive();
+      return;
+    }
+
+    long current = System.currentTimeMillis();
+    if ((current - lastActivityTimestamp) > actorConfiguration.getTerminationTimeout(MAX_TERMINATION_INACTIVITY_INTERVAL)) {
+      cleanUpWithTermination();
+    }
+  }
+
+  protected void cleanUp() {
+    if(jobId != null) {
+      LOG.debug("{} :: Cleaning up resources for inactivity for jobId: {}", self().path().name(), jobId);
+    } else {
+      LOG.debug("{} ::Cleaning up resources with inactivity for Sync execution.", self().path().name());
+    }
+    this.executing = false;
+    cleanUpStatementAndResultSet();
+    cleanUpChildren();
+    stopInactivityScheduler();
+    parent.tell(new FreeConnector(username, jobId, isAsync()), self());
+  }
+
+  protected void cleanUpWithTermination() {
+    LOG.debug("{} :: Cleaning up resources with inactivity for Sync execution.", self().path().name());
+    cleanUpStatementAndResultSet();
+
+    cleanUpChildren();
+    stopInactivityScheduler();
+    stopTeminateInactivityScheduler();
+    parent.tell(new DestroyConnector(username, jobId, isAsync()), this.self());
+    self().tell(PoisonPill.getInstance(), ActorRef.noSender());
+  }
+
+
+  private void cleanUpStatementAndResultSet() {
+    connectionDelegate.closeStatement();
+    connectionDelegate.closeResultSet();
+  }
+
+  private void stopTeminateInactivityScheduler() {
+    if (!(terminateActorScheduler == null || terminateActorScheduler.isCancelled())) {
+      terminateActorScheduler.cancel();
+    }
+  }
+
+  private void stopInactivityScheduler() {
+    if (!(inactivityScheduler == null || inactivityScheduler.isCancelled())) {
+      inactivityScheduler.cancel();
+    }
+  }
+
+  @Override
+  public void postStop() throws Exception {
+    stopInactivityScheduler();
+    stopTeminateInactivityScheduler();
+
+    if (connectable.isOpen()) {
+      connectable.disconnect();
+    }
+  }
+
+
+}

+ 109 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/LogAggregator.java

@@ -0,0 +1,109 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Cancellable;
+import com.google.common.base.Joiner;
+import org.apache.ambari.view.hive2.actor.message.GetMoreLogs;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.LogAggregationFinished;
+import org.apache.ambari.view.hive2.actor.message.StartLogAggregation;
+import org.apache.ambari.view.utils.hdfs.HdfsApi;
+import org.apache.ambari.view.utils.hdfs.HdfsApiException;
+import org.apache.ambari.view.utils.hdfs.HdfsUtil;
+import org.apache.hive.jdbc.HiveStatement;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+import java.sql.SQLException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Reads the logs for a ExecuteJob from the Statement and writes them into hdfs.
+ */
+public class LogAggregator extends HiveActor {
+
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  public static final int AGGREGATION_INTERVAL = 5 * 1000;
+  private final HdfsApi hdfsApi;
+  private final HiveStatement statement;
+  private final String logFile;
+  private final ActorSystem system;
+
+  private Cancellable moreLogsScheduler;
+  private ActorRef parent;
+
+  public LogAggregator(ActorSystem system, HdfsApi hdfsApi, HiveStatement statement, String logFile) {
+    this.system = system;
+    this.hdfsApi = hdfsApi;
+    this.statement = statement;
+    this.logFile = logFile;
+  }
+
+  @Override
+  public void handleMessage(HiveMessage hiveMessage) {
+    Object message = hiveMessage.getMessage();
+    if (message instanceof StartLogAggregation) {
+      start();
+    }
+
+    if (message instanceof GetMoreLogs) {
+      try {
+        getMoreLogs();
+      } catch (SQLException e) {
+        LOG.error("SQL Error while getting logs. Tried writing to: {}", logFile);
+      } catch (HdfsApiException e) {
+        LOG.warn("HDFS Error while getting writing logs to {}", logFile);
+
+      }
+    }
+  }
+
+  private void start() {
+    parent = this.getSender();
+    this.moreLogsScheduler = system.scheduler().schedule(
+      Duration.Zero(), Duration.create(AGGREGATION_INTERVAL, TimeUnit.MILLISECONDS),
+      this.getSelf(), new GetMoreLogs(), system.dispatcher(), null);
+  }
+
+  private void getMoreLogs() throws SQLException, HdfsApiException {
+    if (statement.hasMoreLogs()) {
+      List<String> logs = statement.getQueryLog();
+      String allLogs = Joiner.on("\n").skipNulls().join(logs);
+      HdfsUtil.putStringToFile(hdfsApi, logFile, allLogs);
+    } else {
+      moreLogsScheduler.cancel();
+      parent.tell(new LogAggregationFinished(), ActorRef.noSender());
+    }
+  }
+
+  @Override
+  public void postStop() throws Exception {
+    if(moreLogsScheduler != null && !moreLogsScheduler.isCancelled()){
+      moreLogsScheduler.cancel();
+    }
+
+  }
+
+}

+ 438 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/OperationController.java

@@ -0,0 +1,438 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Props;
+import com.google.common.base.Optional;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.ConnectionDelegate;
+import org.apache.ambari.view.hive2.actor.message.AdvanceCursor;
+import org.apache.ambari.view.hive2.actor.message.AsyncJob;
+import org.apache.ambari.view.hive2.actor.message.Connect;
+import org.apache.ambari.view.hive2.actor.message.ExecuteJob;
+import org.apache.ambari.view.hive2.actor.message.ExecuteQuery;
+import org.apache.ambari.view.hive2.actor.message.FetchError;
+import org.apache.ambari.view.hive2.actor.message.FetchResult;
+import org.apache.ambari.view.hive2.actor.message.HiveJob;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.JobRejected;
+import org.apache.ambari.view.hive2.actor.message.RegisterActor;
+import org.apache.ambari.view.hive2.actor.message.ResultReady;
+import org.apache.ambari.view.hive2.actor.message.job.AsyncExecutionFailed;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.DestroyConnector;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.FreeConnector;
+import org.apache.ambari.view.hive2.internal.ContextSupplier;
+import org.apache.ambari.view.hive2.internal.Either;
+import org.apache.ambari.view.hive2.persistence.Storage;
+import org.apache.ambari.view.hive2.utils.LoggingOutputStream;
+import org.apache.ambari.view.utils.hdfs.HdfsApi;
+import org.apache.commons.collections4.MapUtils;
+import org.apache.commons.collections4.map.HashedMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * Router actor to control the operations. This delegates the operations to underlying child actors and
+ * store the state for them.
+ */
+public class OperationController extends HiveActor {
+
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  private final ActorSystem system;
+  private final ActorRef deathWatch;
+  private final ContextSupplier<ConnectionDelegate> connectionSupplier;
+  private final ContextSupplier<Storage> storageSupplier;
+  private final ContextSupplier<Optional<HdfsApi>> hdfsApiSupplier;
+
+  /**
+   * Store the connection per user which are currently not working
+   */
+  private final Map<String, Queue<ActorRef>> asyncAvailableConnections;
+
+  /**
+   * Store the connection per user which are currently not working
+   */
+  private final Map<String, Queue<ActorRef>> syncAvailableConnections;
+
+
+  /**
+   * Store the connection per user/per job which are currently working.
+   */
+  private final Map<String, Map<String, ActorRefResultContainer>> asyncBusyConnections;
+
+  /**
+   * Store the connection per user which will be used to execute sync jobs
+   * like fetching databases, tables etc.
+   */
+  private final Map<String, Set<ActorRef>> syncBusyConnections;
+
+  public OperationController(ActorSystem system,
+                             ActorRef deathWatch,
+                             ContextSupplier<ConnectionDelegate> connectionSupplier,
+                             ContextSupplier<Storage> storageSupplier,
+                             ContextSupplier<Optional<HdfsApi>> hdfsApiSupplier) {
+    this.system = system;
+    this.deathWatch = deathWatch;
+    this.connectionSupplier = connectionSupplier;
+    this.storageSupplier = storageSupplier;
+    this.hdfsApiSupplier = hdfsApiSupplier;
+    this.asyncAvailableConnections = new HashMap<>();
+    this.syncAvailableConnections = new HashMap<>();
+    this.asyncBusyConnections = new HashedMap<>();
+    this.syncBusyConnections = new HashMap<>();
+  }
+
+  @Override
+  public void handleMessage(HiveMessage hiveMessage) {
+    Object message = hiveMessage.getMessage();
+
+    if (message instanceof ExecuteJob) {
+      ExecuteJob job = (ExecuteJob) message;
+      if (job.getJob().getType() == HiveJob.Type.ASYNC) {
+        sendJob(job.getConnect(), (AsyncJob) job.getJob());
+      } else if (job.getJob().getType() == HiveJob.Type.SYNC) {
+        sendSyncJob(job.getConnect(), job.getJob());
+      }
+    }
+
+    if (message instanceof ResultReady) {
+      updateResultContainer((ResultReady) message);
+    }
+
+    if(message instanceof AsyncExecutionFailed){
+      updateResultContainerWithError((AsyncExecutionFailed) message);
+    }
+
+    if (message instanceof GetResultHolder) {
+      getResultHolder((GetResultHolder) message);
+    }
+
+    if (message instanceof FetchResult) {
+      fetchResultActorRef((FetchResult) message);
+    }
+
+    if (message instanceof FetchError) {
+      fetchError((FetchError) message);
+    }
+
+    if (message instanceof FreeConnector) {
+      freeConnector((FreeConnector) message);
+    }
+
+    if (message instanceof DestroyConnector) {
+      destroyConnector((DestroyConnector) message);
+    }
+  }
+
+  private void fetchError(FetchError message) {
+    String jobId = message.getJobId();
+    String username = message.getUsername();
+    ActorRefResultContainer container = asyncBusyConnections.get(username).get(jobId);
+    if(container.hasError){
+      sender().tell(Optional.of(container.error), self());
+      return;
+    }
+    sender().tell(Optional.absent(), self());
+  }
+
+  private void updateResultContainerWithError(AsyncExecutionFailed message) {
+    String userName = message.getUsername();
+    String jobId = message.getJobId();
+    ActorRefResultContainer container = asyncBusyConnections.get(userName).get(jobId);
+    container.hasError = true;
+    container.error = message;
+  }
+
+  private void getResultHolder(GetResultHolder message) {
+    String userName = message.getUserName();
+    String jobId = message.getJobId();
+    if(asyncBusyConnections.containsKey(userName) && asyncBusyConnections.get(userName).containsKey(jobId))
+      sender().tell(asyncBusyConnections.get(userName).get(jobId).result, self());
+    else {
+      Either<ActorRef, AsyncExecutionFailed> right = Either.right(new AsyncExecutionFailed(message.getJobId(),userName, "Could not find the job, maybe the pool expired"));
+      sender().tell(right, self());
+    }
+  }
+
+  private void updateResultContainer(ResultReady message) {
+    // set up result actor in container
+    String jobId = message.getJobId();
+    String username = message.getUsername();
+    Either<ActorRef, ActorRef> result = message.getResult();
+    asyncBusyConnections.get(username).get(jobId).result = result;
+    // start processing
+    if(message.getResult().isRight()){
+      // Query with no result sets to be returned
+      // execute right away
+      result.getRight().tell(new ExecuteQuery(),self());
+    }
+    if(result.isLeft()){
+      // There is a result set to be processed
+      result.getLeft().tell(new AdvanceCursor(message.getJobId()),self());
+    }
+
+  }
+
+  private void fetchResultActorRef(FetchResult message) {
+    //Gets an Either actorRef,result implementation
+    // and send back to the caller
+    String username = message.getUsername();
+    String jobId = message.getJobId();
+    ActorRefResultContainer container = asyncBusyConnections.get(username).get(jobId);
+    if(container.hasError){
+      sender().tell(container.error,self());
+      return;
+    }
+    Either<ActorRef, ActorRef> result = container.result;
+    sender().tell(result,self());
+  }
+
+  private void sendJob(Connect connect, AsyncJob job) {
+    String username = job.getUsername();
+    String jobId = job.getJobId();
+    ActorRef subActor = null;
+    // Check if there is available actors to process this
+    subActor = getActorRefFromAsyncPool(username);
+    ViewContext viewContext = job.getViewContext();
+    if (subActor == null) {
+      Optional<HdfsApi> hdfsApiOptional = hdfsApiSupplier.get(viewContext);
+      if (!hdfsApiOptional.isPresent()) {
+        sender().tell(new JobRejected(username, jobId, "Failed to connect to Hive."), self());
+        return;
+      }
+      HdfsApi hdfsApi = hdfsApiOptional.get();
+
+      subActor = system.actorOf(
+        Props.create(AsyncJdbcConnector.class, viewContext, hdfsApi, system, self(),
+          deathWatch, connectionSupplier.get(viewContext),
+          storageSupplier.get(viewContext)).withDispatcher("akka.actor.jdbc-connector-dispatcher"),
+        username + ":" + "jobId:" + jobId + ":" + UUID.randomUUID().toString() + ":asyncjdbcConnector");
+      deathWatch.tell(new RegisterActor(subActor),self());
+
+    }
+
+    if (asyncBusyConnections.containsKey(username)) {
+      Map<String, ActorRefResultContainer> actors = asyncBusyConnections.get(username);
+      if (!actors.containsKey(jobId)) {
+        actors.put(jobId, new ActorRefResultContainer(subActor));
+      } else {
+        // Reject this as with the same jobId one connection is already in progress.
+        sender().tell(new JobRejected(username, jobId, "Existing job in progress with same jobId."), ActorRef.noSender());
+      }
+    } else {
+      Map<String, ActorRefResultContainer> actors = new HashMap<>();
+      actors.put(jobId, new ActorRefResultContainer(subActor));
+      asyncBusyConnections.put(username, actors);
+    }
+
+    // set up the connect with ExecuteJob id for terminations
+    subActor.tell(connect, self());
+    subActor.tell(job, self());
+
+  }
+
+  private ActorRef getActorRefFromSyncPool(String username) {
+    return getActorRefFromPool(syncAvailableConnections, username);
+  }
+
+  private ActorRef getActorRefFromAsyncPool(String username) {
+    return getActorRefFromPool(asyncAvailableConnections, username);
+  }
+
+  private ActorRef getActorRefFromPool(Map<String, Queue<ActorRef>> pool, String username) {
+    ActorRef subActor = null;
+    if (pool.containsKey(username)) {
+      Queue<ActorRef> availableActors = pool.get(username);
+      if (availableActors.size() != 0) {
+        subActor = availableActors.poll();
+      }
+    } else {
+      pool.put(username, new LinkedList<ActorRef>());
+    }
+    return subActor;
+  }
+
+  private void sendSyncJob(Connect connect, HiveJob job) {
+    String username = job.getUsername();
+    ActorRef subActor = null;
+    // Check if there is available actors to process this
+    subActor = getActorRefFromSyncPool(username);
+    ViewContext viewContext = job.getViewContext();
+
+    if (subActor == null) {
+      Optional<HdfsApi> hdfsApiOptional = hdfsApiSupplier.get(viewContext);
+      if(!hdfsApiOptional.isPresent()){
+          sender().tell(new JobRejected(username, ExecuteJob.SYNC_JOB_MARKER, "Failed to connect to HDFS."), ActorRef.noSender());
+          return;
+        }
+      HdfsApi hdfsApi = hdfsApiOptional.get();
+
+      subActor = system.actorOf(
+        Props.create(SyncJdbcConnector.class, viewContext, hdfsApi, system, self(),
+          deathWatch, connectionSupplier.get(viewContext),
+          storageSupplier.get(viewContext)).withDispatcher("akka.actor.jdbc-connector-dispatcher"),
+        username + ":" + UUID.randomUUID().toString() + ":SyncjdbcConnector" );
+      deathWatch.tell(new RegisterActor(subActor),self());
+
+    }
+
+    if (syncBusyConnections.containsKey(username)) {
+      Set<ActorRef> actors = syncBusyConnections.get(username);
+      actors.add(subActor);
+    } else {
+      LinkedHashSet<ActorRef> actors = new LinkedHashSet<>();
+      actors.add(subActor);
+      syncBusyConnections.put(username, actors);
+    }
+
+    // Termination requires that the ref is known in case of sync jobs
+    subActor.tell(connect, self());
+    subActor.tell(job, sender());
+  }
+
+
+  private void destroyConnector(DestroyConnector message) {
+    ActorRef sender = getSender();
+    if (message.isForAsync()) {
+      removeFromAsyncBusyPool(message.getUsername(), message.getJobId());
+      removeFromASyncAvailable(message.getUsername(), sender);
+    } else {
+      removeFromSyncBusyPool(message.getUsername(), sender);
+      removeFromSyncAvailable(message.getUsername(), sender);
+    }
+    logMaps();
+  }
+
+  private void freeConnector(FreeConnector message) {
+    LOG.info("About to free connector for job {} and user {}",message.getJobId(),message.getUsername());
+    ActorRef sender = getSender();
+    if (message.isForAsync()) {
+      Optional<ActorRef> refOptional = removeFromAsyncBusyPool(message.getUsername(), message.getJobId());
+      if (refOptional.isPresent()) {
+        addToAsyncAvailable(message.getUsername(), refOptional.get());
+      }
+      return;
+    }
+    // Was a sync job, remove from sync pool
+    Optional<ActorRef> refOptional = removeFromSyncBusyPool(message.getUsername(), sender);
+    if (refOptional.isPresent()) {
+      addToSyncAvailable(message.getUsername(), refOptional.get());
+    }
+
+
+    logMaps();
+
+  }
+
+  private void logMaps() {
+    LOG.info("Pool status");
+    LoggingOutputStream out = new LoggingOutputStream(LOG, LoggingOutputStream.LogLevel.INFO);
+    MapUtils.debugPrint(new PrintStream(out), "Busy Async connections", asyncBusyConnections);
+    MapUtils.debugPrint(new PrintStream(out), "Available Async connections", asyncAvailableConnections);
+    MapUtils.debugPrint(new PrintStream(out), "Busy Sync connections", syncBusyConnections);
+    MapUtils.debugPrint(new PrintStream(out), "Available Sync connections", syncAvailableConnections);
+    try {
+      out.close();
+    } catch (IOException e) {
+      LOG.warn("Cannot close Logging output stream, this may lead to leaks");
+    }
+  }
+
+  private Optional<ActorRef> removeFromSyncBusyPool(String userName, ActorRef refToFree) {
+    if (syncBusyConnections.containsKey(userName)) {
+      Set<ActorRef> actorRefs = syncBusyConnections.get(userName);
+      actorRefs.remove(refToFree);
+    }
+    return Optional.of(refToFree);
+  }
+
+  private Optional<ActorRef> removeFromAsyncBusyPool(String username, String jobId) {
+    ActorRef ref = null;
+    if (asyncBusyConnections.containsKey(username)) {
+      Map<String, ActorRefResultContainer> actors = asyncBusyConnections.get(username);
+      if (actors.containsKey(jobId)) {
+        ref = actors.get(jobId).actorRef;
+        actors.remove(jobId);
+      }
+    }
+    return Optional.fromNullable(ref);
+  }
+
+  private void addToAsyncAvailable(String username, ActorRef actor) {
+    addToAvailable(asyncAvailableConnections, username, actor);
+  }
+
+  private void addToSyncAvailable(String username, ActorRef actor) {
+    addToAvailable(syncAvailableConnections, username, actor);
+  }
+
+  private void addToAvailable(Map<String, Queue<ActorRef>> pool, String username, ActorRef actor) {
+    if (!pool.containsKey(username)) {
+      pool.put(username, new LinkedList<ActorRef>());
+    }
+
+    Queue<ActorRef> availableActors = pool.get(username);
+    availableActors.add(actor);
+  }
+
+  private void removeFromASyncAvailable(String username, ActorRef sender) {
+    removeFromAvailable(asyncAvailableConnections, username, sender);
+  }
+
+  private void removeFromSyncAvailable(String username, ActorRef sender) {
+    removeFromAvailable(syncAvailableConnections, username, sender);
+  }
+
+  private void removeFromAvailable(Map<String, Queue<ActorRef>> pool, String username, ActorRef sender) {
+    if (!pool.containsKey(username)) {
+      return;
+    }
+    Queue<ActorRef> actors = pool.get(username);
+    actors.remove(sender);
+  }
+
+  private static class ActorRefResultContainer {
+
+    ActorRef actorRef;
+    boolean hasError = false;
+    Either<ActorRef, ActorRef> result = Either.none();
+    AsyncExecutionFailed error;
+
+    public ActorRefResultContainer(ActorRef actorRef) {
+      this.actorRef = actorRef;
+    }
+  }
+
+
+}
+
+

+ 219 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/ResultSetIterator.java

@@ -0,0 +1,219 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import com.google.common.collect.Lists;
+import org.apache.ambari.view.hive2.actor.message.CursorReset;
+import org.apache.ambari.view.hive2.actor.message.JobExecutionCompleted;
+import org.apache.ambari.view.hive2.actor.message.ResetCursor;
+import org.apache.ambari.view.hive2.client.ColumnDescription;
+import org.apache.ambari.view.hive2.client.ColumnDescriptionShort;
+import org.apache.ambari.view.hive2.client.Row;
+import org.apache.ambari.view.hive2.persistence.Storage;
+import org.apache.ambari.view.hive2.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.Job;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.JobImpl;
+import org.apache.ambari.view.hive2.actor.message.AdvanceCursor;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.job.FetchFailed;
+import org.apache.ambari.view.hive2.actor.message.job.Next;
+import org.apache.ambari.view.hive2.actor.message.job.NoMoreItems;
+import org.apache.ambari.view.hive2.actor.message.job.Result;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.CleanUp;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.KeepAlive;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.util.List;
+
+public class ResultSetIterator extends HiveActor {
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  private static final int DEFAULT_BATCH_SIZE = 100;
+  public static final String NULL = "NULL";
+
+  private final ActorRef parent;
+  private final ResultSet resultSet;
+  private final int batchSize;
+
+  private List<ColumnDescription> columnDescriptions;
+  private int columnCount;
+  private Storage storage;
+  boolean async = false;
+  private boolean jobCompleteMessageSent = false;
+
+
+  private boolean metaDataFetched = false;
+
+  public ResultSetIterator(ActorRef parent, ResultSet resultSet, int batchSize) {
+    this.parent = parent;
+    this.resultSet = resultSet;
+    this.batchSize = batchSize;
+  }
+
+
+  public ResultSetIterator(ActorRef parent, ResultSet resultSet, Storage storage) {
+    this(parent, resultSet);
+    this.storage = storage;
+    this.async = true;
+  }
+
+  public ResultSetIterator(ActorRef parent, ResultSet resultSet) {
+    this(parent, resultSet, DEFAULT_BATCH_SIZE);
+  }
+
+  @Override
+  void handleMessage(HiveMessage hiveMessage) {
+    LOG.info("Result set Iterator wil handle message {}", hiveMessage);
+    sendKeepAlive();
+    Object message = hiveMessage.getMessage();
+    if (message instanceof Next) {
+      getNext();
+    }
+    if (message instanceof ResetCursor) {
+      resetResultSet();
+    }
+
+    if (message instanceof KeepAlive) {
+      sendKeepAlive();
+    }
+    if (message instanceof AdvanceCursor) {
+      AdvanceCursor moveCursor = (AdvanceCursor) message;
+      advanceCursor(moveCursor);
+    }
+
+  }
+
+  private void advanceCursor(AdvanceCursor moveCursor) {
+    String jobid = moveCursor.getJob();
+    try {
+      // Block here so that we can update the job status
+      resultSet.next();
+      // Resetting the resultset as it needs to fetch from the beginning when the result is asked for.
+      resultSet.beforeFirst();
+      LOG.info("Job execution successful. Setting status in db.");
+      updateJobStatus(jobid, Job.JOB_STATE_FINISHED);
+      sendJobCompleteMessageIfNotDone();
+    } catch (SQLException e) {
+      LOG.error("Failed to reset the cursor after advancing. Setting error state in db.", e);
+      updateJobStatus(jobid, Job.JOB_STATE_ERROR);
+      sender().tell(new FetchFailed("Failed to reset the cursor after advancing", e), self());
+      cleanUpResources();
+    }
+  }
+
+  private void updateJobStatus(String jobid, String status) {
+    try {
+      JobImpl job = storage.load(JobImpl.class, jobid);
+      job.setStatus(status);
+      storage.store(JobImpl.class, job);
+    } catch (ItemNotFound itemNotFound) {
+      // Cannot do anything
+    }
+  }
+
+  private void resetResultSet() {
+    try {
+      resultSet.beforeFirst();
+      sender().tell(new CursorReset(), self());
+    } catch (SQLException e) {
+      LOG.error("Failed to reset the cursor", e);
+      sender().tell(new FetchFailed("Failed to reset the cursor", e), self());
+      cleanUpResources();
+    }
+  }
+
+  private void sendKeepAlive() {
+    LOG.debug("Sending a keep alive to {}", parent);
+    parent.tell(new KeepAlive(), self());
+  }
+
+  private void getNext() {
+    List<Row> rows = Lists.newArrayList();
+    if (!metaDataFetched) {
+      try {
+        initialize();
+      } catch (SQLException ex) {
+        LOG.error("Failed to fetch metadata for the ResultSet", ex);
+        sender().tell(new FetchFailed("Failed to get metadata for ResultSet", ex), self());
+        cleanUpResources();
+      }
+    }
+    int index = 0;
+    try {
+      while (resultSet.next() && index < batchSize) {
+        index++;
+        rows.add(getRowFromResultSet(resultSet));
+        sendJobCompleteMessageIfNotDone();
+      }
+
+      if (index == 0) {
+        // We have hit end of resultSet
+        sender().tell(new NoMoreItems(), self());
+        if(!async) {
+          cleanUpResources();
+        }
+      } else {
+        Result result = new Result(rows, columnDescriptions);
+        sender().tell(result, self());
+      }
+
+    } catch (SQLException ex) {
+      LOG.error("Failed to fetch next batch for the Resultset", ex);
+      sender().tell(new FetchFailed("Failed to fetch next batch for the Resultset", ex), self());
+      cleanUpResources();
+    }
+  }
+
+  private void sendJobCompleteMessageIfNotDone() {
+    if (!jobCompleteMessageSent) {
+      jobCompleteMessageSent = true;
+      parent.tell(new JobExecutionCompleted(), self());
+    }
+  }
+
+  private void cleanUpResources() {
+    parent.tell(new CleanUp(), self());
+  }
+
+  private Row getRowFromResultSet(ResultSet resultSet) throws SQLException {
+    Object[] values = new Object[columnCount];
+    for (int i = 0; i < columnCount; i++) {
+      values[i] = resultSet.getObject(i + 1);
+    }
+    return new Row(values);
+  }
+
+  private void initialize() throws SQLException {
+    metaDataFetched = true;
+    ResultSetMetaData metaData = resultSet.getMetaData();
+    columnCount = metaData.getColumnCount();
+    columnDescriptions = Lists.newArrayList();
+    for (int i = 1; i <= columnCount; i++) {
+      String columnName = metaData.getColumnName(i);
+      String typeName = metaData.getColumnTypeName(i);
+      ColumnDescription description = new ColumnDescriptionShort(columnName, typeName, i);
+      columnDescriptions.add(description);
+    }
+  }
+}

+ 174 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/SyncJdbcConnector.java

@@ -0,0 +1,174 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.PoisonPill;
+import akka.actor.Props;
+import com.google.common.base.Optional;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.actor.message.RegisterActor;
+import org.apache.ambari.view.hive2.persistence.Storage;
+import org.apache.ambari.view.hive2.ConnectionDelegate;
+import org.apache.ambari.view.hive2.actor.message.GetColumnMetadataJob;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+import org.apache.ambari.view.hive2.actor.message.SyncJob;
+import org.apache.ambari.view.hive2.actor.message.job.ExecutionFailed;
+import org.apache.ambari.view.hive2.actor.message.job.NoResult;
+import org.apache.ambari.view.hive2.actor.message.job.ResultSetHolder;
+import org.apache.ambari.view.utils.hdfs.HdfsApi;
+import org.apache.hive.jdbc.HiveConnection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+public class SyncJdbcConnector extends JdbcConnector {
+
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+  private ActorRef resultSetActor = null;
+
+  public SyncJdbcConnector(ViewContext viewContext, HdfsApi hdfsApi, ActorSystem system, ActorRef parent,ActorRef deathWatch, ConnectionDelegate connectionDelegate, Storage storage) {
+    super(viewContext, hdfsApi, system, parent,deathWatch, connectionDelegate, storage);
+  }
+
+  @Override
+  protected void handleJobMessage(HiveMessage message) {
+    Object job = message.getMessage();
+    if(job instanceof SyncJob) {
+      execute((SyncJob) job);
+    } else if (job instanceof GetColumnMetadataJob) {
+      getColumnMetaData((GetColumnMetadataJob) job);
+    }
+  }
+
+  @Override
+  protected boolean isAsync() {
+    return false;
+  }
+
+  @Override
+  protected void cleanUpChildren() {
+    if(resultSetActor != null && !resultSetActor.isTerminated()) {
+      LOG.debug("Sending poison pill to log aggregator");
+      resultSetActor.tell(PoisonPill.getInstance(), self());
+    }
+  }
+
+  @Override
+  protected void notifyFailure() {
+    sender().tell(new ExecutionFailed("Cannot connect to hive"), ActorRef.noSender());
+  }
+
+  protected void execute(final SyncJob job) {
+    this.executing = true;
+    executeJob(new Operation<SyncJob>() {
+      @Override
+      SyncJob getJob() {
+        return job;
+      }
+
+      @Override
+      Optional<ResultSet> call(HiveConnection connection) throws SQLException {
+        return connectionDelegate.executeSync(connection, job);
+      }
+
+      @Override
+      String notConnectedErrorMessage() {
+        return "Cannot execute sync job for user: " + job.getUsername() + ". Not connected to Hive";
+      }
+
+      @Override
+      String executionFailedErrorMessage() {
+        return "Failed to execute Jdbc Statement";
+      }
+    });
+  }
+
+
+  private void getColumnMetaData(final GetColumnMetadataJob job) {
+    executeJob(new Operation<GetColumnMetadataJob>() {
+
+      @Override
+      GetColumnMetadataJob getJob() {
+        return job;
+      }
+
+      @Override
+      Optional<ResultSet> call(HiveConnection connection) throws SQLException {
+        return connectionDelegate.getColumnMetadata(connection, job);
+      }
+
+      @Override
+      String notConnectedErrorMessage() {
+        return String.format("Cannot get column metadata for user: %s, schema: %s, table: %s, column: %s" +
+            ". Not connected to Hive", job.getUsername(), job.getSchemaPattern(), job.getTablePattern(),
+          job.getColumnPattern());
+      }
+
+      @Override
+      String executionFailedErrorMessage() {
+        return "Failed to execute Jdbc Statement";
+      }
+    });
+  }
+
+  private void executeJob(Operation operation) {
+    ActorRef sender = this.getSender();
+    String errorMessage = operation.notConnectedErrorMessage();
+    if (connectable == null) {
+      sender.tell(new ExecutionFailed(errorMessage), ActorRef.noSender());
+      cleanUp();
+      return;
+    }
+
+    Optional<HiveConnection> connectionOptional = connectable.getConnection();
+    if (!connectionOptional.isPresent()) {
+      sender.tell(new ExecutionFailed(errorMessage), ActorRef.noSender());
+      cleanUp();
+      return;
+    }
+
+    try {
+      Optional<ResultSet> resultSetOptional = operation.call(connectionOptional.get());
+      if(resultSetOptional.isPresent()) {
+        ActorRef resultSetActor = getContext().actorOf(Props.create(ResultSetIterator.class, self(),
+          resultSetOptional.get()).withDispatcher("akka.actor.result-dispatcher"));
+        deathWatch.tell(new RegisterActor(resultSetActor),self());
+        sender.tell(new ResultSetHolder(resultSetActor), self());
+      } else {
+        sender.tell(new NoResult(), self());
+        cleanUp();
+      }
+    } catch (SQLException e) {
+      LOG.error(operation.executionFailedErrorMessage(), e);
+      sender.tell(new ExecutionFailed(operation.executionFailedErrorMessage(), e), self());
+      cleanUp();
+    }
+  }
+
+  private abstract class Operation<T> {
+    abstract T getJob();
+    abstract Optional<ResultSet> call(HiveConnection connection) throws SQLException;
+    abstract String notConnectedErrorMessage();
+    abstract String executionFailedErrorMessage();
+  }
+}

+ 32 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/YarnAtsParser.java

@@ -0,0 +1,32 @@
+/*
+ * 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.ambari.view.hive2.actor;
+
+import akka.actor.UntypedActor;
+import org.apache.ambari.view.hive2.actor.message.HiveMessage;
+
+/**
+ * Queries YARN/ATS time to time to fetch the status of the ExecuteJob and updates database
+ */
+public class YarnAtsParser extends HiveActor {
+  @Override
+  public void handleMessage(HiveMessage hiveMessage) {
+
+  }
+}

+ 32 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AdvanceCursor.java

@@ -0,0 +1,32 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class AdvanceCursor {
+
+    private String job;
+
+    public AdvanceCursor(String job) {
+        this.job = job;
+    }
+
+    public String getJob() {
+        return job;
+    }
+}

+ 48 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AssignResultSet.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.ambari.view.hive2.actor.message;
+
+import com.google.common.base.Optional;
+
+import java.sql.ResultSet;
+
+public class AssignResultSet {
+
+    private Optional<ResultSet> resultSet;
+
+
+    public AssignResultSet(Optional<ResultSet> resultSet) {
+        this.resultSet = resultSet;
+
+    }
+
+
+    public ResultSet getResultSet() {
+        return resultSet.orNull();
+    }
+
+
+    @Override
+    public String toString() {
+        return "ExtractResultSet{" +
+                "resultSet=" + resultSet +
+                '}';
+    }
+
+}

+ 46 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AssignStatement.java

@@ -0,0 +1,46 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import com.google.common.base.Optional;
+
+import java.sql.Statement;
+
+public class AssignStatement {
+
+    private Statement resultSet;
+
+    public AssignStatement(Statement statement) {
+        this.resultSet = statement;
+    }
+
+
+    public Statement getStatement() {
+        return resultSet;
+    }
+
+    @Override
+    public String toString() {
+        return "AssignStatement{" +
+                "resultSet=" + resultSet +
+                '}';
+    }
+
+
+}

+ 52 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/AsyncJob.java

@@ -0,0 +1,52 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import org.apache.ambari.view.ViewContext;
+
+/**
+ * Message to be sent when a statement has to be executed
+ */
+public class AsyncJob extends DDLJob {
+  private final String jobId;
+  private final String logFile;
+
+  public AsyncJob(String jobId, String username, String[] statements, String logFile,ViewContext viewContext) {
+    super(Type.ASYNC, statements, username,viewContext);
+    this.jobId = jobId;
+    this.logFile = logFile;
+  }
+
+  public String getJobId() {
+    return jobId;
+  }
+
+  public String getLogFile() {
+    return logFile;
+  }
+
+
+  @Override
+  public String toString() {
+    return "AsyncJob{" +
+            "jobId='" + jobId + '\'' +
+            ", logFile='" + logFile + '\'' +
+            "} " + super.toString();
+  }
+}

+ 56 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/Connect.java

@@ -0,0 +1,56 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import org.apache.ambari.view.hive2.internal.Connectable;
+import org.apache.ambari.view.hive2.internal.HiveConnectionWrapper;
+
+/**
+ * Connect message to be sent to the Connection Actor with the connection parameters
+ */
+public class Connect {
+
+  private final String username;
+  private final String password;
+  private final String jdbcUrl;
+
+
+  public Connect(String username, String password, String jdbcUrl) {
+    this.username = username;
+    this.password = password;
+    this.jdbcUrl = jdbcUrl;
+  }
+
+  public Connectable getConnectable(){
+    return new HiveConnectionWrapper(getJdbcUrl(),username,password);
+  }
+
+  public String getUsername() {
+    return username;
+  }
+
+  public String getPassword() {
+    return password;
+  }
+
+  public String getJdbcUrl() {
+    return jdbcUrl;
+  }
+
+}

+ 22 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/CursorReset.java

@@ -0,0 +1,22 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class CursorReset {
+}

+ 73 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/DDLJob.java

@@ -0,0 +1,73 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.ambari.view.ViewContext;
+import org.apache.commons.lang.StringUtils;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+
+public class DDLJob extends HiveJob {
+
+  public static final String SEMICOLON = ";";
+  private String[] statements;
+
+  public DDLJob(Type type, String[] statements, String username, ViewContext viewContext) {
+    super(type, username, viewContext);
+    this.statements = new String[statements.length];
+    for (int i = 0; i < statements.length; i++) {
+      this.statements[i] = clean(statements[i]);
+
+    }
+
+  }
+
+  private String clean(String statement) {
+    return StringUtils.trim(statement);
+  }
+
+  public Collection<String> getStatements() {
+    return Arrays.asList(statements);
+  }
+
+  /**
+   * Get the statements to be executed synchronously
+   *
+   * @return
+   */
+  public Collection<String> getSyncStatements() {
+    if (!(statements.length > 1))
+      return Collections.emptyList();
+    else
+      return ImmutableList.copyOf(Arrays.copyOfRange(statements, 0, statements.length - 1));
+  }
+
+  /**
+   * Get the statement to be executed asynchronously
+   *
+   * @return async statement
+   */
+  public String getAsyncStatement() {
+    return statements[statements.length - 1];
+  }
+}

+ 38 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ExecuteJob.java

@@ -0,0 +1,38 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class ExecuteJob {
+  public final static String SYNC_JOB_MARKER = "SYNC";
+  private final Connect connect;
+  private final HiveJob job;
+
+  public ExecuteJob(Connect connect, HiveJob job) {
+    this.connect = connect;
+    this.job = job;
+  }
+
+  public Connect getConnect() {
+    return connect;
+  }
+
+  public HiveJob getJob() {
+    return job;
+  }
+}

+ 23 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ExecuteQuery.java

@@ -0,0 +1,23 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class ExecuteQuery {
+
+}

+ 42 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/FetchError.java

@@ -0,0 +1,42 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+/**
+ *
+ * Fetch the result for
+ *
+ */
+public class FetchError {
+    private final String jobId;
+    private final String username;
+
+    public FetchError(String jobId, String username) {
+        this.jobId = jobId;
+        this.username = username;
+    }
+
+    public String getJobId() {
+        return jobId;
+    }
+
+    public String getUsername() {
+        return username;
+    }
+}

+ 42 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/FetchResult.java

@@ -0,0 +1,42 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+/**
+ *
+ * Fetch the result for
+ *
+ */
+public class FetchResult {
+    private final String jobId;
+    private final String username;
+
+    public FetchResult(String jobId, String username) {
+        this.jobId = jobId;
+        this.username = username;
+    }
+
+    public String getJobId() {
+        return jobId;
+    }
+
+    public String getUsername() {
+        return username;
+    }
+}

+ 60 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/GetColumnMetadataJob.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.ambari.view.hive2.actor.message;
+
+import org.apache.ambari.view.ViewContext;
+
+public class GetColumnMetadataJob extends HiveJob {
+  private final String schemaPattern;
+  private final String tablePattern;
+  private final String columnPattern;
+  public GetColumnMetadataJob(String username, ViewContext viewContext,
+                              String schemaPattern, String tablePattern, String columnPattern) {
+    super(Type.SYNC, username, viewContext);
+    this.schemaPattern = schemaPattern;
+    this.tablePattern = tablePattern;
+    this.columnPattern = columnPattern;
+  }
+
+  public GetColumnMetadataJob(String username, ViewContext viewContext,
+                              String tablePattern, String columnPattern) {
+    this(username, viewContext, "*", tablePattern, columnPattern);
+  }
+
+  public GetColumnMetadataJob(String username, ViewContext viewContext,
+                              String columnPattern) {
+    this(username, viewContext, "*", "*", columnPattern);
+  }
+
+  public GetColumnMetadataJob(String username, ViewContext viewContext) {
+    this(username, viewContext, "*", "*", "*");
+  }
+
+  public String getSchemaPattern() {
+    return schemaPattern;
+  }
+
+  public String getTablePattern() {
+    return tablePattern;
+  }
+
+  public String getColumnPattern() {
+    return columnPattern;
+  }
+}

+ 22 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/GetMoreLogs.java

@@ -0,0 +1,22 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+
+public class GetMoreLogs {}

+ 63 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/HiveJob.java

@@ -0,0 +1,63 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.ambari.view.ViewContext;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+public abstract class HiveJob {
+
+  private final String username;
+  private final Type type;
+  private final ViewContext viewContext;
+
+  public HiveJob(Type type, String username,ViewContext viewContext) {
+    this.type = type;
+    this.username = username;
+    this.viewContext = viewContext;
+  }
+
+  public String getUsername() {
+    return username;
+  }
+
+
+
+
+  public Type getType() {
+    return type;
+  }
+
+
+
+  public ViewContext getViewContext() {
+    return viewContext;
+  }
+
+
+  public enum Type {
+    SYNC,
+    ASYNC
+  }
+
+}

+ 53 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/HiveMessage.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.ambari.view.hive2.actor.message;
+
+
+import java.util.UUID;
+
+/**
+ * Message wrapper, Each message has a unique ID
+ */
+public class HiveMessage {
+
+    private String id = UUID.randomUUID().toString();
+
+    private Object message;
+
+    public HiveMessage(Object message) {
+        this.message = message;
+    }
+
+
+    public Object getMessage() {
+        return message;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    @Override
+    public String toString() {
+        return "HiveMessage{" +
+                "message=" + message +
+                ", id='" + id + '\'' +
+                '}';
+    }
+}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/JobExecutionCompleted.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class JobExecutionCompleted {}

+ 44 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/JobRejected.java

@@ -0,0 +1,44 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class JobRejected {
+
+  private final String username;
+  private final String jobId;
+  private final String message;
+
+  public JobRejected(String username, String jobId, String message) {
+    this.username = username;
+    this.jobId = jobId;
+    this.message = message;
+  }
+
+  public String getUsername() {
+    return username;
+  }
+
+  public String getJobId() {
+    return jobId;
+  }
+
+  public String getMessage() {
+    return message;
+  }
+}

+ 38 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/JobSubmitted.java

@@ -0,0 +1,38 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class JobSubmitted {
+
+  private final String username;
+  private final String jobId;
+
+  public JobSubmitted(String username, String jobId) {
+    this.username = username;
+    this.jobId = jobId;
+  }
+
+  public String getUsername() {
+    return username;
+  }
+
+  public String getJobId() {
+    return jobId;
+  }
+}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/LogAggregationFinished.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class LogAggregationFinished {}

+ 34 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/RegisterActor.java

@@ -0,0 +1,34 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import akka.actor.ActorRef;
+
+public class RegisterActor {
+
+    private ActorRef actorRef;
+
+    public RegisterActor(ActorRef actorRef) {
+        this.actorRef = actorRef;
+    }
+
+    public ActorRef getActorRef() {
+        return actorRef;
+    }
+}

+ 22 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ResetCursor.java

@@ -0,0 +1,22 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class ResetCursor {
+}

+ 47 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/ResultReady.java

@@ -0,0 +1,47 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import akka.actor.ActorRef;
+import org.apache.ambari.view.hive2.actor.message.job.AsyncExecutionFailed;
+import org.apache.ambari.view.hive2.internal.Either;
+
+/**
+ *
+ * Fetch the result for
+ *
+ */
+public class ResultReady extends FetchResult {
+    private Either<ActorRef, ActorRef> result;
+
+
+    public ResultReady(String jobId, String username, Either<ActorRef, ActorRef> result) {
+        super(jobId, username);
+        this.result = result;
+    }
+
+    public Either<ActorRef, ActorRef> getResult() {
+        return result;
+    }
+
+    public void setResult(Either<ActorRef, ActorRef> result) {
+        this.result = result;
+    }
+}
+

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/StartLogAggregation.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+public class StartLogAggregation {}

+ 27 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/SyncJob.java

@@ -0,0 +1,27 @@
+/*
+ * 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.ambari.view.hive2.actor.message;
+
+import org.apache.ambari.view.ViewContext;
+
+public class SyncJob extends DDLJob {
+  public SyncJob(String username, String[] statements,ViewContext viewContext) {
+    super(Type.SYNC, statements, username,viewContext);
+  }
+}

+ 46 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/AsyncExecutionFailed.java

@@ -0,0 +1,46 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+public class AsyncExecutionFailed extends ExecutionFailed {
+  private final String jobId;
+  private final String username;
+
+  public AsyncExecutionFailed(String jobId,String username, String message, Throwable error) {
+    super(message, error);
+    this.jobId = jobId;
+    this.username = username;
+  }
+
+  public AsyncExecutionFailed(String jobId,String username, String message) {
+    super(message);
+    this.jobId = jobId;
+    this.username = username;
+  }
+
+
+
+  public String getJobId() {
+    return jobId;
+  }
+
+  public String getUsername() {
+    return username;
+  }
+}

+ 31 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/ExecutionFailed.java

@@ -0,0 +1,31 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+public class ExecutionFailed extends Failure {
+
+  public ExecutionFailed(String message, Throwable error) {
+    super(message, error);
+  }
+
+  public ExecutionFailed(String message) {
+    super(message, new Exception(message));
+  }
+
+}

+ 37 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/Failure.java

@@ -0,0 +1,37 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+public class Failure {
+  private final Throwable error;
+  private final String message;
+
+  public Failure(String message, Throwable error) {
+    this.message = message;
+    this.error = error;
+  }
+
+  public Throwable getError() {
+    return error;
+  }
+
+  public String getMessage() {
+    return message;
+  }
+}

+ 31 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/FetchFailed.java

@@ -0,0 +1,31 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+public class FetchFailed extends Failure{
+
+  public FetchFailed(String message, Throwable error) {
+    super(message, error);
+  }
+
+  public FetchFailed(String message) {
+    this(message, new Exception(message));
+  }
+
+}

+ 22 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/Next.java

@@ -0,0 +1,22 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+public class Next {
+}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/NoMoreItems.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+public class NoMoreItems {}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/NoResult.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+public class NoResult {}

+ 43 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/Result.java

@@ -0,0 +1,43 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.ambari.view.hive2.client.ColumnDescription;
+import org.apache.ambari.view.hive2.client.Row;
+
+import java.util.List;
+
+public class Result {
+  private final List<ColumnDescription> columns;
+  private final List<Row> rows;
+
+  public Result(List<Row> rows, List<ColumnDescription> columns) {
+    this.rows = ImmutableList.copyOf(rows);
+    this.columns = columns;
+  }
+
+  public List<Row> getRows() {
+    return rows;
+  }
+
+  public List<ColumnDescription> getColumns() {
+    return columns;
+  }
+}

+ 33 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/job/ResultSetHolder.java

@@ -0,0 +1,33 @@
+/*
+ * 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.ambari.view.hive2.actor.message.job;
+
+import akka.actor.ActorRef;
+
+public class ResultSetHolder {
+  private final ActorRef iterator;
+
+  public ResultSetHolder(ActorRef iterator) {
+    this.iterator = iterator;
+  }
+
+  public ActorRef getIterator() {
+    return iterator;
+  }
+}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/CleanUp.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message.lifecycle;
+
+public class CleanUp {}

+ 52 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/DestroyConnector.java

@@ -0,0 +1,52 @@
+/*
+ * 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.ambari.view.hive2.actor.message.lifecycle;
+
+public class DestroyConnector {
+  private final String username;
+  private final String jobId;
+  private final boolean forAsync;
+
+  public DestroyConnector(String username, String jobId, boolean forAsync) {
+    this.username = username;
+    this.jobId = jobId;
+    this.forAsync = forAsync;
+  }
+
+  public String getUsername() {
+    return username;
+  }
+
+  public String getJobId() {
+    return jobId;
+  }
+
+  public boolean isForAsync() {
+    return forAsync;
+  }
+
+  @Override
+  public String toString() {
+    return "DestroyConnector{" +
+      "username='" + username + '\'' +
+      ", jobId='" + jobId + '\'' +
+      ", forAsync=" + forAsync +
+      '}';
+  }
+}

+ 53 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/FreeConnector.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.ambari.view.hive2.actor.message.lifecycle;
+
+public class FreeConnector  {
+
+  private final String username;
+  private final String jobId;
+  private final boolean forAsync;
+
+  public FreeConnector(String username, String jobId, boolean forAsync) {
+    this.username = username;
+    this.jobId = jobId;
+    this.forAsync = forAsync;
+  }
+
+  public String getUsername() {
+    return username;
+  }
+
+  public String getJobId() {
+    return jobId;
+  }
+
+  public boolean isForAsync() {
+    return forAsync;
+  }
+
+  @Override
+  public String toString() {
+    return "FreeConnector{" +
+      "username='" + username + '\'' +
+      ", jobId='" + jobId + '\'' +
+      ", forAsync=" + forAsync +
+      '}';
+  }
+}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/InactivityCheck.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message.lifecycle;
+
+public class InactivityCheck {}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/KeepAlive.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message.lifecycle;
+
+public class KeepAlive {}

+ 21 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/actor/message/lifecycle/TerminateInactivityCheck.java

@@ -0,0 +1,21 @@
+/*
+ * 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.ambari.view.hive2.actor.message.lifecycle;
+
+public class TerminateInactivityCheck {}

+ 84 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/backgroundjobs/BackgroundJobController.java

@@ -0,0 +1,84 @@
+/**
+ * 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.ambari.view.hive2.backgroundjobs;
+
+import org.apache.ambari.view.ViewContext;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class BackgroundJobController {
+  private ViewContext context;
+
+  protected BackgroundJobController(ViewContext context) {
+    this.context = context;
+  }
+
+  private static Map<String, BackgroundJobController> viewSingletonObjects = new HashMap<String, BackgroundJobController>();
+  public static BackgroundJobController getInstance(ViewContext context) {
+    if (!viewSingletonObjects.containsKey(context.getInstanceName()))
+      viewSingletonObjects.put(context.getInstanceName(), new BackgroundJobController(context));
+    return viewSingletonObjects.get(context.getInstanceName());
+  }
+
+  private Map<String, Thread> jobs = new HashMap<String, Thread>();
+  public void startJob(String key, Runnable runnable) {
+    if (jobs.containsKey(key)) {
+      interrupt(key);
+      try {
+        jobs.get(key).join();
+      } catch (InterruptedException ignored) {
+      }
+    }
+    Thread t = new Thread(runnable);
+    jobs.put(key, t);
+    t.start();
+  }
+
+  public Thread.State state(String key) {
+    if (!jobs.containsKey(key)) {
+      return Thread.State.TERMINATED;
+    }
+
+    Thread.State state = jobs.get(key).getState();
+
+    if (state == Thread.State.TERMINATED) {
+      jobs.remove(key);
+    }
+
+    return state;
+  }
+
+  public boolean interrupt(String key) {
+    if (!jobs.containsKey(key)) {
+      return false;
+    }
+
+    jobs.get(key).interrupt();
+    return true;
+  }
+
+  public boolean isInterrupted(String key) {
+    if (state(key) == Thread.State.TERMINATED) {
+      return true;
+    }
+
+    return jobs.get(key).isInterrupted();
+  }
+}

+ 36 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/AsyncJobRunner.java

@@ -0,0 +1,36 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import com.google.common.base.Optional;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.Job;
+import org.apache.ambari.view.hive2.actor.message.AsyncJob;
+import org.apache.ambari.view.hive2.actor.message.job.AsyncExecutionFailed;
+
+public interface AsyncJobRunner {
+
+    void submitJob(ConnectionConfig connectionConfig, AsyncJob asyncJob, Job job);
+
+    Optional<NonPersistentCursor> getCursor(String jobId, String username);
+
+    Optional<NonPersistentCursor> resetAndGetCursor(String jobId, String username);
+
+    Optional<AsyncExecutionFailed> getError(String jobId, String username);
+
+}

+ 115 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/AsyncJobRunnerImpl.java

@@ -0,0 +1,115 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Inbox;
+import com.google.common.base.Optional;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.actor.message.CursorReset;
+import org.apache.ambari.view.hive2.actor.message.FetchError;
+import org.apache.ambari.view.hive2.actor.message.ResetCursor;
+import org.apache.ambari.view.hive2.resources.jobs.viewJobs.Job;
+import org.apache.ambari.view.hive2.actor.message.AsyncJob;
+import org.apache.ambari.view.hive2.actor.message.Connect;
+import org.apache.ambari.view.hive2.actor.message.ExecuteJob;
+import org.apache.ambari.view.hive2.actor.message.FetchResult;
+import org.apache.ambari.view.hive2.actor.message.job.AsyncExecutionFailed;
+import org.apache.ambari.view.hive2.internal.Either;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+import java.util.concurrent.TimeUnit;
+
+public class AsyncJobRunnerImpl implements AsyncJobRunner {
+
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  private final ActorRef controller;
+  private final ActorSystem system;
+  private final ViewContext context;
+
+  public AsyncJobRunnerImpl(ViewContext context, ActorRef controller, ActorSystem system) {
+    this.context = context;
+    this.controller = controller;
+    this.system = system;
+  }
+
+
+
+    @Override
+    public void submitJob(ConnectionConfig config, AsyncJob job, Job jobp) {
+        Connect connect = config.createConnectMessage();
+        ExecuteJob executeJob = new ExecuteJob(connect, job);
+        controller.tell(executeJob,ActorRef.noSender());
+    }
+
+  @Override
+  public Optional<NonPersistentCursor> getCursor(String jobId, String username) {
+    Inbox inbox = Inbox.create(system);
+    inbox.send(controller, new FetchResult(jobId, username));
+    Object receive = inbox.receive(Duration.create(1, TimeUnit.MINUTES));
+    Either<ActorRef, ActorRef> result = (Either<ActorRef, ActorRef>) receive;
+    if (result.isRight()) {
+      return Optional.absent();
+
+    } else if (result.isLeft()) {
+      return Optional.of(new NonPersistentCursor(context, system, result.getLeft()));
+    }
+
+    return Optional.absent();
+  }
+
+  @Override
+  public Optional<NonPersistentCursor> resetAndGetCursor(String jobId, String username) {
+    Inbox inbox = Inbox.create(system);
+    inbox.send(controller, new FetchResult(jobId, username));
+    Object receive = inbox.receive(Duration.create(1, TimeUnit.MINUTES));
+    Either<ActorRef, ActorRef> result = (Either<ActorRef, ActorRef>) receive;
+    if (result.isRight()) {
+      return Optional.absent();
+
+    } else if (result.isLeft()) {
+      // Reset the result set cursor
+      inbox.send(result.getLeft(), new ResetCursor());
+      Object resetResult = inbox.receive(Duration.create(1, TimeUnit.MINUTES));
+      if (resetResult instanceof CursorReset) {
+        return Optional.of(new NonPersistentCursor(context, system, result.getLeft()));
+      } else {
+        return Optional.absent();
+      }
+
+    }
+
+    return Optional.absent();
+  }
+
+    @Override
+    public Optional<AsyncExecutionFailed> getError(String jobId, String username) {
+        Inbox inbox = Inbox.create(system);
+        inbox.send(controller, new FetchError(jobId, username));
+        Object receive = inbox.receive(Duration.create(1, TimeUnit.MINUTES));
+        Optional<AsyncExecutionFailed>  result = (Optional<AsyncExecutionFailed>) receive;
+        return result;
+    }
+
+
+}

+ 45 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ColumnDescription.java

@@ -0,0 +1,45 @@
+/**
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.ambari.view.hive2.client;
+
+public interface ColumnDescription {
+  enum DataTypes {
+    TINYINT, //
+    SMALLINT, //
+    INT, //
+    BIGINT, //
+    BOOLEAN, //
+    FLOAT, //
+    DOUBLE, //
+    STRING, //
+    BINARY, // -- (Note: Available in Hive 0.8.0 and later)
+    TIMESTAMP, // -- (Note: Available in Hive 0.8.0 and later)
+    DECIMAL, // -- (Note: Available in Hive 0.11.0 and later)
+    // DECIMAL,(precision, scale)  -- (Note: Available in Hive 0.13.0 and later) Not included.
+    DATE, // -- (Note: Available in Hive 0.12.0 and later)
+    VARCHAR, // -- (Note: Available in Hive 0.12.0 and later)
+    CHAR, // -- (Note: Available in Hive 0.13.0 and later)
+  }
+
+  String getName();
+
+  String getType();
+
+  int getPosition();
+}

+ 74 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ColumnDescriptionExtended.java

@@ -0,0 +1,74 @@
+/**
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.ambari.view.hive2.client;
+
+public class ColumnDescriptionExtended implements ColumnDescription {
+  private String name;
+  private String type;
+  private int position;
+  private String comment;
+  private boolean partitioned;
+  private boolean sortedBy;
+  private boolean clusteredBy;
+
+  public ColumnDescriptionExtended(String name, String type, String comment, boolean partitioned,
+                                   boolean sortedBy, boolean clusteredBy, int position) {
+    this.name = name;
+    this.type = type;
+    this.comment = comment;
+    this.partitioned = partitioned;
+    this.sortedBy = sortedBy;
+    this.clusteredBy = clusteredBy;
+    this.position = position;
+  }
+
+  public ColumnDescription createShortColumnDescription() {
+    return new ColumnDescriptionShort(getName(), getType(), getPosition());
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  public String getType() {
+    return type;
+  }
+
+  public int getPosition() {
+    return position;
+  }
+
+  public String getComment() {
+    return comment;
+  }
+
+  public boolean isPartitioned() {
+    return partitioned;
+  }
+
+  public boolean isSortedBy() {
+    return sortedBy;
+  }
+
+  public boolean isClusteredBy() {
+    return clusteredBy;
+  }
+
+
+}

+ 53 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ColumnDescriptionShort.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.ambari.view.hive2.client;
+
+import java.util.ArrayList;
+
+public class ColumnDescriptionShort extends ArrayList<Object> implements ColumnDescription {
+  private static final int INITIAL_CAPACITY = 3;
+  private String name;
+  private String type;
+  private int position;
+
+  public ColumnDescriptionShort(String name, String type, int position) {
+    super(INITIAL_CAPACITY);
+    add(name);
+    add(type);
+    add(position);
+    this.name = name;
+    this.type = type;
+    this.position = position;
+  }
+
+  @Override
+  public String getName() {
+    return name;
+  }
+
+  @Override
+  public String getType() {
+    return type;
+  }
+
+  @Override
+  public int getPosition() {
+    return position;
+  }
+}

+ 51 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/ConnectionConfig.java

@@ -0,0 +1,51 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import org.apache.ambari.view.hive2.actor.message.Connect;
+
+public class ConnectionConfig {
+  private final String username;
+  private final String password;
+  private final String jdbcUrl;
+
+  public ConnectionConfig(String username, String password, String jdbcUrl) {
+    this.username = username;
+    this.password = password;
+    this.jdbcUrl = jdbcUrl;
+  }
+
+  public String getUsername() {
+    return username;
+  }
+
+  public String getPassword() {
+    return password;
+  }
+
+  public String getJdbcUrl() {
+    return jdbcUrl;
+  }
+
+  public Connect createConnectMessage() {
+    return new Connect(username, password, jdbcUrl);
+  }
+
+
+}

+ 30 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/Cursor.java

@@ -0,0 +1,30 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import java.util.Iterator;
+import java.util.List;
+
+public interface Cursor<T, R> extends Iterator<T>, Iterable<T>{
+  boolean isResettable();
+  void reset();
+  int getOffset();
+  List<R> getDescriptions();
+  void keepAlive();
+}

+ 36 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/DDLDelegator.java

@@ -0,0 +1,36 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import java.util.List;
+
+public interface DDLDelegator {
+
+  List<String> getDbList(ConnectionConfig config, String like);
+
+  List<String> getTableList(ConnectionConfig config, String database, String like);
+
+  List<ColumnDescription> getTableDescription(ConnectionConfig config, String database, String table, String like, boolean extended);
+
+  Cursor<Row, ColumnDescription> getDbListCursor(ConnectionConfig config, String like);
+
+  Cursor<Row, ColumnDescription> getTableListCursor(ConnectionConfig config, String database, String like);
+
+  Cursor<Row, ColumnDescription> getTableDescriptionCursor(ConnectionConfig config, String database, String table, String like, boolean extended);
+}

+ 242 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/DDLDelegatorImpl.java

@@ -0,0 +1,242 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Inbox;
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Optional;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.utils.HiveActorConfiguration;
+import org.apache.ambari.view.hive2.utils.ServiceFormattedException;
+import org.apache.ambari.view.hive2.actor.message.Connect;
+import org.apache.ambari.view.hive2.actor.message.ExecuteJob;
+import org.apache.ambari.view.hive2.actor.message.GetColumnMetadataJob;
+import org.apache.ambari.view.hive2.actor.message.HiveJob;
+import org.apache.ambari.view.hive2.actor.message.SyncJob;
+import org.apache.ambari.view.hive2.actor.message.job.ExecutionFailed;
+import org.apache.ambari.view.hive2.actor.message.job.FetchFailed;
+import org.apache.ambari.view.hive2.actor.message.job.Next;
+import org.apache.ambari.view.hive2.actor.message.job.NoMoreItems;
+import org.apache.ambari.view.hive2.actor.message.job.NoResult;
+import org.apache.ambari.view.hive2.actor.message.job.Result;
+import org.apache.ambari.view.hive2.actor.message.job.ResultSetHolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+public class DDLDelegatorImpl implements DDLDelegator {
+
+  public static final String NO_VALUE_MARKER = "NO_VALUE";
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+
+  private final ActorRef controller;
+  private final ActorSystem system;
+
+  private final ViewContext context;
+  private final HiveActorConfiguration actorConfiguration;
+
+  public DDLDelegatorImpl(ViewContext context, ActorSystem system, ActorRef controller) {
+    this.context = context;
+    this.system = system;
+    this.controller = controller;
+    actorConfiguration = new HiveActorConfiguration(context);
+  }
+
+  @Override
+  public List<String> getDbList(ConnectionConfig config, String like) {
+    Optional<Result> rowsFromDB = getRowsFromDB(config, getDatabaseListStatements(like));
+    return rowsFromDB.isPresent() ? getFirstColumnValues(rowsFromDB.get().getRows()) : Lists.<String>newArrayList();
+  }
+
+  @Override
+  public List<String> getTableList(ConnectionConfig config, String database, String like) {
+    Optional<Result> rowsFromDB = getRowsFromDB(config, getTableListStatements(database, like));
+    return rowsFromDB.isPresent() ? getFirstColumnValues(rowsFromDB.get().getRows()) : Lists.<String>newArrayList();
+  }
+
+  @Override
+  public List<ColumnDescription> getTableDescription(ConnectionConfig config, String database, String table, String like, boolean extended) {
+ Optional<Result> resultOptional = getTableDescription(config, database, table, like);
+    List<ColumnDescription> descriptions = new ArrayList<>();
+    if(resultOptional.isPresent()) {
+      for (Row row : resultOptional.get().getRows()) {
+        Object[] values = row.getRow();
+        String name = (String) values[3];
+        String type = (String) values[5];
+        int position = (Integer) values[16];
+        descriptions.add(new ColumnDescriptionShort(name, type, position));
+      }
+    }
+    return descriptions;
+  }
+
+  @Override
+  public Cursor<Row, ColumnDescription> getDbListCursor(ConnectionConfig config, String like) {
+    Optional<Result> rowsFromDB = getRowsFromDB(config, getDatabaseListStatements(like));
+    if (rowsFromDB.isPresent()) {
+      Result result = rowsFromDB.get();
+      return new PersistentCursor<>(result.getRows(), result.getColumns());
+    } else {
+      return new PersistentCursor<>(Lists.<Row>newArrayList(), Lists.<ColumnDescription>newArrayList());
+    }
+  }
+
+  @Override
+  public Cursor<Row, ColumnDescription> getTableListCursor(ConnectionConfig config, String database, String like) {
+    Optional<Result> rowsFromDB = getRowsFromDB(config, getTableListStatements(database, like));
+    if (rowsFromDB.isPresent()) {
+      Result result = rowsFromDB.get();
+      return new PersistentCursor<>(result.getRows(), result.getColumns());
+    } else {
+      return new PersistentCursor<>(Lists.<Row>newArrayList(), Lists.<ColumnDescription>newArrayList());
+    }
+  }
+
+  @Override
+  public Cursor<Row, ColumnDescription> getTableDescriptionCursor(ConnectionConfig config, String database, String table, String like, boolean extended) {
+    Optional<Result> tableDescriptionOptional = getTableDescription(config, database, table, like);
+    if(tableDescriptionOptional.isPresent()) {
+      Result result = tableDescriptionOptional.get();
+      return new PersistentCursor<>(result.getRows(), result.getColumns());
+    } else {
+      return new PersistentCursor<>(Lists.<Row>newArrayList(), Lists.<ColumnDescription>newArrayList());
+    }
+  }
+
+  private String[] getDatabaseListStatements(String like) {
+    return new String[]{
+      String.format("show databases like '%s'", like)
+    };
+  }
+
+  private String[] getTableListStatements(String database, String like) {
+    return new String[]{
+      String.format("use %s", database),
+      String.format("show tables like '%s'", like)
+    };
+  }
+
+  private Optional<Result> getRowsFromDB(ConnectionConfig config, String[] statements) {
+    Connect connect = config.createConnectMessage();
+    HiveJob job = new SyncJob(config.getUsername(), statements, context);
+    ExecuteJob execute = new ExecuteJob(connect, job);
+
+    LOG.info("Executing query: {}, for user: {}", getJoinedStatements(statements), job.getUsername());
+
+    return getResultFromDB(execute);
+  }
+
+  private Optional<Result> getTableDescription(ConnectionConfig config, String databasePattern, String tablePattern, String columnPattern) {
+    Connect connect = config.createConnectMessage();
+    HiveJob job = new GetColumnMetadataJob(config.getUsername(), context, databasePattern, tablePattern, columnPattern);
+    ExecuteJob execute = new ExecuteJob(connect, job);
+
+    LOG.info("Executing query to fetch the column description for dbPattern: {}, tablePattern: {}, columnPattern: {}, for user: {}",
+      databasePattern, tablePattern, columnPattern, job.getUsername());
+    return getResultFromDB(execute);
+  }
+
+  private Optional<Result> getResultFromDB(ExecuteJob job) {
+    List<ColumnDescription> descriptions = null;
+    List<Row> rows = Lists.newArrayList();
+    Inbox inbox = Inbox.create(system);
+    inbox.send(controller, job);
+    Object submitResult;
+    try {
+      submitResult = inbox.receive(Duration.create(actorConfiguration.getSyncQueryTimeout(60 * 1000), TimeUnit.MILLISECONDS));
+    } catch (Throwable ex) {
+      String errorMessage = "Query timed out to fetch table description for user: " + job.getConnect().getUsername();
+      LOG.error(errorMessage, ex);
+      throw new ServiceFormattedException(errorMessage, ex);
+    }
+
+    if (submitResult instanceof NoResult) {
+      LOG.info("Query returned with no result.");
+      return Optional.absent();
+
+    }
+
+    if (submitResult instanceof ExecutionFailed) {
+      ExecutionFailed error = (ExecutionFailed) submitResult;
+      LOG.error("Failed to get the table description");
+      throw new ServiceFormattedException(error.getMessage(), error.getError());
+
+    } else if (submitResult instanceof ResultSetHolder) {
+      ResultSetHolder holder = (ResultSetHolder) submitResult;
+      ActorRef iterator = holder.getIterator();
+      while (true) {
+        inbox.send(iterator, new Next());
+        Object receive;
+        try {
+          receive = inbox.receive(Duration.create(actorConfiguration.getResultFetchTimeout(60 * 1000), TimeUnit.MILLISECONDS));
+        } catch (Throwable ex) {
+          String errorMessage = "Query timed out to fetch results for user: " + job.getConnect().getUsername();
+          LOG.error(errorMessage, ex);
+          throw new ServiceFormattedException(errorMessage, ex);
+        }
+
+        if (receive instanceof Result) {
+          Result result = (Result) receive;
+          if (descriptions == null) {
+            descriptions = result.getColumns();
+          }
+          rows.addAll(result.getRows());
+        }
+
+        if (receive instanceof NoMoreItems) {
+          break;
+        }
+
+        if (receive instanceof FetchFailed) {
+          FetchFailed error = (FetchFailed) receive;
+          LOG.error("Failed to fetch results ");
+          throw new ServiceFormattedException(error.getMessage(), error.getError());
+        }
+      }
+
+    }
+    return Optional.of(new Result(rows, descriptions));
+  }
+
+  private String getJoinedStatements(String[] statements) {
+    return Joiner.on("; ").skipNulls().join(statements);
+  }
+
+  private ImmutableList<String> getFirstColumnValues(List<Row> rows) {
+    return FluentIterable.from(rows)
+      .transform(new Function<Row, String>() {
+        @Override
+        public String apply(Row input) {
+          Object[] values = input.getRow();
+          return values.length > 0 ? (String) values[0] : NO_VALUE_MARKER;
+        }
+      }).toList();
+  }
+
+}

+ 110 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/EmptyCursor.java

@@ -0,0 +1,110 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import com.beust.jcommander.internal.Lists;
+import org.apache.commons.lang.NotImplementedException;
+
+import java.util.Iterator;
+import java.util.List;
+
+public class EmptyCursor implements Cursor<Row, ColumnDescription> {
+
+    private List<Row> rows = Lists.newArrayList();
+    private List<ColumnDescription> desc = Lists.newArrayList();
+
+
+    @Override
+    public boolean isResettable() {
+        return false;
+    }
+
+    @Override
+    public void reset() {
+
+    }
+
+    @Override
+    public int getOffset() {
+        return 0;
+    }
+
+    @Override
+    public List<ColumnDescription> getDescriptions() {
+        return desc;
+    }
+
+  @Override
+  public void keepAlive() {
+    // Do Nothing
+  }
+
+  /**
+     * Returns an iterator over a set of elements of type T.
+     *
+     * @return an Iterator.
+     */
+    @Override
+    public Iterator<Row> iterator() {
+        return rows.iterator();
+    }
+
+    /**
+     * Returns {@code true} if the iteration has more elements.
+     * (In other words, returns {@code true} if {@link #next} would
+     * return an element rather than throwing an exception.)
+     *
+     * @return {@code true} if the iteration has more elements
+     */
+    @Override
+    public boolean hasNext() {
+        return false;
+    }
+
+    /**
+     * Returns the next element in the iteration.
+     *
+     * @return the next element in the iteration
+     * @throws NotImplementedException  if the iteration has no more elements
+     */
+    @Override
+    public Row next() {
+        throw new NotImplementedException();
+    }
+
+    /**
+     * Removes from the underlying collection the last element returned
+     * by this iterator (optional operation).  This method can be called
+     * only once per call to {@link #next}.  The behavior of an iterator
+     * is unspecified if the underlying collection is modified while the
+     * iteration is in progress in any way other than by calling this
+     * method.
+     *
+     * @throws UnsupportedOperationException if the {@code remove}
+     *                                       operation is not supported by this iterator
+     * @throws IllegalStateException         if the {@code next} method has not
+     *                                       yet been called, or the {@code remove} method has already
+     *                                       been called after the last call to the {@code next}
+     *                                       method
+     */
+    @Override
+    public void remove() {
+        throw new NotImplementedException();
+    }
+}

+ 31 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveAuthCredentials.java

@@ -0,0 +1,31 @@
+/**
+ * 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.ambari.view.hive2.client;
+
+public class HiveAuthCredentials {
+  private String password;
+
+  public String getPassword() {
+    return password;
+  }
+
+  public void setPassword(String password) {
+    this.password = password;
+  }
+}

+ 27 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveAuthRequiredException.java

@@ -0,0 +1,27 @@
+/**
+ * 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.ambari.view.hive2.client;
+
+import org.apache.ambari.view.hive2.utils.ServiceFormattedException;
+
+public class HiveAuthRequiredException extends ServiceFormattedException {
+  public HiveAuthRequiredException() {
+    super("Hive Password Required", null, 401);
+  }
+}

+ 25 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveClientAuthRequiredException.java

@@ -0,0 +1,25 @@
+/**
+ * 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.ambari.view.hive2.client;
+
+public class HiveClientAuthRequiredException extends Exception {
+  public HiveClientAuthRequiredException(String comment, Exception ex) {
+    super(comment + ((ex == null)?"":(": " + ex.toString())), ex);
+  }
+}

+ 25 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveClientException.java

@@ -0,0 +1,25 @@
+/**
+ * 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.ambari.view.hive2.client;
+
+public class HiveClientException extends Exception {
+  public HiveClientException(String comment, Exception ex) {
+    super(comment + ((ex == null)?"":(": " + ex.toString())), ex);
+  }
+}

+ 25 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/HiveClientRuntimeException.java

@@ -0,0 +1,25 @@
+/**
+ * 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.ambari.view.hive2.client;
+
+public class HiveClientRuntimeException extends RuntimeException {
+  public HiveClientRuntimeException(String comment, Exception ex) {
+    super(comment + ((ex == null)?"":(": " + ex.toString())), ex);
+  }
+}

+ 153 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/NonPersistentCursor.java

@@ -0,0 +1,153 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Inbox;
+import com.google.common.collect.Lists;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.actor.message.lifecycle.KeepAlive;
+import org.apache.ambari.view.hive2.utils.HiveActorConfiguration;
+import org.apache.ambari.view.hive2.utils.ServiceFormattedException;
+import org.apache.ambari.view.hive2.actor.message.job.FetchFailed;
+import org.apache.ambari.view.hive2.actor.message.job.Next;
+import org.apache.ambari.view.hive2.actor.message.job.NoMoreItems;
+import org.apache.ambari.view.hive2.actor.message.job.Result;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Wrapper over iterator actor and blocks to fetch Rows and ColumnDescription whenever there is no more Rows to be
+ * returned.
+ */
+public class NonPersistentCursor implements Cursor<Row, ColumnDescription> {
+  private final Logger LOG = LoggerFactory.getLogger(getClass());
+  private static long DEFAULT_WAIT_TIMEOUT = 60 * 1000L;
+
+  private final ActorSystem system;
+  private final ActorRef actorRef;
+  private final ViewContext context;
+  private final HiveActorConfiguration actorConfiguration;
+  private final Queue<Row> rows = Lists.newLinkedList();
+  private final List<ColumnDescription> descriptions = Lists.newLinkedList();
+  private int offSet = 0;
+  private boolean endReached = false;
+
+
+  public NonPersistentCursor(ViewContext context, ActorSystem system, ActorRef actorRef) {
+    this.context = context;
+    this.system = system;
+    this.actorRef = actorRef;
+    actorConfiguration = new HiveActorConfiguration(context);
+  }
+
+  @Override
+  public boolean isResettable() {
+    return false;
+  }
+
+  @Override
+  public void reset() {
+    // Do nothing
+  }
+
+  @Override
+  public int getOffset() {
+    return offSet;
+  }
+
+  @Override
+  public List<ColumnDescription> getDescriptions() {
+    fetchIfNeeded();
+    return descriptions;
+  }
+
+  @Override
+  public void keepAlive() {
+    Inbox inbox = Inbox.create(system);
+    inbox.send(actorRef, new KeepAlive());
+  }
+
+  @Override
+  public Iterator<Row> iterator() {
+    return this;
+  }
+
+  @Override
+  public boolean hasNext() {
+    fetchIfNeeded();
+    return !endReached;
+  }
+
+  @Override
+  public Row next() {
+    fetchIfNeeded();
+    offSet++;
+    return rows.poll();
+  }
+
+  @Override
+  public void remove() {
+    throw new RuntimeException("Read only cursor. Method not supported");
+  }
+
+  private void fetchIfNeeded() {
+    if (endReached || rows.size() > 0) return;
+    getNextRows();
+  }
+
+  private void getNextRows() {
+    Inbox inbox = Inbox.create(system);
+    inbox.send(actorRef, new Next());
+    Object receive;
+    try {
+      receive = inbox.receive(Duration.create(actorConfiguration.getResultFetchTimeout(DEFAULT_WAIT_TIMEOUT),
+        TimeUnit.MILLISECONDS));
+    } catch (Throwable ex) {
+      String errorMessage = "Result fetch timed out";
+      LOG.error(errorMessage, ex);
+      throw new ServiceFormattedException(errorMessage, ex);
+    }
+
+    if (receive instanceof Result) {
+      Result result = (Result) receive;
+      if (descriptions.isEmpty()) {
+        descriptions.addAll(result.getColumns());
+      }
+      rows.addAll(result.getRows());
+    }
+
+    if (receive instanceof NoMoreItems) {
+      endReached = true;
+    }
+
+    if (receive instanceof FetchFailed) {
+      FetchFailed error = (FetchFailed) receive;
+      LOG.error("Failed to fetch results ");
+      throw new ServiceFormattedException(error.getMessage(), error.getError());
+    }
+  }
+}

+ 87 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/PersistentCursor.java

@@ -0,0 +1,87 @@
+/*
+ * 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.ambari.view.hive2.client;
+
+
+import com.google.common.collect.Lists;
+
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Wrapper over other iterables. Does not block and can be reset to start again from beginning.
+ */
+public class PersistentCursor<T, R> implements Cursor<T, R>  {
+  private List<T> rows = Lists.newArrayList();
+  private List<R> columns = Lists.newArrayList();
+  private int offset = 0;
+
+  public PersistentCursor(List<T> rows, List<R> columns) {
+    this.rows = rows;
+    this.columns = columns;
+  }
+
+
+  @Override
+  public Iterator<T> iterator() {
+    return this;
+  }
+
+  @Override
+  public boolean hasNext() {
+    return rows.size() > 0 && offset < rows.size();
+  }
+
+  @Override
+  public T next() {
+    T row = rows.get(offset);
+    offset++;
+    return row;
+  }
+
+  @Override
+  public void remove() {
+    throw new RuntimeException("Read only cursor. Method not supported");
+  }
+
+  @Override
+  public boolean isResettable() {
+    return true;
+  }
+
+  @Override
+  public void reset() {
+    this.offset = 0;
+  }
+
+  @Override
+  public int getOffset() {
+    return offset;
+  }
+
+  @Override
+  public List<R> getDescriptions() {
+    return columns;
+  }
+
+  @Override
+  public void keepAlive() {
+    // Do Nothing as we are pre-fetching everything.
+  }
+}

+ 74 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/client/Row.java

@@ -0,0 +1,74 @@
+/**
+ * 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.ambari.view.hive2.client;
+
+import java.util.Arrays;
+import java.util.HashSet;
+
+public class Row {
+  private Object[] row;
+
+  public Row(Object[] row) {
+    this(row, null);
+  }
+
+  public Row(Object[] row, HashSet<Integer> selectedColumns) {
+    if (selectedColumns == null || selectedColumns.size() == 0)
+      this.row = row.clone();
+    else {
+      this.row = new Object[selectedColumns.size()];
+      int rowIndex = 0;
+      for (Integer selectedIndex : selectedColumns) {
+        this.row[rowIndex] = row[selectedIndex];
+        rowIndex ++;
+      }
+    }
+  }
+
+  public Object[] getRow() {
+    return row;
+  }
+
+  public void setRow(Object[] row) {
+    this.row = row;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    Row row1 = (Row) o;
+
+    boolean retValue = Arrays.equals(row, row1.row);
+    return retValue;
+  }
+
+  @Override
+  public int hashCode() {
+    return Arrays.hashCode(row);
+  }
+
+  @Override
+  public String toString() {
+    return "Row{" +
+            "row=" + Arrays.toString(row) +
+            '}';
+  }
+}

+ 28 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/exceptions/NotConnectedException.java

@@ -0,0 +1,28 @@
+/*
+ * 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.ambari.view.hive2.exceptions;
+
+/**
+ * Exception thrown when the connection is not made and we try to execute some job
+ */
+public class NotConnectedException extends RuntimeException {
+  public NotConnectedException(String message) {
+    super(message);
+  }
+}

+ 23 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/AsyncExecutionFailure.java

@@ -0,0 +1,23 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+public class AsyncExecutionFailure {
+}
+

+ 25 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/AsyncExecutionSuccess.java

@@ -0,0 +1,25 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+public class AsyncExecutionSuccess {
+
+
+}
+

+ 59 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/Connectable.java

@@ -0,0 +1,59 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import com.google.common.base.Optional;
+import org.apache.hive.jdbc.HiveConnection;
+
+/**
+ * Life cycle management for java.sql.Connection
+ */
+public interface Connectable  {
+
+    /**
+     * Get the underlying connection
+     * @return an optional wrapping the connection
+     */
+    Optional<HiveConnection> getConnection();
+
+    /**
+     * Check if the connection is open
+     * @return
+     */
+    boolean isOpen();
+
+    /**
+     * Open a connection
+     * @throws ConnectionException
+     */
+    void connect() throws ConnectionException;
+
+    /**
+     * Reconnect if closed
+     * @throws ConnectionException
+     */
+    void reconnect() throws ConnectionException;
+
+    /**
+     * Close the connection
+     * @throws ConnectionException
+     */
+    void disconnect() throws ConnectionException;
+
+}

+ 25 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ConnectionException.java

@@ -0,0 +1,25 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+public class ConnectionException extends Exception {
+    public ConnectionException(Exception e, String message) {
+        super(message,e);
+    }
+}

+ 94 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ConnectionProperties.java

@@ -0,0 +1,94 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import com.google.common.collect.Maps;
+
+import java.util.Map;
+
+/**
+ * Holds all information needed to connect to HS2
+ */
+public class ConnectionProperties {
+
+    private String host;
+    private int port;
+    private String userName;
+    private String password;
+    private Map<String, String> authParams = Maps.newHashMap();
+
+    public Map<String, String> getAuthParams() {
+        return authParams;
+    }
+
+    public void addAuthParam(String key,String value){
+        authParams.put(key, value);
+    }
+
+    public String getHost() {
+        return host;
+    }
+
+    public void setHost(String host) {
+        this.host = host;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public int getPort() {
+        return port;
+    }
+
+    public void setPort(int port) {
+        this.port = port;
+    }
+
+    public String getUserName() {
+        return userName;
+    }
+
+    public void setUserName(String userName) {
+        this.userName = userName;
+    }
+
+    @Override
+    public String toString() {
+        return "HiveConnectionProps{" +
+                "authParams=" + authParams +
+                ", host='" + host + '\'' +
+                ", port=" + port +
+                ", userName='" + userName + '\'' +
+                ", password='" + password + '\'' +
+                '}';
+    }
+
+    public String asUrl() {
+        return null;
+    }
+
+    public String asUrlWithoutCredentials() {
+        return null;
+    }
+}

+ 37 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ConnectionSupplier.java

@@ -0,0 +1,37 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.ConnectionDelegate;
+import org.apache.ambari.view.hive2.HiveJdbcConnectionDelegate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ConnectionSupplier implements ContextSupplier<ConnectionDelegate> {
+
+  protected final Logger LOG =
+    LoggerFactory.getLogger(getClass());
+
+  @Override
+  public ConnectionDelegate get(ViewContext context) {
+    LOG.debug("Creating Connection delegate instance for Viewname: {}, Instance Name: {}", context.getViewName(), context.getInstanceName());
+    return new HiveJdbcConnectionDelegate();
+  }
+}

+ 37 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/ContextSupplier.java

@@ -0,0 +1,37 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import org.apache.ambari.view.ViewContext;
+
+/**
+ * A class that can supply objects of same type.
+ * @param <T>
+ */
+public interface ContextSupplier<T> {
+  /**
+   * Retrieves an instance of appropriate type. The returned object could be a new instance
+   * or an exiting instance. No guarantee on that.
+   * @param context View Context to be used to create the instance
+   * @return instance of appropriateType
+   */
+  T get(ViewContext context);
+
+
+}

+ 42 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/DataStorageSupplier.java

@@ -0,0 +1,42 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.persistence.DataStoreStorage;
+import org.apache.ambari.view.hive2.persistence.Storage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A supplier for data storage
+ * Duplicated to keep the API uniform
+ */
+public class DataStorageSupplier implements ContextSupplier<Storage> {
+
+  protected final Logger LOG =
+    LoggerFactory.getLogger(getClass());
+
+  @Override
+  public Storage get(ViewContext context) {
+    LOG.debug("Creating storage instance for Viewname: {}, Instance Name: {}", context.getViewName(), context.getInstanceName());
+    return new DataStoreStorage(context);
+  }
+}

+ 62 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/DefaultSupplier.java

@@ -0,0 +1,62 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import com.google.common.base.Supplier;
+
+import java.util.List;
+
+/**
+ * Create instances of classes
+ * for which no constructors have been specified
+ * @param <T>
+ */
+public class DefaultSupplier<T> implements Supplier<T>{
+
+    private Class<T> clazz;
+    T instance;
+
+    public DefaultSupplier(T instance) {
+        this.instance = instance;
+    }
+
+    public DefaultSupplier(Class<T> clazz) throws IllegalAccessException, InstantiationException {
+        this.clazz = clazz;
+    }
+
+    /**
+     * Get the instance
+     * @return
+     */
+    @Override
+    public T get() {
+        if(clazz != null){
+            try {
+                return clazz.newInstance();
+            } catch (InstantiationException e) {
+                e.printStackTrace();
+                return null;
+            } catch (IllegalAccessException e) {
+                return null;
+            }
+        } else {
+            return instance;
+        }
+    }
+}

+ 78 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/Either.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.ambari.view.hive2.internal;
+
+import com.google.common.base.Optional;
+
+/**
+ * Simple implementation of a container class which can
+ * hold one of two values
+ *
+ * Callers should check if the value if left or right before
+ * trying to get the value
+ *
+ * @param <L> Left Value
+ * @param <R> Right value
+ */
+public class Either<L,R> {
+
+    private final Optional<L> left;
+    private final Optional<R> right;
+
+
+    public boolean isLeft(){
+       return left.isPresent() && !right.isPresent();
+    }
+
+    public boolean isRight(){
+        return !left.isPresent() && right.isPresent();
+    }
+
+    public L getLeft(){
+        return left.orNull();
+    }
+
+    public R getRight(){
+        return right.orNull();
+    }
+
+
+    private Either(Optional<L> left, Optional<R> right) {
+        this.left = left;
+        this.right = right;
+    }
+
+
+
+    public static <L,R> Either<L,R> left(L value) {
+        return new Either<>(Optional.of(value), Optional.<R>absent());
+    }
+
+    public static <L,R> Either<L,R> right(R value) {
+        return new Either<>(Optional.<L>absent(), Optional.of(value));
+    }
+
+    public static <L,R> Either<L,R> none() {
+        return new Either<>(Optional.<L>absent(), Optional.<R>absent());
+    }
+
+}
+
+
+

+ 59 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HdfsApiSupplier.java

@@ -0,0 +1,59 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import com.google.common.base.Optional;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.utils.hdfs.HdfsApi;
+import org.apache.ambari.view.utils.hdfs.HdfsApiException;
+import org.apache.ambari.view.utils.hdfs.HdfsUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class HdfsApiSupplier implements ContextSupplier<Optional<HdfsApi>> {
+
+  protected final Logger LOG =
+    LoggerFactory.getLogger(getClass());
+
+  private static final Map<String, HdfsApi> hdfsApiMap = new ConcurrentHashMap<>();
+  private final Object lock = new Object();
+
+  @Override
+  public Optional<HdfsApi> get(ViewContext context) {
+    try {
+      if(!hdfsApiMap.containsKey(context.getInstanceName())) {
+        synchronized (lock) {
+          if(!hdfsApiMap.containsKey(context.getInstanceName())) {
+            LOG.debug("Creating HDFSApi instance for Viewname: {}, Instance Name: {}", context.getViewName(), context.getInstanceName());
+            HdfsApi api = HdfsUtil.connectToHDFSApi(context);
+            hdfsApiMap.put(context.getInstanceName(), api);
+            return Optional.of(api);
+          }
+        }
+      }
+      return Optional.of(hdfsApiMap.get(context.getInstanceName()));
+    } catch (HdfsApiException e) {
+      LOG.error("Cannot get the HDFS API", e);
+      return Optional.absent();
+    }
+  }
+}

+ 109 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveConnectionWrapper.java

@@ -0,0 +1,109 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Supplier;
+import org.apache.hive.jdbc.HiveConnection;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+/**
+ * Composition over a Hive jdbc connection
+ * This class only provides a connection over which
+ * callers should run their own JDBC statements
+ */
+public class HiveConnectionWrapper implements Connectable,Supplier<HiveConnection> {
+
+  private static String DRIVER_NAME = "org.apache.hive.jdbc.HiveDriver";
+  private final String jdbcUrl;
+  private final String username;
+  private final String password;
+
+  private HiveConnection connection = null;
+
+  public HiveConnectionWrapper(String jdbcUrl, String username, String password) {
+    this.jdbcUrl = jdbcUrl;
+    this.username = username;
+    this.password = password;
+  }
+
+
+  @Override
+  public void connect() throws ConnectionException {
+    try {
+      Class.forName(DRIVER_NAME);
+    } catch (ClassNotFoundException e) {
+      throw new ConnectionException(e, "Cannot load the hive JDBC driver");
+    }
+
+    try {
+      Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
+      connection = (HiveConnection)conn;
+
+    } catch (SQLException e) {
+      throw new ConnectionException(e, "Cannot open a hive connection with connect string " + jdbcUrl);
+    }
+
+
+  }
+
+  @Override
+  public void reconnect() throws ConnectionException {
+
+  }
+
+  @Override
+  public void disconnect() throws ConnectionException {
+    if (connection != null) {
+      try {
+        connection.close();
+      } catch (SQLException e) {
+        throw new ConnectionException(e, "Cannot close the hive connection with connect string " + jdbcUrl);
+      }
+    }
+  }
+
+  public Optional<HiveConnection> getConnection() {
+    return Optional.fromNullable(connection);
+  }
+
+  @Override
+  public boolean isOpen() {
+    try {
+      return connection != null && !connection.isClosed() && connection.isValid(100);
+    } catch (SQLException e) {
+      // in case of an SQ error just return
+      return false;
+    }
+  }
+
+  /**
+   * Retrieves an instance of the appropriate type. The returned object may or
+   * may not be a new instance, depending on the implementation.
+   *
+   * @return an instance of the appropriate type
+   */
+  @Override
+  public HiveConnection get() {
+    return null;
+  }
+}

+ 71 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveQuery.java

@@ -0,0 +1,71 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+
+import com.google.common.base.Function;
+import com.google.common.collect.FluentIterable;
+
+import javax.annotation.Nullable;
+import java.util.Arrays;
+import java.util.Collection;
+
+/**
+ * Holder for query submitted by the user
+ * This may contain multiple hive queries
+ */
+public class HiveQuery {
+
+    private String query;
+
+    public HiveQuery(String query) {
+        this.query = query;
+    }
+
+    public HiveQueries fromMultiLineQuery(String multiLineQuery){
+        return new HiveQueries(multiLineQuery);
+    }
+
+
+    public static class HiveQueries{
+
+        static final String QUERY_SEP = ";";
+        Collection<HiveQuery> hiveQueries;
+
+        private HiveQueries(String userQuery) {
+            hiveQueries = FluentIterable.from(Arrays.asList(userQuery.split(QUERY_SEP)))
+                    .transform(new Function<String, HiveQuery>() {
+                        @Nullable
+                        @Override
+                        public HiveQuery apply(@Nullable String input) {
+                            return new HiveQuery(input.trim());
+                        }
+                    }).toList();
+        }
+
+
+
+
+
+    }
+
+
+
+
+};

+ 160 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveResult.java

@@ -0,0 +1,160 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+import com.google.common.collect.Lists;
+
+import java.math.RoundingMode;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+public class HiveResult implements Iterator<HiveResult.Row> {
+
+    public static final String NULL = "NULL";
+    private static final int DEFAULT_BATCH_SIZE = 50;
+    private static ResultSetMetaData metaData;
+    private Row colNames;
+    private NumberFormat nf = new DecimalFormat();
+    private List<Row> rows = Lists.newArrayList();
+
+    public HiveResult(ResultSet rs) throws SQLException {
+        nf.setRoundingMode(RoundingMode.FLOOR);
+        nf.setMinimumFractionDigits(0);
+        nf.setMaximumFractionDigits(2);
+        metaData = rs.getMetaData();
+        int columnCount = metaData.getColumnCount();
+        colNames = new Row(columnCount);
+        int index = 0;
+        while (rs.next() && index <DEFAULT_BATCH_SIZE){
+            index ++;
+            rows.add(new Row(columnCount,rs));
+        }
+
+
+    }
+
+    public List<Row> getRows(){
+        return rows;
+    }
+
+    public List<Row> getData() {
+        return rows;
+    }
+
+    /**
+     * use the lists iterator
+     *
+     * @return {@code true} if the iteration has more elements
+     */
+    @Override
+    public boolean hasNext() {
+        return rows.iterator().hasNext();
+    }
+
+    /**
+     * Returns the next row in the iteration.
+     *
+     * @return the next element in the iteration
+     */
+    @Override
+    public Row next() {
+        return rows.iterator().next();
+    }
+
+    /**
+     * Removes from the underlying collection the last element returned
+     * by this iterator (optional operation).  This method can be called
+     * only once per call to {@link #next}.  The behavior of an iterator
+     * is unspecified if the underlying collection is modified while the
+     * iteration is in progress in any way other than by calling this
+     * method.
+     *
+     * @throws UnsupportedOperationException if the {@code remove}
+     *                                       operation is not supported by this iterator
+     * @throws IllegalStateException         if the {@code next} method has not
+     *                                       yet been called, or the {@code remove} method has already
+     *                                       been called after the last call to the {@code next}
+     *                                       method
+     */
+    @Override
+    public void remove() {
+        throw new UnsupportedOperationException();
+    }
+
+    public Row getColNames() {
+        return colNames;
+    }
+
+
+    @Override
+    public String toString() {
+        return "HiveResult{" +
+                "colNames=" + colNames +
+                ", rows=" + rows +
+                '}';
+    }
+
+    public class Row {
+        String[] values;
+
+        public Row(int size) throws SQLException {
+            values = new String[size];
+            for (int i = 0; i < size; i++) {
+                values[i] = metaData.getColumnLabel(i + 1);
+            }
+        }
+
+
+        public Row(int size, ResultSet rs) throws SQLException {
+            values = new String[size];
+            for (int i = 0; i < size; i++) {
+                if (nf != null) {
+                    Object object = rs.getObject(i + 1);
+                    if (object == null) {
+                        values[i] = null;
+                    } else if (object instanceof Number) {
+                        values[i] = nf.format(object);
+                    } else {
+                        values[i] = object.toString();
+                    }
+                } else {
+                    values[i] = rs.getString(i + 1);
+                }
+                values[i] = values[i] == null ? NULL : values[i];
+
+            }
+
+        }
+
+        @Override
+        public String toString() {
+            return "Row{" +
+                    "values=" + Arrays.toString(values) +
+                    '}';
+        }
+    }
+
+
+}

+ 53 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveTask.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.ambari.view.hive2.internal;
+
+public interface HiveTask {
+
+    /**
+     * The task id for this task
+     * @return task Id
+     */
+    Long getId();
+
+    /**
+     * The user for which this task was submitted
+     * @return
+     */
+    String getUser();
+
+    /**
+     * The view instance tied to this task
+     * @return
+     */
+    String getInstance();
+
+    /**
+     * Connection properties pulled from the view context and request
+     * @return
+     */
+
+    //Connectable getConnectionClass();
+
+    ConnectionProperties getConnectionProperties();
+
+    HiveQuery.HiveQueries getQueries();
+
+
+}

+ 118 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/internal/HiveTaskMessage.java

@@ -0,0 +1,118 @@
+/*
+ * 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.ambari.view.hive2.internal;
+
+public class HiveTaskMessage implements HiveTask {
+
+    private Long id;
+    private String instance;
+    private ConnectionProperties connectionProps;
+    private HiveQuery.HiveQueries queries;
+    //private Connectable connectable = new HiveConnectionWrapper(connectMessage);
+
+
+    public void setConnectionProps(ConnectionProperties connectionProps) {
+        this.connectionProps = connectionProps;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public void setInstance(String instance) {
+        this.instance = instance;
+    }
+
+    public void setQueries(HiveQuery.HiveQueries queries) {
+        this.queries = queries;
+    }
+
+
+    /*public void setConnectable(Connectable connectable) {
+        this.connectable = connectable;
+    }*/
+
+    /**
+     * The task id for this task
+     *
+     * @return task Id
+     */
+    @Override
+    public Long getId() {
+        return id;
+    }
+
+    /**
+     * The user for which this task was submitted
+     *
+     * @return
+     */
+    @Override
+    public String getUser() {
+        return connectionProps.getUserName();
+    }
+
+    /**
+     * The view instance tied to this task
+     *
+     * @return
+     */
+    @Override
+    public String getInstance() {
+        return instance;
+    }
+
+    /**
+     * Connection properties pulled from the view context and request
+     *
+     * @return
+     */
+    /*@Override
+    public Connectable getConnectionClass() {
+        return connectable;
+    }
+*/
+    /**
+     * Connection properties pulled from the view context and request
+     *
+     * @return
+     */
+    @Override
+    public ConnectionProperties getConnectionProperties() {
+        return connectionProps;
+    }
+
+    @Override
+    public HiveQuery.HiveQueries getQueries() {
+        return queries;
+    }
+
+
+    @Override
+    public String toString() {
+        return "HiveTaskMessage{" +
+                "connectionProps=" + connectionProps +
+                ", id=" + id +
+                ", instance='" + instance + '\'' +
+                ", queries=" + queries +
+                '}';
+    }
+
+
+}

+ 172 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/DataStoreStorage.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.ambari.view.hive2.persistence;
+
+import org.apache.ambari.view.PersistenceException;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.persistence.utils.FilteringStrategy;
+import org.apache.ambari.view.hive2.persistence.utils.Indexed;
+import org.apache.ambari.view.hive2.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive2.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.ambari.view.hive2.utils.ServiceFormattedException;
+import org.apache.commons.beanutils.BeanUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.beans.Transient;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Engine for storing objects to context DataStore storage
+ */
+public class DataStoreStorage implements Storage {
+  private final static Logger LOG =
+      LoggerFactory.getLogger(DataStoreStorage.class);
+
+  protected ViewContext context;
+
+  /**
+   * Constructor
+   * @param context View Context instance
+   */
+  public DataStoreStorage(ViewContext context) {
+    this.context = context;
+  }
+
+  @Override
+  public synchronized void store(Class model, Indexed obj) {
+    assignId(model, obj);
+
+    Indexed newBean;
+    try {
+      newBean = (Indexed) BeanUtils.cloneBean(obj);
+    } catch (IllegalAccessException e) {
+      throw new ServiceFormattedException("S010 Data storage error", e);
+    } catch (InstantiationException e) {
+      throw new ServiceFormattedException("S010 Data storage error", e);
+    } catch (InvocationTargetException e) {
+      throw new ServiceFormattedException("S010 Data storage error", e);
+    } catch (NoSuchMethodException e) {
+      throw new ServiceFormattedException("S010 Data storage error", e);
+    }
+    preprocessEntity(newBean);
+
+    try {
+      context.getDataStore().store(newBean);
+    } catch (PersistenceException e) {
+      throw new ServiceFormattedException("S020 Data storage error", e);
+    }
+  }
+
+  public void assignId(Class model, Indexed obj) {
+    if (obj.getId() == null) {
+      String id = nextIdForEntity(context, model);
+      obj.setId(id);
+    }
+  }
+
+  private void preprocessEntity(Indexed obj) {
+    cleanTransientFields(obj);
+  }
+
+  private void cleanTransientFields(Indexed obj) {
+    for (Method m : obj.getClass().getMethods()) {
+      Transient aTransient = m.getAnnotation(Transient.class);
+      if (aTransient != null && m.getName().startsWith("set")) {
+        try {
+          m.invoke(obj, new Object[]{ null });
+        } catch (IllegalAccessException e) {
+          throw new ServiceFormattedException("S030 Data storage error", e);
+        } catch (InvocationTargetException e) {
+          throw new ServiceFormattedException("S030 Data storage error", e);
+        }
+      }
+    }
+  }
+
+  private static synchronized String nextIdForEntity(ViewContext context, Class aClass) {
+    // auto increment id implementation
+    String lastId = context.getInstanceData(aClass.getName());
+    int newId;
+    if (lastId == null) {
+      newId = 1;
+    } else {
+      newId = Integer.parseInt(lastId) + 1;
+    }
+    context.putInstanceData(aClass.getName(), String.valueOf(newId));
+    return String.valueOf(newId);
+  }
+
+  @Override
+  public synchronized <T extends Indexed> T load(Class<T> model, Object id) throws ItemNotFound {
+    LOG.debug(String.format("Loading %s #%s", model.getName(), id));
+    try {
+      T obj = context.getDataStore().find(model, id);
+      if (obj != null) {
+        return obj;
+      } else {
+        throw new ItemNotFound();
+      }
+    } catch (PersistenceException e) {
+      throw new ServiceFormattedException("S040 Data storage error", e);
+    }
+  }
+
+  @Override
+  public synchronized <T extends Indexed> List<T> loadAll(Class<? extends T> model, FilteringStrategy filter) {
+    LinkedList<T> list = new LinkedList<T>();
+    LOG.debug(String.format("Loading all %s-s", model.getName()));
+    try {
+      for(T item: context.getDataStore().findAll(model, filter.whereStatement())) {
+        list.add(item);
+      }
+    } catch (PersistenceException e) {
+      throw new ServiceFormattedException("S050 Data storage error", e);
+    }
+    return list;
+  }
+
+  @Override
+  public synchronized <T extends Indexed> List<T> loadAll(Class<T> model) {
+    return loadAll(model, new OnlyOwnersFilteringStrategy(this.context.getUsername()));
+  }
+
+  @Override
+  public synchronized void delete(Class model, Object id) throws ItemNotFound {
+    LOG.debug(String.format("Deleting %s:%s", model.getName(), id));
+    Object obj = load(model, id);
+    try {
+      context.getDataStore().remove(obj);
+    } catch (PersistenceException e) {
+      throw new ServiceFormattedException("S060 Data storage error", e);
+    }
+  }
+
+  @Override
+  public boolean exists(Class model, Object id) {
+    try {
+      return context.getDataStore().find(model, id) != null;
+    } catch (PersistenceException e) {
+      throw new ServiceFormattedException("S070 Data storage error", e);
+    }
+  }
+}

+ 23 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/IStorageFactory.java

@@ -0,0 +1,23 @@
+/**
+ * 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.ambari.view.hive2.persistence;
+
+public interface IStorageFactory {
+  Storage getStorage();
+}

+ 132 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/InstanceKeyValueStorage.java

@@ -0,0 +1,132 @@
+/**
+ * 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.ambari.view.hive2.persistence;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.persistence.utils.ContextConfigurationAdapter;
+import org.apache.ambari.view.hive2.utils.ServiceFormattedException;
+import org.apache.commons.configuration.Configuration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.WebApplicationException;
+
+
+/**
+ * Persistent storage engine for storing java beans to
+ * instance data
+ */
+@Deprecated
+public class InstanceKeyValueStorage extends KeyValueStorage {
+  private final static Logger LOG =
+      LoggerFactory.getLogger(InstanceKeyValueStorage.class);
+
+  private ContextConfigurationAdapter config = null;
+  private int VALUE_LENGTH_LIMIT = 254;
+
+  /**
+   * Constructor.
+   * @param context View Context instance
+   */
+  public InstanceKeyValueStorage(ViewContext context) {
+    super(context);
+  }
+
+  /**
+   * Returns config instance, adapter to Persistence API
+   * @return config instance
+   */
+  @Override
+  protected synchronized Configuration getConfig() {
+    if (config == null) {
+      config = new ContextConfigurationAdapter(context);
+    }
+    return config;
+  }
+
+  /**
+   * Value is limited to 256 symbols, this code splits value into chunks and saves them as <key>#<chunk_id>
+   * @param modelPropName key
+   * @param json value
+   */
+  protected void write(String modelPropName, String json) {
+    int saved = 0;
+    int page = 1;
+    while (saved < json.length()) {
+      int end = Math.min(saved + VALUE_LENGTH_LIMIT, json.length());
+      String substring = json.substring(saved, end);
+      getConfig().setProperty(modelPropName + "#" + page, substring);
+      saved += VALUE_LENGTH_LIMIT;
+      page += 1;
+      LOG.debug("Chunk saved: " + modelPropName + "#" + page + "=" + substring);
+    }
+    getConfig().setProperty(modelPropName, page - 1);
+    LOG.debug("Write finished: " + modelPropName + " pages:" + (page - 1));
+  }
+
+  /**
+   * Read chunked value (keys format <key>#<chunk_id>)
+   * @param modelPropName key
+   * @return value
+   */
+  protected String read(String modelPropName) {
+    StringBuilder result = new StringBuilder();
+    int pages = getConfig().getInt(modelPropName);
+    LOG.debug("Read started: " + modelPropName + " pages:" + pages);
+
+    for(int page = 1; page <= pages; page++) {
+      String substring = getConfig().getString(modelPropName + "#" + page);
+      LOG.debug("Chunk read: " + modelPropName + "#" + page + "=" + substring);
+      if (substring != null) {
+        result.append(substring);
+      }
+    }
+
+    return result.toString();
+  }
+
+  /**
+   * Remove chunked value (keys format <key>#<chunk_id>)
+   * @param modelPropName key
+   */
+  protected void clear(String modelPropName) {
+    int pages = getConfig().getInt(modelPropName);
+    LOG.debug("Clean started: " + modelPropName + " pages:" + pages);
+
+    for(int page = 1; page <= pages; page++) {
+      getConfig().clearProperty(modelPropName + "#" + page);
+      LOG.debug("Chunk clean: " + modelPropName + "#" + page);
+    }
+    getConfig().clearProperty(modelPropName);
+  }
+
+  public static void storageSmokeTest(ViewContext context) {
+    try {
+      final String property = "test.smoke.property";
+      context.putInstanceData(property, "42");
+      boolean status = context.getInstanceData(property).equals("42");
+      context.removeInstanceData(property);
+      if (!status) throw new ServiceFormattedException("Ambari Views instance data DB doesn't work properly", null);
+    } catch (WebApplicationException ex) {
+      throw ex;
+    } catch (Exception ex) {
+      throw new ServiceFormattedException(ex.getMessage(), ex);
+    }
+  }
+}

+ 163 - 0
contrib/views/hive-next/src/main/java/org/apache/ambari/view/hive2/persistence/KeyValueStorage.java

@@ -0,0 +1,163 @@
+/**
+ * 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.ambari.view.hive2.persistence;
+
+import com.google.gson.Gson;
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive2.persistence.utils.FilteringStrategy;
+import org.apache.ambari.view.hive2.persistence.utils.Indexed;
+import org.apache.ambari.view.hive2.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive2.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.commons.configuration.Configuration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Engine for storing objects to key-value storage
+ */
+public abstract class KeyValueStorage implements Storage {
+  private final static Logger LOG =
+      LoggerFactory.getLogger(KeyValueStorage.class);
+  protected final Gson gson = new Gson();
+  protected ViewContext context;
+
+  /**
+   * Constructor
+   * @param context View Context instance
+   */
+  public KeyValueStorage(ViewContext context) {
+    this.context = context;
+  }
+
+  /**
+   * Returns config instance, adapter to Persistence API
+   * @return config instance
+   */
+  protected abstract Configuration getConfig();
+
+  @Override
+  public <T extends Indexed> void store(Class<T> model, Indexed obj) {
+    String modelIndexingPropName = getIndexPropertyName(model);
+
+    if (obj.getId() == null) {
+      int lastIndex = getConfig().getInt(modelIndexingPropName, 0);
+      lastIndex ++;
+      getConfig().setProperty(modelIndexingPropName, lastIndex);
+      obj.setId(String.valueOf(lastIndex));
+    }
+
+    String modelPropName = getItemPropertyName(model, obj.getId());
+    String json = serialize(obj);
+    write(modelPropName, json);
+  }
+
+  @Override
+  public <T extends Indexed> T load(Class<T> model, Object id) throws ItemNotFound {
+    String modelPropName = getItemPropertyName(model, id);
+    LOG.debug(String.format("Loading %s", modelPropName));
+    if (getConfig().containsKey(modelPropName)) {
+      String json = read(modelPropName);
+      LOG.debug(String.format("json: %s", json));
+
+      return deserialize(model, json);
+    } else {
+      throw new ItemNotFound();
+    }
+  }
+
+  /**
+   * Write json to storage
+   * @param modelPropName key
+   * @param json value
+   */
+  protected void write(String modelPropName, String json) {
+    getConfig().setProperty(modelPropName, json);
+  }
+
+  /**
+   * Read json from storage
+   * @param modelPropName key
+   * @return value
+   */
+  protected String read(String modelPropName) {
+    return getConfig().getString(modelPropName);
+  }
+
+  /**
+   * Remove line from storage
+   * @param modelPropName key
+   */
+  protected void clear(String modelPropName) {
+    getConfig().clearProperty(modelPropName);
+  }
+
+  protected String serialize(Indexed obj) {
+    return gson.toJson(obj);
+  }
+
+  protected <T extends Indexed> T deserialize(Class<T> model, String json) {
+    return gson.fromJson(json, model);
+  }
+
+  @Override
+  public synchronized <T extends Indexed> List<T> loadAll(Class<? extends T> model, FilteringStrategy filter) {
+    ArrayList<T> list = new ArrayList<T>();
+    String modelIndexingPropName = getIndexPropertyName(model);
+    LOG.debug(String.format("Loading all %s-s", model.getName()));
+    int lastIndex = getConfig().getInt(modelIndexingPropName, 0);
+    for(int i=1; i<=lastIndex; i++) {
+      try {
+        T item = load(model, i);
+        if ((filter == null) || filter.isConform(item)) {
+          list.add(item);
+        }
+      } catch (ItemNotFound ignored) {
+      }
+    }
+    return list;
+  }
+
+  @Override
+  public synchronized <T extends Indexed> List<T> loadAll(Class<T> model) {
+    return loadAll(model, new OnlyOwnersFilteringStrategy(this.context.getUsername()));
+  }
+
+  @Override
+  public synchronized void delete(Class model, Object id) {
+    LOG.debug(String.format("Deleting %s:%s", model.getName(), id));
+    String modelPropName = getItemPropertyName(model, id);
+    clear(modelPropName);
+  }
+
+  @Override
+  public boolean exists(Class model, Object id) {
+    return getConfig().containsKey(getItemPropertyName(model, id));
+  }
+
+  private String getIndexPropertyName(Class model) {
+    return String.format("%s:index", model.getName());
+  }
+
+  private String getItemPropertyName(Class model, Object id) {
+    return String.format("%s.%s", model.getName(), id);
+  }
+}

Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff