You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by ha...@apache.org on 2013/07/09 05:41:38 UTC

svn commit: r1501053 [1/2] - in /hive/trunk: contrib/src/test/results/clientnegative/ hcatalog/src/test/e2e/templeton/tests/ hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/ hcatalog/webhcat/svr/src/test/java/org/apache/hcatalog/temple...

Author: hashutosh
Date: Tue Jul  9 03:41:36 2013
New Revision: 1501053

URL: http://svn.apache.org/r1501053
Log:
HIVE-4580 : Change DDLTask to report errors using canonical error messages rather than http status codes (Eugene Koifman via Ashutosh Chauhan)

Added:
    hive/trunk/hcatalog/webhcat/svr/src/test/java/org/apache/hcatalog/templeton/TestWebHCatE2e.java
Modified:
    hive/trunk/contrib/src/test/results/clientnegative/serde_regex.q.out
    hive/trunk/contrib/src/test/results/clientnegative/url_hook.q.out
    hive/trunk/hcatalog/src/test/e2e/templeton/tests/ddl.conf
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/AppConfig.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BadParam.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BusyException.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CallbackFailedException.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CatchallExceptionMapper.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatDelegator.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatException.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/JsonBuilder.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/Main.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/NotAuthorizedException.java
    hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/QueueException.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/Driver.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/ErrorMsg.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Task.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskResult.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskRunner.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/HiveException.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/InvalidTableException.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/JsonMetaDataFormatter.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/MetaDataFormatUtils.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/MetaDataFormatter.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/formatting/TextMetaDataFormatter.java
    hive/trunk/ql/src/test/org/apache/hadoop/hive/ql/QTestUtil.java
    hive/trunk/ql/src/test/results/clientnegative/add_partition_with_whitelist.q.out
    hive/trunk/ql/src/test/results/clientnegative/addpart1.q.out
    hive/trunk/ql/src/test/results/clientnegative/alter_partition_nodrop_table.q.out
    hive/trunk/ql/src/test/results/clientnegative/alter_partition_with_whitelist.q.out
    hive/trunk/ql/src/test/results/clientnegative/alter_rename_partition_failure.q.out
    hive/trunk/ql/src/test/results/clientnegative/alter_rename_partition_failure2.q.out
    hive/trunk/ql/src/test/results/clientnegative/alter_rename_partition_failure3.q.out
    hive/trunk/ql/src/test/results/clientnegative/alter_table_wrong_regex.q.out
    hive/trunk/ql/src/test/results/clientnegative/alter_view_failure4.q.out
    hive/trunk/ql/src/test/results/clientnegative/altern1.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive1.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive2.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive_multi1.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive_multi2.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive_multi3.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive_multi4.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive_multi5.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive_multi6.q.out
    hive/trunk/ql/src/test/results/clientnegative/archive_multi7.q.out
    hive/trunk/ql/src/test/results/clientnegative/authorization_fail_1.q.out
    hive/trunk/ql/src/test/results/clientnegative/column_rename1.q.out
    hive/trunk/ql/src/test/results/clientnegative/column_rename2.q.out
    hive/trunk/ql/src/test/results/clientnegative/column_rename4.q.out
    hive/trunk/ql/src/test/results/clientnegative/create_table_failure3.q.out
    hive/trunk/ql/src/test/results/clientnegative/create_table_failure4.q.out
    hive/trunk/ql/src/test/results/clientnegative/create_table_wrong_regex.q.out
    hive/trunk/ql/src/test/results/clientnegative/create_view_failure1.q.out
    hive/trunk/ql/src/test/results/clientnegative/create_view_failure2.q.out
    hive/trunk/ql/src/test/results/clientnegative/create_view_failure4.q.out
    hive/trunk/ql/src/test/results/clientnegative/database_create_already_exists.q.out
    hive/trunk/ql/src/test/results/clientnegative/database_create_invalid_name.q.out
    hive/trunk/ql/src/test/results/clientnegative/database_drop_does_not_exist.q.out
    hive/trunk/ql/src/test/results/clientnegative/database_drop_not_empty.q.out
    hive/trunk/ql/src/test/results/clientnegative/database_drop_not_empty_restrict.q.out
    hive/trunk/ql/src/test/results/clientnegative/database_switch_does_not_exist.q.out
    hive/trunk/ql/src/test/results/clientnegative/deletejar.q.out
    hive/trunk/ql/src/test/results/clientnegative/describe_xpath1.q.out
    hive/trunk/ql/src/test/results/clientnegative/describe_xpath2.q.out
    hive/trunk/ql/src/test/results/clientnegative/describe_xpath3.q.out
    hive/trunk/ql/src/test/results/clientnegative/describe_xpath4.q.out
    hive/trunk/ql/src/test/results/clientnegative/disallow_incompatible_type_change_on1.q.out
    hive/trunk/ql/src/test/results/clientnegative/disallow_incompatible_type_change_on2.q.out
    hive/trunk/ql/src/test/results/clientnegative/drop_table_failure2.q.out
    hive/trunk/ql/src/test/results/clientnegative/drop_table_failure3.q.out
    hive/trunk/ql/src/test/results/clientnegative/drop_view_failure1.q.out
    hive/trunk/ql/src/test/results/clientnegative/external1.q.out
    hive/trunk/ql/src/test/results/clientnegative/external2.q.out
    hive/trunk/ql/src/test/results/clientnegative/invalid_columns.q.out
    hive/trunk/ql/src/test/results/clientnegative/lockneg2.q.out
    hive/trunk/ql/src/test/results/clientnegative/lockneg3.q.out
    hive/trunk/ql/src/test/results/clientnegative/lockneg4.q.out
    hive/trunk/ql/src/test/results/clientnegative/lockneg5.q.out
    hive/trunk/ql/src/test/results/clientnegative/protectmode_tbl6.q.out
    hive/trunk/ql/src/test/results/clientnegative/protectmode_tbl_no_drop.q.out
    hive/trunk/ql/src/test/results/clientnegative/serde_regex.q.out
    hive/trunk/ql/src/test/results/clientnegative/serde_regex3.q.out
    hive/trunk/ql/src/test/results/clientnegative/touch1.q.out
    hive/trunk/ql/src/test/results/clientnegative/touch2.q.out

Modified: hive/trunk/contrib/src/test/results/clientnegative/serde_regex.q.out
URL: http://svn.apache.org/viewvc/hive/trunk/contrib/src/test/results/clientnegative/serde_regex.q.out?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/contrib/src/test/results/clientnegative/serde_regex.q.out (original)
+++ hive/trunk/contrib/src/test/results/clientnegative/serde_regex.q.out Tue Jul  9 03:41:36 2013
@@ -80,5 +80,4 @@ WITH SERDEPROPERTIES (
 )
 STORED AS TEXTFILE
 PREHOOK: type: CREATETABLE
-#### A masked pattern was here ####
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. java.lang.RuntimeException: MetaException(message:org.apache.hadoop.hive.serde2.SerDeException org.apache.hadoop.hive.contrib.serde2.RegexSerDe only accepts string columns, but column[5] named status has type int)

Modified: hive/trunk/contrib/src/test/results/clientnegative/url_hook.q.out
URL: http://svn.apache.org/viewvc/hive/trunk/contrib/src/test/results/clientnegative/url_hook.q.out?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/contrib/src/test/results/clientnegative/url_hook.q.out (original)
+++ hive/trunk/contrib/src/test/results/clientnegative/url_hook.q.out Tue Jul  9 03:41:36 2013
@@ -5,5 +5,4 @@ POSTHOOK: type: SHOWTABLES
 src
 PREHOOK: query: SHOW TABLES 'src'
 PREHOOK: type: SHOWTABLES
-FAILED: Error in metadata: ERROR: The database default does not exist.
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Database does not exist: default

Modified: hive/trunk/hcatalog/src/test/e2e/templeton/tests/ddl.conf
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/src/test/e2e/templeton/tests/ddl.conf?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/src/test/e2e/templeton/tests/ddl.conf (original)
+++ hive/trunk/hcatalog/src/test/e2e/templeton/tests/ddl.conf Tue Jul  9 03:41:36 2013
@@ -299,7 +299,7 @@ $cfg = 
      'method' => 'GET',
      'url' => ':TEMPLETON_URL:/templeton/v1/ddl/database/templeton_testdb1/table/templeton_testtab1?user.name=:UNAME:',
      'status_code' => 404, 
-     'json_field_substr_match' => {'error' => 'templeton_testtab1 does not exist'},
+     'json_field_substr_match' => {'error' => 'FAILED: SemanticException \[Error 10001\]: Table not found templeton_testtab1'},
     },
     {
                                 #-ve test , describe on non existent table
@@ -307,7 +307,7 @@ $cfg = 
      'method' => 'GET',
      'url' => ':TEMPLETON_URL:/templeton/v1/ddl/database/templeton_testdb1/table/templeton_testtab1?user.name=:UNAME:&format=extended:',
      'status_code' => 404, 
-     'json_field_substr_match' => {'error' => 'templeton_testtab1 does not exist'},
+     'json_field_substr_match' => {'error' => 'FAILED: SemanticException \[Error 10001\]: Table not found templeton_testtab1'},
     },
 
    ]
@@ -732,7 +732,7 @@ STORED AS rcfile
      'status_code' => 404,
      'json_field_substr_match' => 
        {
-        'error' => 'Partition.*for table templetontest_parts does not exist'
+        'error' => 'FAILED: SemanticException \[Error 10006\]: Partition not found \{dt=20120101\, country=IN\}'
        },
     },
 

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/AppConfig.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/AppConfig.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/AppConfig.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/AppConfig.java Tue Jul  9 03:41:36 2013
@@ -116,6 +116,7 @@ public class AppConfig extends Configura
     public static final String HADOOP_SPECULATIVE_NAME
         = "mapred.map.tasks.speculative.execution";
     public static final String HADOOP_CHILD_JAVA_OPTS = "mapred.child.java.opts";
+    public static final String UNIT_TEST_MODE     = "templeton.unit.test.mode";
 
     
     private static final Log LOG = LogFactory.getLog(AppConfig.class);

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BadParam.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BadParam.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BadParam.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BadParam.java Tue Jul  9 03:41:36 2013
@@ -18,11 +18,13 @@
  */
 package org.apache.hcatalog.templeton;
 
+import org.eclipse.jetty.http.HttpStatus;
+
 /**
  * Missing required or badly configured paramater.
  */
 public class BadParam extends SimpleWebException {
     public BadParam(String msg) {
-        super(400, msg);
+        super(HttpStatus.BAD_REQUEST_400, msg);
     }
 }

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BusyException.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BusyException.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BusyException.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/BusyException.java Tue Jul  9 03:41:36 2013
@@ -18,11 +18,13 @@
  */
 package org.apache.hcatalog.templeton;
 
+import org.eclipse.jetty.http.HttpStatus;
+
 /**
  * Simple "we are busy, try again" exception.
  */
 public class BusyException extends SimpleWebException {
     public BusyException() {
-        super(503, "Busy, please retry");
+        super(HttpStatus.SERVICE_UNAVAILABLE_503, "Busy, please retry");
     }
 }

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CallbackFailedException.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CallbackFailedException.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CallbackFailedException.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CallbackFailedException.java Tue Jul  9 03:41:36 2013
@@ -18,11 +18,13 @@
  */
 package org.apache.hcatalog.templeton;
 
+import org.eclipse.jetty.http.HttpStatus;
+
 /**
  * The callback failed when it tried to reach the callback URL.
  */
 public class CallbackFailedException extends SimpleWebException {
     public CallbackFailedException(String msg) {
-        super(400, msg);
+        super(HttpStatus.BAD_REQUEST_400, msg);
     }
 }

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CatchallExceptionMapper.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CatchallExceptionMapper.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CatchallExceptionMapper.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/CatchallExceptionMapper.java Tue Jul  9 03:41:36 2013
@@ -24,6 +24,7 @@ import javax.ws.rs.ext.Provider;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.eclipse.jetty.http.HttpStatus;
 
 /**
  * Map all exceptions to the Jersey response.  This lets us have nice
@@ -36,6 +37,6 @@ public class CatchallExceptionMapper
 
     public Response toResponse(Exception e) {
         LOG.error(e.getMessage(), e);
-        return SimpleWebException.buildMessage(500, null, e.getMessage());
+        return SimpleWebException.buildMessage(HttpStatus.INTERNAL_SERVER_ERROR_500, null, e.getMessage());
     }
 }

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatDelegator.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatDelegator.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatDelegator.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatDelegator.java Tue Jul  9 03:41:36 2013
@@ -33,7 +33,9 @@ import org.apache.commons.logging.LogFac
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.ql.ErrorMsg;
 import org.apache.hcatalog.templeton.tool.TempletonUtils;
+import org.eclipse.jetty.http.HttpStatus;
 
 
 /**
@@ -95,7 +97,15 @@ public class HcatDelegator extends Launc
             args.add("-D");
             args.add("hive.format=json");
         }
-
+        LOG.info("Main.getAppConfigInstance().get(AppConfig.UNIT_TEST_MODE)=" +
+                Main.getAppConfigInstance().get(AppConfig.UNIT_TEST_MODE));
+        if(System.getProperty("hive.metastore.warehouse.dir") != null) {
+            /*when running in unit test mode, pass this property to HCat,
+            which will in turn pass it to Hive to make sure that Hive
+            tries to write to a directory that exists.*/
+            args.add("-D");
+            args.add("hive.metastore.warehouse.dir=" + System.getProperty("hive.metastore.warehouse.dir"));
+        }
         return args;
     }
 
@@ -113,12 +123,6 @@ public class HcatDelegator extends Launc
             String res = jsonRun(user, exec);
             return JsonBuilder.create(res).build();
         } catch (HcatException e) {
-            if (e.execBean.stderr.contains("SemanticException")) {
-                return JsonBuilder.create().
-                    put("error", "Database " + db + " does not exist")
-                    .put("errorCode", "404")
-                    .put("database", db).build();
-            }
             throw new HcatException("unable to describe database: " + db,
                 e.execBean, exec);
         }
@@ -256,14 +260,6 @@ public class HcatDelegator extends Launc
                 .put("table", table)
                 .build();
         } catch (HcatException e) {
-            if (e.execBean.stderr.contains("SemanticException") &&
-                e.execBean.stderr.contains("Table not found")) {
-                return JsonBuilder.create().
-                    put("error", "Table" + db + "." + table + " does not exist" )
-                    .put("errorCode", "404")
-                    .put("table", table)
-                    .put("database", db).build();
-            }
             throw new HcatException("unable to describe database: " + db,
                 e.execBean, exec);
         }
@@ -470,8 +466,8 @@ public class HcatDelegator extends Launc
             return JsonBuilder.mapToJson(tables.get(0));
         else {
             return JsonBuilder
-                .createError(String.format("Table %s does not exist", table),
-                    JsonBuilder.MISSING).
+                .createError(ErrorMsg.INVALID_TABLE.format(table),
+                        ErrorMsg.INVALID_TABLE.getErrorCode()).
                     buildJson();
         }
     }
@@ -530,7 +526,7 @@ public class HcatDelegator extends Launc
         throws HcatException, NotAuthorizedException, BusyException,
         ExecuteException, IOException {
         Response res = descTable(user, db, table, true);
-        if (res.getStatus() != JsonBuilder.OK)
+        if (res.getStatus() != HttpStatus.OK_200)
             return res;
         Map props = tableProperties(res.getEntity());
         Map found = null;
@@ -556,7 +552,7 @@ public class HcatDelegator extends Launc
         throws HcatException, NotAuthorizedException, BusyException,
         ExecuteException, IOException {
         Response res = descTable(user, db, table, true);
-        if (res.getStatus() != JsonBuilder.OK)
+        if (res.getStatus() != HttpStatus.OK_200)
             return res;
         Map props = tableProperties(res.getEntity());
         return JsonBuilder.create()
@@ -645,7 +641,8 @@ public class HcatDelegator extends Launc
                     + table + " does not exist" + db + "." + table + " does not exist";
                 return JsonBuilder.create()
                     .put("error", emsg)
-                    .put("errorCode", "404")
+                     //this error should really be produced by Hive (DDLTask)
+                    .put("errorCode", ErrorMsg.INVALID_PARTITION.getErrorCode())
                     .put("database", db)
                     .put("table", table)
                     .put("partition", partition)
@@ -678,7 +675,8 @@ public class HcatDelegator extends Launc
             if (res.indexOf("AlreadyExistsException") > -1) {
                 return JsonBuilder.create().
                     put("error", "Partition already exists")
-                    .put("errorCode", "409")
+                     //This error code should really be produced by Hive
+                    .put("errorCode", ErrorMsg.PARTITION_EXISTS.getErrorCode())
                     .put("database", db)
                     .put("table", table)
                     .put("partition", desc.partition).build();
@@ -742,13 +740,13 @@ public class HcatDelegator extends Launc
         throws SimpleWebException, NotAuthorizedException, BusyException,
         ExecuteException, IOException {
         Response res = listColumns(user, db, table);
-        if (res.getStatus() != JsonBuilder.OK)
+        if (res.getStatus() != HttpStatus.OK_200)
             return res;
 
         Object o = res.getEntity();
         final Map fields = (o != null && (o instanceof Map)) ? (Map) o : null;
         if (fields == null)
-            throw new SimpleWebException(500, "Internal error, unable to find column "
+            throw new SimpleWebException(HttpStatus.INTERNAL_SERVER_ERROR_500, "Internal error, unable to find column "
                 + column);
 
 
@@ -763,7 +761,7 @@ public class HcatDelegator extends Launc
             }
         }
         if (found == null)
-            throw new SimpleWebException(500, "unable to find column " + column,
+            throw new SimpleWebException(HttpStatus.INTERNAL_SERVER_ERROR_500, "unable to find column " + column,
                 new HashMap<String, Object>() {
                     {
                         put("description", fields);

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatException.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatException.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatException.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/HcatException.java Tue Jul  9 03:41:36 2013
@@ -18,6 +18,8 @@
  */
 package org.apache.hcatalog.templeton;
 
+import org.eclipse.jetty.http.HttpStatus;
+
 import java.util.HashMap;
 
 /**
@@ -28,7 +30,7 @@ public class HcatException extends Simpl
     public String statement;
 
     public HcatException(String msg, final ExecBean bean, final String statement) {
-        super(500, msg, new HashMap<String, Object>() {
+        super(HttpStatus.INTERNAL_SERVER_ERROR_500, msg, new HashMap<String, Object>() {
             {
                 put("exec", bean);
                 put("statement", statement);

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/JsonBuilder.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/JsonBuilder.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/JsonBuilder.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/JsonBuilder.java Tue Jul  9 03:41:36 2013
@@ -25,17 +25,34 @@ import java.util.Map;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 
+import org.apache.hadoop.hive.ql.ErrorMsg;
 import org.apache.hcatalog.templeton.tool.TempletonUtils;
 import org.codehaus.jackson.map.ObjectMapper;
+import org.eclipse.jetty.http.HttpStatus;
 
 /**
  * Helper class to build new json objects with new top level
  * properties.  Only add non-null entries.
  */
 public class JsonBuilder {
-    static final int OK = 200;
-    static final int MISSING = 404;
-    static final int SERVER_ERROR = 500;
+    private static final Map<Object, Integer> hiveError2HttpStatusCode = new HashMap<Object, Integer>();
+
+    /**
+     * It's expected that Hive (and thus HCat CLI) will return canonical error msgs/codes.
+     * Here they are mapped to appropriate HTTP Status Code.
+     */
+    static {
+        hiveError2HttpStatusCode.put(ErrorMsg.GENERIC_ERROR.getErrorCode(), HttpStatus.INTERNAL_SERVER_ERROR_500);
+        hiveError2HttpStatusCode.put(ErrorMsg.DATABASE_NOT_EXISTS.getErrorCode(), HttpStatus.NOT_FOUND_404);
+        hiveError2HttpStatusCode.put(ErrorMsg.INVALID_TABLE.getErrorCode(), HttpStatus.NOT_FOUND_404);
+        hiveError2HttpStatusCode.put(ErrorMsg.TABLE_NOT_PARTITIONED.getErrorCode(), HttpStatus.NOT_FOUND_404);
+        hiveError2HttpStatusCode.put(ErrorMsg.INVALID_PARTITION.getErrorCode(), HttpStatus.NOT_FOUND_404);
+
+        hiveError2HttpStatusCode.put(ErrorMsg.DUPLICATE_COLUMN_NAMES.getErrorCode(), HttpStatus.CONFLICT_409);
+        hiveError2HttpStatusCode.put(ErrorMsg.DATABSAE_ALREADY_EXISTS.getErrorCode(), HttpStatus.CONFLICT_409);
+        hiveError2HttpStatusCode.put(ErrorMsg.PARTITION_EXISTS.getErrorCode(), HttpStatus.CONFLICT_409);
+        hiveError2HttpStatusCode.put(ErrorMsg.TABLE_ALREADY_EXISTS.getErrorCode(), HttpStatus.CONFLICT_409);
+    }
 
     // The map we're building.
     private Map map;
@@ -65,11 +82,11 @@ public class JsonBuilder {
     /**
      * Create a new map error object.
      */
-    public static JsonBuilder createError(String msg, int code)
+    public static JsonBuilder createError(String msg, int errorCode)
         throws IOException {
         return new JsonBuilder(null)
             .put("error", msg)
-            .put("errorCode", code);
+            .put("errorCode", errorCode);
     }
 
     /**
@@ -115,16 +132,13 @@ public class JsonBuilder {
      * Turn the map back to response object.
      */
     public Response buildResponse() {
-        int status = OK;        // Server ok.
+        int status = HttpStatus.OK_200;        // Server ok.
         if (map.containsKey("error"))
-            status = SERVER_ERROR; // Generic http server error.
+            status = HttpStatus.INTERNAL_SERVER_ERROR_500; // Generic http server error.
         Object o = map.get("errorCode");
         if (o != null) {
-            try {
-                status = Integer.parseInt(o.toString());
-            } catch (Exception e) {
-                if (o instanceof Number)
-                    status = ((Number) o).intValue();
+            if(hiveError2HttpStatusCode.containsKey(o)) {
+                status = hiveError2HttpStatusCode.get(o);
             }
         }
         return buildResponse(status);

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/Main.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/Main.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/Main.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/Main.java Tue Jul  9 03:41:36 2013
@@ -50,6 +50,7 @@ public class Main {
     private static final Log LOG = LogFactory.getLog(Main.class);
 
     public static final int DEFAULT_PORT = 8080;
+    private Server server;
 
     private static volatile AppConfig conf;
 
@@ -62,7 +63,7 @@ public class Main {
         return conf;
     }
 
-    public Main(String[] args) {
+    Main(String[] args) {
         init(args);
     }
 
@@ -115,6 +116,17 @@ public class Main {
             System.exit(1);
         }
     }
+    void stop() {
+        if(server != null) {
+            try {
+                server.stop();
+            }
+            catch(Exception ex) {
+                LOG.warn("Failed to stop jetty.Server", ex);
+            }
+        }
+    }
+
 
     private void checkEnv() {
         checkCurrentDirPermissions();
@@ -179,6 +191,7 @@ public class Main {
 
         // Start the server
         server.start();
+        this.server = server;
         return server;
     }
 

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/NotAuthorizedException.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/NotAuthorizedException.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/NotAuthorizedException.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/NotAuthorizedException.java Tue Jul  9 03:41:36 2013
@@ -18,11 +18,13 @@
  */
 package org.apache.hcatalog.templeton;
 
+import org.eclipse.jetty.http.HttpStatus;
+
 /**
  * Simple "user not found" type exception.
  */
 public class NotAuthorizedException extends SimpleWebException {
     public NotAuthorizedException(String msg) {
-        super(401, msg);
+        super(HttpStatus.UNAUTHORIZED_401, msg);
     }
 }

Modified: hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/QueueException.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/QueueException.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/QueueException.java (original)
+++ hive/trunk/hcatalog/webhcat/svr/src/main/java/org/apache/hcatalog/templeton/QueueException.java Tue Jul  9 03:41:36 2013
@@ -18,12 +18,14 @@
  */
 package org.apache.hcatalog.templeton;
 
+import org.eclipse.jetty.http.HttpStatus;
+
 /**
  * Unable to queue the job
  */
 public class QueueException extends SimpleWebException {
     public QueueException(String msg) {
-        super(500, msg);
+        super(HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
     }
 
 }

Added: hive/trunk/hcatalog/webhcat/svr/src/test/java/org/apache/hcatalog/templeton/TestWebHCatE2e.java
URL: http://svn.apache.org/viewvc/hive/trunk/hcatalog/webhcat/svr/src/test/java/org/apache/hcatalog/templeton/TestWebHCatE2e.java?rev=1501053&view=auto
==============================================================================
--- hive/trunk/hcatalog/webhcat/svr/src/test/java/org/apache/hcatalog/templeton/TestWebHCatE2e.java (added)
+++ hive/trunk/hcatalog/webhcat/svr/src/test/java/org/apache/hcatalog/templeton/TestWebHCatE2e.java Tue Jul  9 03:41:36 2013
@@ -0,0 +1,283 @@
+/**
+ * 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.hcatalog.templeton;
+
+import junit.framework.Assert;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.methods.DeleteMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+import org.apache.hadoop.hive.ql.ErrorMsg;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.http.HttpStatus;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A set of tests exercising e2e WebHCat DDL APIs.  These tests are somewhat
+ * between WebHCat e2e (hcatalog/src/tests/e2e/templeton) tests and simple58
+ * 
+ * unit tests.  This will start a WebHCat server and make REST calls to it.
+ * It doesn't need Hadoop or (standalone) metastore to be running.
+ * Running this is much simpler than e2e tests.
+ *
+ * Most of these tests check that HTTP Status code is what is expected and
+ * Hive Error code {@link org.apache.hadoop.hive.ql.ErrorMsg} is what is
+ * expected.
+ *
+ * It may be possible to extend this to more than just DDL later.
+ */
+public class TestWebHCatE2e {
+    private static final Logger LOG =
+          LoggerFactory.getLogger(TestWebHCatE2e.class);
+    private static final String templetonBaseUrl =
+          "http://localhost:50111/templeton/v1";
+    private static final String username= "johndoe";
+    private static final String ERROR_CODE = "errorCode";
+    private static Main templetonServer;
+    private static final String charSet = "UTF-8";
+    //  "not ready due to HIVE-4820"
+    //@BeforeClass
+    public static void startHebHcatInMem() {
+        templetonServer = new Main(new String[] {"-D" + AppConfig.UNIT_TEST_MODE + "=true"});
+        LOG.info("Starting Main");
+        templetonServer.run();
+        LOG.info("Main started");
+    }
+    @AfterClass
+    public static void stopWebHcatInMem() {
+        if(templetonServer != null) {
+            LOG.info("Stopping Main");
+            templetonServer.stop();
+            LOG.info("Main stopped");
+        }
+    }
+    @Ignore("not ready due to HIVE-4820")
+    @Test
+    public void getStatus() throws IOException {
+        LOG.debug("+getStatus()");
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/status", HTTP_METHOD_TYPE.GET);
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.OK_200, p.httpStatusCode);
+        Assert.assertEquals(p.getAssertMsg(), "{\"status\":\"ok\",\"version\":\"v1\"}", p.responseBody);
+        LOG.debug("-getStatus()");
+    }
+    @Ignore("not ready due to HIVE-4824")
+    @Test
+    public void listDataBases() throws IOException {
+        LOG.debug("+listDataBases()");
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/ddl/database", HTTP_METHOD_TYPE.GET);
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.OK_200, p.httpStatusCode);
+        Assert.assertEquals(p.getAssertMsg(), "{\"databases\":[\"default\"]}", p.responseBody);
+        LOG.debug("-listDataBases()");
+    }
+    /**
+     * Check that we return correct status code when the URL doesn't map to any method
+     * in {@link Server}
+     */
+    @Ignore("not ready due to HIVE-4820")
+    @Test
+    public void invalidPath() throws IOException {
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/no_such_mapping/database", HTTP_METHOD_TYPE.GET);
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.INTERNAL_SERVER_ERROR_500, p.httpStatusCode);
+    }
+    /**
+     * tries to drop table in a DB that doesn't exist
+     */
+    @Ignore("not ready due to HIVE-4824")
+    @Test
+    public void dropTableNoSuchDB() throws IOException {
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl +
+            "/ddl/database/no_such_db/table/t1", HTTP_METHOD_TYPE.DELETE);
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.NOT_FOUND_404, p.httpStatusCode);
+        Assert.assertEquals(p.getAssertMsg(),
+            ErrorMsg.DATABASE_NOT_EXISTS.getErrorCode(),
+            getErrorCode(p.responseBody));
+    }
+    /**
+     * tries to drop table in a DB that doesn't exist
+     */
+    @Ignore("not ready due to HIVE-4824")
+    @Test
+    public void dropTableNoSuchDbIfExists() throws IOException {
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/ddl/database/no_such_db/table/t1",
+            HTTP_METHOD_TYPE.DELETE, null, new NameValuePair[]
+            {new NameValuePair("ifExists", "true")});
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.NOT_FOUND_404, p.httpStatusCode);
+        Assert.assertEquals(p.getAssertMsg(), ErrorMsg.DATABASE_NOT_EXISTS.getErrorCode(), getErrorCode(p.responseBody));
+    }
+    /**
+     * tries to drop table that doesn't exist (with ifExists=true)
+    */
+    @Ignore("not ready due to HIVE-4824")
+    @Test
+    public void dropTableIfExists() throws IOException {
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/ddl/database/default/table/no_such_table",
+            HTTP_METHOD_TYPE.DELETE, null, new NameValuePair[]
+            {new NameValuePair("ifExists", "true")});
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.OK_200, p.httpStatusCode);
+    }
+    @Ignore("not ready due to HIVE-4824")
+    @Test
+    public void createDataBase() throws IOException {
+        Map<String, Object> props = new HashMap<String, Object>();
+        props.put("comment", "Hello, there");
+        props.put("location", "file://" + System.getProperty("hive.metastore.warehouse.dir"));
+        Map<String, String> props2 = new HashMap<String, String>();
+        props2.put("prop", "val");
+        props.put("properties", props2);
+        //{ "comment":"Hello there", "location":"file:///tmp/warehouse", "properties":{"a":"b"}}
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl + "/ddl/database/newdb", HTTP_METHOD_TYPE.PUT, props, null);
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.OK_200, p.httpStatusCode);
+    }
+    @Ignore("not ready due to HIVE-4824")
+    @Test
+    public void createTable() throws IOException {
+        //{ "comment":"test", "columns": [ { "name": "col1", "type": "string" } ], "format": { "storedAs": "rcfile" } }
+        Map<String, Object> props = new HashMap<String, Object>();
+        props.put("comment", "Table in default db");
+        Map<String, Object> col = new HashMap<String, Object>();
+        col.put("name", "col1");
+        col.put("type", "string");
+        List<Map<String, Object>> colList = new ArrayList<Map<String, Object>>(1);
+        colList.add(col);
+        props.put("columns", colList);
+        Map<String, Object> format = new HashMap<String, Object>();
+        format.put("storedAs", "rcfile");
+        props.put("format", format);
+        MethodCallRetVal createTbl = doHttpCall(templetonBaseUrl + "/ddl/database/default/table/test_table", HTTP_METHOD_TYPE.PUT, props, null);
+        Assert.assertEquals(createTbl.getAssertMsg(), HttpStatus.OK_200, createTbl.httpStatusCode);
+        LOG.info("createTable() resp: " + createTbl.responseBody);
+
+        MethodCallRetVal descTbl = doHttpCall(templetonBaseUrl + "/ddl/database/default/table/test_table", HTTP_METHOD_TYPE.GET);
+        Assert.assertEquals(descTbl.getAssertMsg(), HttpStatus.OK_200, descTbl.httpStatusCode);
+    }
+    @Ignore("not ready due to HIVE-4824")
+    @Test
+    public void describeNoSuchTable() throws IOException {
+        MethodCallRetVal p = doHttpCall(templetonBaseUrl +
+            "/ddl/database/default/table/no_such_table", HTTP_METHOD_TYPE.GET);
+        Assert.assertEquals(p.getAssertMsg(), HttpStatus.NOT_FOUND_404,
+            p.httpStatusCode);
+        Assert.assertEquals(p.getAssertMsg(),
+            ErrorMsg.INVALID_TABLE.getErrorCode(),
+            getErrorCode(p.responseBody));
+    }
+    /**
+     * It's expected that Templeton returns a properly formatted JSON object when it
+     * encounters an error.  It should have {@code ERROR_CODE} element in it which
+     * should be the Hive canonical error msg code.
+     * @return the code or -1 if it cannot be found
+     */
+    private static int getErrorCode(String jsonErrorObject) throws IOException {
+        @SuppressWarnings("unchecked")//JSON key is always a String
+        Map<String, Object> retProps = JsonBuilder.jsonToMap(jsonErrorObject + "blah blah");
+        int hiveRetCode = -1;
+        if(retProps.get(ERROR_CODE) !=null) {
+            hiveRetCode = Integer.parseInt(retProps.get(ERROR_CODE).toString());
+        }
+        return hiveRetCode;
+    }
+    /**
+     * Encapsulates information from HTTP method call
+     */
+    private static class MethodCallRetVal {
+        private final int httpStatusCode;
+        private final String responseBody;
+        private final String submittedURL;
+        private final String methodName;
+        private MethodCallRetVal(int httpStatusCode, String responseBody, String submittedURL, String methodName) {
+            this.httpStatusCode = httpStatusCode;
+            this.responseBody = responseBody;
+            this.submittedURL = submittedURL;
+            this.methodName = methodName;
+        }
+        String getAssertMsg() {
+            return methodName + " " + submittedURL + " " + responseBody;
+        }
+    }
+    private static enum HTTP_METHOD_TYPE {GET, POST, DELETE, PUT}
+    private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type) throws IOException {
+        return doHttpCall(uri, type, null, null);
+    }
+    /**
+     * Does a basic HTTP GET and returns Http Status code + response body
+     * Will add the dummy user query string
+     */
+    private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data, NameValuePair[] params) throws IOException {
+        HttpClient client = new HttpClient();
+        HttpMethod method;
+        switch (type) {
+        case GET:
+            method = new GetMethod(uri);
+            break;
+        case DELETE:
+            method = new DeleteMethod(uri);
+            break;
+        case PUT:
+            method = new PutMethod(uri);
+            if(data == null) {
+                break;
+            }
+            String msgBody = JsonBuilder.mapToJson(data);
+            LOG.info("Msg Body: " + msgBody);
+            StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet);
+            ((PutMethod)method).setRequestEntity(sre);
+            break;
+        default:
+            throw new IllegalArgumentException("Unsupported method type: " + type);
+        }
+        if(params == null) {
+            method.setQueryString(new NameValuePair[] {new NameValuePair("user.name", username)});
+        }
+        else {
+            NameValuePair[] newParams = new NameValuePair[params.length + 1];
+            System.arraycopy(params, 0, newParams, 1, params.length);
+            newParams[0] = new NameValuePair("user.name", username);
+            method.setQueryString(newParams);
+        }
+        String actualUri = "no URI";
+        try {
+            actualUri = method.getURI().toString();//should this be escaped string?
+            LOG.debug(type + ": " + method.getURI().getEscapedURI());
+            int httpStatus = client.executeMethod(method);
+            LOG.debug("Http Status Code=" + httpStatus);
+            String resp = method.getResponseBodyAsString();
+            LOG.debug("response: " + resp);
+            return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName());
+        }
+        catch (IOException ex) {
+            LOG.error("doHttpCall() failed", ex);
+        }
+        finally {
+            method.releaseConnection();
+        }
+        return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri, method.getName());
+    }
+}

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/Driver.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/Driver.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/Driver.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/Driver.java Tue Jul  9 03:41:36 2013
@@ -78,6 +78,9 @@ import org.apache.hadoop.hive.ql.metadat
 import org.apache.hadoop.hive.ql.metadata.HiveException;
 import org.apache.hadoop.hive.ql.metadata.Partition;
 import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.ql.metadata.formatting.JsonMetaDataFormatter;
+import org.apache.hadoop.hive.ql.metadata.formatting.MetaDataFormatUtils;
+import org.apache.hadoop.hive.ql.metadata.formatting.MetaDataFormatter;
 import org.apache.hadoop.hive.ql.optimizer.ppr.PartitionPruner;
 import org.apache.hadoop.hive.ql.parse.ASTNode;
 import org.apache.hadoop.hive.ql.parse.AbstractSemanticAnalyzerHook;
@@ -126,6 +129,7 @@ public class Driver implements CommandPr
 
   private String errorMessage;
   private String SQLState;
+  private Throwable downstreamError;
 
   // A limit on the number of threads that can be launched
   private int maxthreads;
@@ -143,6 +147,7 @@ public class Driver implements CommandPr
       } catch (SemanticException e) {
         errorMessage = "FAILED: Error in semantic analysis: " + e.getMessage();
         SQLState = ErrorMsg.findSQLState(e.getMessage());
+        downstreamError = e;
         console.printError(errorMessage, "\n"
             + org.apache.hadoop.util.StringUtils.stringifyException(e));
         return false;
@@ -483,8 +488,9 @@ public class Driver implements CommandPr
           perfLogger.PerfLogBegin(LOG, PerfLogger.DO_AUTHORIZATION);
           doAuthorization(sem);
         } catch (AuthorizationException authExp) {
-          console.printError("Authorization failed:" + authExp.getMessage()
-              + ". Use show grant to get more details.");
+          errorMessage = "Authorization failed:" + authExp.getMessage()
+                  + ". Use show grant to get more details.";
+          console.printError(errorMessage);
           return 403;
         } finally {
           perfLogger.PerfLogEnd(LOG, PerfLogger.DO_AUTHORIZATION);
@@ -502,6 +508,7 @@ public class Driver implements CommandPr
       }
       errorMessage += " " + e.getMessage();
       SQLState = error.getSQLState();
+      downstreamError = e;
       console.printError(errorMessage, "\n"
           + org.apache.hadoop.util.StringUtils.stringifyException(e));
       return error.getErrorCode();
@@ -837,12 +844,14 @@ public class Driver implements CommandPr
     } catch (SemanticException e) {
       errorMessage = "FAILED: Error in acquiring locks: " + e.getMessage();
       SQLState = ErrorMsg.findSQLState(e.getMessage());
+      downstreamError = e;
       console.printError(errorMessage, "\n"
           + org.apache.hadoop.util.StringUtils.stringifyException(e));
       return (10);
     } catch (LockException e) {
       errorMessage = "FAILED: Error in acquiring locks: " + e.getMessage();
       SQLState = ErrorMsg.findSQLState(e.getMessage());
+      downstreamError = e;
       console.printError(errorMessage, "\n"
           + org.apache.hadoop.util.StringUtils.stringifyException(e));
       return (10);
@@ -869,8 +878,62 @@ public class Driver implements CommandPr
   }
 
   public CommandProcessorResponse run(String command) throws CommandNeedRetryException {
+    CommandProcessorResponse cpr = runInternal(command);
+    if(cpr.getResponseCode() == 0) 
+      return cpr;
+    SessionState ss = SessionState.get();
+    if(ss == null) 
+      return cpr;
+    MetaDataFormatter mdf = MetaDataFormatUtils.getFormatter(ss.getConf());
+    if(!(mdf instanceof JsonMetaDataFormatter)) 
+      return cpr;
+    /*Here we want to encode the error in machine readable way (e.g. JSON)
+     * Ideally, errorCode would always be set to a canonical error defined in ErrorMsg.
+     * In practice that is rarely the case, so the messy logic below tries to tease
+     * out canonical error code if it can.  Exclude stack trace from output when
+     * the error is a specific/expected one.
+     * It's written to stdout for backward compatibility (WebHCat consumes it).*/
+    try {
+      if(downstreamError == null) {
+        mdf.error(ss.out, errorMessage, cpr.getResponseCode(), SQLState);
+        return cpr;
+      }
+      ErrorMsg canonicalErr = ErrorMsg.getErrorMsg(cpr.getResponseCode());
+      if(canonicalErr != null && canonicalErr != ErrorMsg.GENERIC_ERROR) {
+        /*Some HiveExceptions (e.g. SemanticException) don't set
+          canonical ErrorMsg explicitly, but there is logic
+          (e.g. #compile()) to find an appropriate canonical error and
+          return its code as error code. In this case we want to
+          preserve it for downstream code to interpret*/
+        mdf.error(ss.out, errorMessage, cpr.getResponseCode(), SQLState, null);
+        return cpr;
+      }
+      if(downstreamError instanceof HiveException) {
+        HiveException rc = (HiveException) downstreamError;
+        mdf.error(ss.out, errorMessage,
+                rc.getCanonicalErrorMsg().getErrorCode(), SQLState,
+                rc.getCanonicalErrorMsg() == ErrorMsg.GENERIC_ERROR ?
+                        org.apache.hadoop.util.StringUtils.stringifyException(rc)
+                        : null);
+      }
+      else {
+        ErrorMsg canonicalMsg =
+                ErrorMsg.getErrorMsg(downstreamError.getMessage());
+        mdf.error(ss.out, errorMessage, canonicalMsg.getErrorCode(),
+                SQLState, org.apache.hadoop.util.StringUtils.
+                stringifyException(downstreamError));
+      }
+    }
+    catch(HiveException ex) {
+      console.printError("Unable to JSON-encode the error",
+              org.apache.hadoop.util.StringUtils.stringifyException(ex));
+    }
+    return cpr;
+  }
+  private CommandProcessorResponse runInternal(String command) throws CommandNeedRetryException {
     errorMessage = null;
     SQLState = null;
+    downstreamError = null;
 
     if (!validateConfVariables()) {
       return new CommandProcessorResponse(12, errorMessage, SQLState);
@@ -885,10 +948,11 @@ public class Driver implements CommandPr
           driverRunHook.preDriverRun(hookContext);
       }
     } catch (Exception e) {
-      errorMessage = "FAILED: Hive Internal Error: " + Utilities.getNameMessage(e)
-          + "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e);
+      errorMessage = "FAILED: Hive Internal Error: " + Utilities.getNameMessage(e);
       SQLState = ErrorMsg.findSQLState(e.getMessage());
-      console.printError(errorMessage);
+      downstreamError = e;
+      console.printError(errorMessage + "\n"
+          + org.apache.hadoop.util.StringUtils.stringifyException(e));
       return new CommandProcessorResponse(12, errorMessage, SQLState);
     }
 
@@ -961,10 +1025,11 @@ public class Driver implements CommandPr
           driverRunHook.postDriverRun(hookContext);
       }
     } catch (Exception e) {
-      errorMessage = "FAILED: Hive Internal Error: " + Utilities.getNameMessage(e)
-          + "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e);
+      errorMessage = "FAILED: Hive Internal Error: " + Utilities.getNameMessage(e);
       SQLState = ErrorMsg.findSQLState(e.getMessage());
-      console.printError(errorMessage);
+      downstreamError = e;
+      console.printError(errorMessage + "\n"
+          + org.apache.hadoop.util.StringUtils.stringifyException(e));
       return new CommandProcessorResponse(12, errorMessage, SQLState);
     }
 
@@ -984,7 +1049,7 @@ public class Driver implements CommandPr
                   .getBoolVar(HiveConf.ConfVars.HIVE_OPTIMIZE_UNION_REMOVE))))) {
       errorMessage = "FAILED: Hive Internal Error: "
           + ErrorMsg.SUPPORT_DIR_MUST_TRUE_FOR_LIST_BUCKETING.getMsg();
-      SQLState = ErrorMsg.findSQLState(errorMessage);
+      SQLState = ErrorMsg.SUPPORT_DIR_MUST_TRUE_FOR_LIST_BUCKETING.getSQLState();
       console.printError(errorMessage + "\n");
       valid = false;
     }
@@ -1158,12 +1223,7 @@ public class Driver implements CommandPr
           }
           Task<? extends Serializable> backupTask = tsk.getAndInitBackupTask();
           if (backupTask != null) {
-            errorMessage = "FAILED: Execution Error, return code " + exitVal + " from "
-                + tsk.getClass().getName();
-            ErrorMsg em = ErrorMsg.getErrorMsg(exitVal);
-            if (em != null) {
-              errorMessage += ". " +  em.getMsg();
-            }
+            setErrorMsgAndDetail(exitVal, tskRes.getTaskError(), tsk);
             console.printError(errorMessage);
             errorMessage = "ATTEMPT: Execute BackupTask: " + backupTask.getClass().getName();
             console.printError(errorMessage);
@@ -1184,13 +1244,7 @@ public class Driver implements CommandPr
 
               perfLogger.PerfLogEnd(LOG, PerfLogger.FAILURE_HOOK + ofh.getClass().getName());
             }
-
-            errorMessage = "FAILED: Execution Error, return code " + exitVal + " from "
-                + tsk.getClass().getName();
-            ErrorMsg em = ErrorMsg.getErrorMsg(exitVal);
-            if (em != null) {
-              errorMessage += ". " +  em.getMsg();
-            }
+            setErrorMsgAndDetail(exitVal, tskRes.getTaskError(), tsk);
             SQLState = "08S01";
             console.printError(errorMessage);
             if (!running.isEmpty()) {
@@ -1273,6 +1327,7 @@ public class Driver implements CommandPr
       // TODO: do better with handling types of Exception here
       errorMessage = "FAILED: Hive Internal Error: " + Utilities.getNameMessage(e);
       SQLState = "08S01";
+      downstreamError = e;
       console.printError(errorMessage + "\n"
           + org.apache.hadoop.util.StringUtils.stringifyException(e));
       return (12);
@@ -1308,7 +1363,21 @@ public class Driver implements CommandPr
 
     return (0);
   }
-
+  private void setErrorMsgAndDetail(int exitVal, Throwable downstreamError, Task tsk) {
+    this.downstreamError = downstreamError;
+    errorMessage = "FAILED: Execution Error, return code " + exitVal + " from " + tsk.getClass().getName();
+    if(downstreamError != null) {
+      //here we assume that upstream code may have parametrized the msg from ErrorMsg
+      //so we want to keep it
+      errorMessage += ". " + downstreamError.getMessage();
+    }
+    else {
+      ErrorMsg em = ErrorMsg.getErrorMsg(exitVal);
+      if (em != null) {
+        errorMessage += ". " +  em.getMsg();
+      }
+    }
+  }
   /**
    * Launches a new task
    *
@@ -1388,7 +1457,7 @@ public class Driver implements CommandPr
     while (true) {
       while (resultIterator.hasNext()) {
         TaskResult tskRes = resultIterator.next();
-        if (tskRes.isRunning() == false) {
+        if (!tskRes.isRunning()) {
           return tskRes;
         }
       }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/ErrorMsg.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/ErrorMsg.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/ErrorMsg.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/ErrorMsg.java Tue Jul  9 03:41:36 2013
@@ -32,11 +32,15 @@ import org.apache.hadoop.hive.ql.parse.A
 /**
  * List of all error messages.
  * This list contains both compile time and run-time errors.
- **/
+ *
+ * This class supports parametrized messages such as (@link #TRUNCATE_FOR_NON_MANAGED_TABLE}.  These are
+ * preferable over un-parametrized ones where arbitrary String is appended to the end of the message,
+ * for example {@link #getMsg(String)} and {@link #INVALID_TABLE}.
+ */
 
 public enum ErrorMsg {
   // The error codes are Hive-specific and partitioned into the following ranges:
-  // 10000 to 19999: Errors occuring during semantic analysis and compilation of the query.
+  // 10000 to 19999: Errors occurring during semantic analysis and compilation of the query.
   // 20000 to 29999: Runtime errors where Hive believes that retries are unlikely to succeed.
   // 30000 to 39999: Runtime errors which Hive thinks may be transient and retrying may succeed.
   // 40000 to 49999: Errors where Hive is unable to advise about retries.
@@ -351,6 +355,12 @@ public enum ErrorMsg {
   TRUNCATE_LIST_BUCKETED_COLUMN(10240,
       "A column on which a partition/table is list bucketed cannot be truncated."),
 
+  TABLE_NOT_PARTITIONED(10241, "Table {0} is not a partitioned table", true),
+  DATABSAE_ALREADY_EXISTS(10242, "Database {0} already exists", true),
+  CANNOT_REPLACE_COLUMNS(10243, "Replace columns is not supported for table {0}. SerDe may be incompatible.", true),
+  BAD_LOCATION_VALUE(10244, "{0}  is not absolute or has no scheme information.  Please specify a complete absolute uri with scheme information."),
+  UNSUPPORTED_ALTER_TBL_OP(10245, "{0} alter table options is not supported"),
+
   SCRIPT_INIT_ERROR(20000, "Unable to initialize custom script."),
   SCRIPT_IO_ERROR(20001, "An error occurred while reading or writing to your custom script. "
       + "It may have crashed with an error."),
@@ -488,7 +498,7 @@ public enum ErrorMsg {
 
   /**
    * For a given error message string, searches for a <code>ErrorMsg</code> enum
-   * that appears to be a match. If an match is found, returns the
+   * that appears to be a match. If a match is found, returns the
    * <code>SQLState</code> associated with the <code>ErrorMsg</code>. If a match
    * is not found or <code>ErrorMsg</code> has no <code>SQLState</code>, returns
    * the <code>SQLState</code> bound to the <code>GENERIC_ERROR</code>
@@ -605,10 +615,41 @@ public enum ErrorMsg {
   public String format(String reason) {
     return format(new String[]{reason});
   }
-
+  /**
+   * If the message is parametrized, this will fill the parameters with supplied 
+   * {@code reasons}, otherwise {@code reasons} are appended at the end of the 
+   * message.
+   */
   public String format(String... reasons) {
-    assert format != null;
-    return format.format(reasons);
+    /* Not all messages are parametrized even those that should have been, e.g {@link #INVALID_TABLE}.
+     INVALID_TABLE is usually used with {@link #getMsg(String)}.
+     This method can also be used with INVALID_TABLE and the like and will match getMsg(String) behavior.
+
+     Another example: {@link #INVALID_PARTITION}.  Ideally you want the message to have 2 parameters one for
+     partition name one for table name.  Since this is already defined w/o any parameters, one can still call
+     {@code INVALID_PARTITION.format("<partName> <table Name>"}.  This way the message text will be slightly
+     different but at least the errorCode will match.  Note this, should not be abused by adding anything other
+     than what should have been parameter names to keep msg text standardized.
+     */
+    if(reasons == null || reasons.length == 0) {
+      return getMsg();
+    }
+    if(format != null) {
+      return format.format(reasons);
+    }
+    if(reasons.length > 1) {
+      StringBuilder sb = new StringBuilder();
+      for(String re : reasons) {
+        if(re != null) {
+          if(sb.length() > 0) {
+            sb.append(" ");
+          }
+          sb.append(re);
+        }
+      }
+      return getMsg(sb.toString());
+    }
+    return getMsg(reasons[0]);
   }
 
   public String getErrorCodedMsg() {

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java Tue Jul  9 03:41:36 2013
@@ -80,6 +80,7 @@ import org.apache.hadoop.hive.metastore.
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.ql.Context;
 import org.apache.hadoop.hive.ql.DriverContext;
+import org.apache.hadoop.hive.ql.ErrorMsg;
 import org.apache.hadoop.hive.ql.QueryPlan;
 import org.apache.hadoop.hive.ql.exec.ArchiveUtils.PartSpecInfo;
 import org.apache.hadoop.hive.ql.hooks.ReadEntity;
@@ -102,10 +103,8 @@ import org.apache.hadoop.hive.ql.metadat
 import org.apache.hadoop.hive.ql.metadata.InvalidTableException;
 import org.apache.hadoop.hive.ql.metadata.Partition;
 import org.apache.hadoop.hive.ql.metadata.Table;
-import org.apache.hadoop.hive.ql.metadata.formatting.JsonMetaDataFormatter;
 import org.apache.hadoop.hive.ql.metadata.formatting.MetaDataFormatUtils;
 import org.apache.hadoop.hive.ql.metadata.formatting.MetaDataFormatter;
-import org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataFormatter;
 import org.apache.hadoop.hive.ql.parse.AlterTablePartMergeFilesDesc;
 import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer;
 import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
@@ -205,14 +204,7 @@ public class DDLTask extends Task<DDLWor
 
     // Pick the formatter to use to display the results.  Either the
     // normal human readable output or a json object.
-    if ("json".equals(conf.get(
-            HiveConf.ConfVars.HIVE_DDL_OUTPUT_FORMAT.varname, "text"))) {
-      formatter = new JsonMetaDataFormatter();
-    } else {
-      formatter = new TextMetaDataFormatter(
-                      conf.getIntVar(HiveConf.ConfVars.CLIPRETTYOUTPUTNUMCOLS));
-    }
-
+    formatter = MetaDataFormatUtils.getFormatter(conf);
     INTERMEDIATE_ARCHIVED_DIR_SUFFIX =
       HiveConf.getVar(conf, ConfVars.METASTORE_INT_ARCHIVED);
     INTERMEDIATE_ORIGINAL_DIR_SUFFIX =
@@ -437,32 +429,10 @@ public class DDLTask extends Task<DDLWor
       if (alterTableExchangePartition != null) {
         return exchangeTablePartition(db, alterTableExchangePartition);
       }
-
-    } catch (InvalidTableException e) {
-      formatter.consoleError(console, "Table " + e.getTableName() + " does not exist",
-                             formatter.MISSING);
-      LOG.debug(stringifyException(e));
-      return 1;
-    } catch (AlreadyExistsException e) {
-      formatter.consoleError(console, e.getMessage(), formatter.CONFLICT);
-      return 1;
-    } catch (NoSuchObjectException e) {
-      formatter.consoleError(console, e.getMessage(),
-                             "\n" + stringifyException(e),
-                             formatter.MISSING);
-      return 1;
-    } catch (HiveException e) {
-      formatter.consoleError(console,
-                             "FAILED: Error in metadata: " + e.getMessage(),
-                             "\n" + stringifyException(e),
-                             formatter.ERROR);
-      LOG.debug(stringifyException(e));
+    } catch (Throwable e) {
+      setException(e);
+      LOG.error(stringifyException(e));
       return 1;
-    } catch (Exception e) {
-      formatter.consoleError(console, "Failed with exception " + e.getMessage(),
-                             "\n" + stringifyException(e),
-                             formatter.ERROR);
-      return (1);
     }
     assert false;
     return 0;
@@ -881,7 +851,7 @@ public class DDLTask extends Task<DDLWor
       }
       db.alterDatabase(database.getName(), database);
     } else {
-      throw new HiveException("ERROR: The database " + dbName + " does not exist.");
+      throw new HiveException(ErrorMsg.DATABASE_NOT_EXISTS, dbName);
     }
     return 0;
   }
@@ -1000,16 +970,6 @@ public class DDLTask extends Task<DDLWor
    * @return Returns 0 when execution succeeds and above 0 if it fails.
    * @throws HiveException
    */
-  /**
-   * Add a partition to a table.
-   *
-   * @param db
-   *          Database to add the partition to.
-   * @param addPartitionDesc
-   *          Add this partition.
-   * @return Returns 0 when execution succeeds and above 0 if it fails.
-   * @throws HiveException
-   */
   private int addPartition(Hive db, AddPartitionDesc addPartitionDesc) throws HiveException {
 
     Table tbl = db.getTable(addPartitionDesc.getDbName(), addPartitionDesc.getTableName());
@@ -1118,7 +1078,7 @@ public class DDLTask extends Task<DDLWor
     try {
       db.alterTable(tabName, tbl);
     } catch (InvalidOperationException e) {
-      throw new HiveException("Uable to update table");
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "Unable to alter " + tabName);
     }
 
     work.getInputs().add(new ReadEntity(tbl));
@@ -1878,10 +1838,7 @@ public class DDLTask extends Task<DDLWor
     tbl = db.getTable(tabName);
 
     if (!tbl.isPartitioned()) {
-      formatter.consoleError(console,
-                             "Table " + tabName + " is not a partitioned table",
-                             formatter.ERROR);
-      return 1;
+      throw new HiveException(ErrorMsg.TABLE_NOT_PARTITIONED, tabName);
     }
     if (showParts.getPartSpec() != null) {
       parts = db.getPartitionNames(tbl.getDbName(),
@@ -1899,20 +1856,12 @@ public class DDLTask extends Task<DDLWor
 
       formatter.showTablePartitons(outStream, parts);
 
-      ((FSDataOutputStream) outStream).close();
+      outStream.close();
       outStream = null;
-    } catch (FileNotFoundException e) {
-        formatter.logWarn(outStream, "show partitions: " + stringifyException(e),
-                          MetaDataFormatter.ERROR);
-        return 1;
-      } catch (IOException e) {
-        formatter.logWarn(outStream, "show partitions: " + stringifyException(e),
-                          MetaDataFormatter.ERROR);
-        return 1;
     } catch (Exception e) {
-      throw new HiveException(e);
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "show partitions for table " + tabName);
     } finally {
-      IOUtils.closeStream((FSDataOutputStream) outStream);
+      IOUtils.closeStream(outStream);
     }
 
     return 0;
@@ -2212,7 +2161,7 @@ public class DDLTask extends Task<DDLWor
   /**
    * Write a list of the available databases to a file.
    *
-   * @param showDatabases
+   * @param showDatabasesDesc
    *          These are the databases we're interested in.
    * @return Returns 0 when execution succeeds and above 0 if it fails.
    * @throws HiveException
@@ -2237,20 +2186,12 @@ public class DDLTask extends Task<DDLWor
       outStream = fs.create(resFile);
 
       formatter.showDatabases(outStream, databases);
-      ((FSDataOutputStream) outStream).close();
+      outStream.close();
       outStream = null;
-    } catch (FileNotFoundException e) {
-      formatter.logWarn(outStream, "show databases: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
-    } catch (IOException e) {
-      formatter.logWarn(outStream, "show databases: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
     } catch (Exception e) {
-      throw new HiveException(e.toString());
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "show databases");
     } finally {
-      IOUtils.closeStream((FSDataOutputStream) outStream);
+      IOUtils.closeStream(outStream);
     }
     return 0;
   }
@@ -2272,8 +2213,7 @@ public class DDLTask extends Task<DDLWor
     String dbName = showTbls.getDbName();
 
     if (!db.databaseExists(dbName)) {
-      throw new HiveException("ERROR: The database " + dbName + " does not exist.");
-
+      throw new HiveException(ErrorMsg.DATABASE_NOT_EXISTS, dbName);
     }
     if (showTbls.getPattern() != null) {
       LOG.info("pattern: " + showTbls.getPattern());
@@ -2292,20 +2232,12 @@ public class DDLTask extends Task<DDLWor
 
       SortedSet<String> sortedTbls = new TreeSet<String>(tbls);
       formatter.showTables(outStream, sortedTbls);
-      ((FSDataOutputStream) outStream).close();
+      outStream.close();
       outStream = null;
-    } catch (FileNotFoundException e) {
-      formatter.logWarn(outStream, "show table: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
-    } catch (IOException e) {
-      formatter.logWarn(outStream, "show table: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
     } catch (Exception e) {
-      throw new HiveException(e.toString());
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "in database" + dbName);
     } finally {
-      IOUtils.closeStream((FSDataOutputStream) outStream);
+      IOUtils.closeStream(outStream);
     }
     return 0;
   }
@@ -2337,8 +2269,7 @@ public class DDLTask extends Task<DDLWor
       ((FSDataOutputStream) outStream).close();
       outStream = null;
     } catch (IOException e) {
-      LOG.warn("show columns: " + stringifyException(e));
-      return 1;
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR);
     } finally {
       IOUtils.closeStream((FSDataOutputStream) outStream);
     }
@@ -2668,9 +2599,7 @@ public class DDLTask extends Task<DDLWor
       Database database = db.getDatabase(descDatabase.getDatabaseName());
 
       if (database == null) {
-          formatter.error(outStream,
-                          "No such database: " + descDatabase.getDatabaseName(),
-                          formatter.MISSING);
+        throw new HiveException(ErrorMsg.DATABASE_NOT_EXISTS, descDatabase.getDatabaseName());
       } else {
           Map<String, String> params = null;
           if(descDatabase.isExt()) {
@@ -2683,22 +2612,12 @@ public class DDLTask extends Task<DDLWor
                                             database.getLocationUri(),
                                             params);
       }
-      ((FSDataOutputStream) outStream).close();
+      outStream.close();
       outStream = null;
-    } catch (FileNotFoundException e) {
-      formatter.logWarn(outStream,
-                        "describe database: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
     } catch (IOException e) {
-      formatter.logWarn(outStream,
-                        "describe database: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
-    } catch (Exception e) {
-      throw new HiveException(e.toString());
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR);
     } finally {
-      IOUtils.closeStream((FSDataOutputStream) outStream);
+      IOUtils.closeStream(outStream);
     }
     return 0;
   }
@@ -2713,7 +2632,7 @@ public class DDLTask extends Task<DDLWor
    * @return Return 0 when execution succeeds and above 0 if it fails.
    */
   private int showTableStatus(Hive db, ShowTableStatusDesc showTblStatus) throws HiveException {
-    // get the tables for the desired pattenn - populate the output stream
+    // get the tables for the desired pattern - populate the output stream
     List<Table> tbls = new ArrayList<Table>();
     Map<String, String> part = showTblStatus.getPartSpec();
     Partition par = null;
@@ -2749,20 +2668,12 @@ public class DDLTask extends Task<DDLWor
 
       formatter.showTableStatus(outStream, db, conf, tbls, part, par);
 
-      ((FSDataOutputStream) outStream).close();
+      outStream.close();
       outStream = null;
-    } catch (FileNotFoundException e) {
-      formatter.logInfo(outStream, "show table status: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
-    } catch (IOException e) {
-      formatter.logInfo(outStream, "show table status: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
     } catch (Exception e) {
-      throw new HiveException(e);
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "show table status");
     } finally {
-      IOUtils.closeStream((FSDataOutputStream) outStream);
+      IOUtils.closeStream(outStream);
     }
     return 0;
   }
@@ -2835,7 +2746,6 @@ public class DDLTask extends Task<DDLWor
 
     return 0;
   }
-
   /**
    * Write the description of a table to a file.
    *
@@ -2860,36 +2770,26 @@ public class DDLTask extends Task<DDLWor
       if (tbl == null) {
         FileSystem fs = resFile.getFileSystem(conf);
         outStream = fs.create(resFile);
-        String errMsg = "Table " + tableName + " does not exist";
-        formatter.error(outStream, errMsg, formatter.MISSING);
-        ((FSDataOutputStream) outStream).close();
+        outStream.close();
         outStream = null;
-        return 0;
+        throw new HiveException(ErrorMsg.INVALID_TABLE, tableName);
       }
       if (descTbl.getPartSpec() != null) {
         part = db.getPartition(tbl, descTbl.getPartSpec(), false);
         if (part == null) {
           FileSystem fs = resFile.getFileSystem(conf);
           outStream = fs.create(resFile);
-          String errMsg = "Partition " + descTbl.getPartSpec() + " for table "
-              + tableName + " does not exist";
-          formatter.error(outStream, errMsg, formatter.MISSING);
-          ((FSDataOutputStream) outStream).close();
+          outStream.close();
           outStream = null;
-          return 0;
+          throw new HiveException(ErrorMsg.INVALID_PARTITION,
+                  StringUtils.join(descTbl.getPartSpec().keySet(), ','), tableName);
         }
         tbl = part.getTable();
       }
-    } catch (FileNotFoundException e) {
-      formatter.logInfo(outStream, "describe table: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
     } catch (IOException e) {
-      formatter.logInfo(outStream, "describe table: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, tableName);
     } finally {
-      IOUtils.closeStream((FSDataOutputStream) outStream);
+      IOUtils.closeStream(outStream);
     }
 
     try {
@@ -2916,21 +2816,13 @@ public class DDLTask extends Task<DDLWor
                               descTbl.isFormatted(), descTbl.isExt(), descTbl.isPretty());
 
       LOG.info("DDLTask: written data for " + tbl.getTableName());
-      ((FSDataOutputStream) outStream).close();
+      outStream.close();
       outStream = null;
 
-    } catch (FileNotFoundException e) {
-      formatter.logInfo(outStream, "describe table: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
     } catch (IOException e) {
-      formatter.logInfo(outStream, "describe table: " + stringifyException(e),
-                        formatter.ERROR);
-      return 1;
-    } catch (Exception e) {
-      throw new HiveException(e);
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, tableName);
     } finally {
-      IOUtils.closeStream((FSDataOutputStream) outStream);
+      IOUtils.closeStream(outStream);
     }
 
     return 0;
@@ -3009,11 +2901,8 @@ public class DDLTask extends Task<DDLWor
       if (alterTbl.getOp() != AlterTableDesc.AlterTableTypes.ALTERPROTECTMODE) {
         part = db.getPartition(tbl, alterTbl.getPartSpec(), false);
         if (part == null) {
-          formatter.consoleError(console,
-                                 "Partition : " + alterTbl.getPartSpec().toString()
-                                 + " does not exist.",
-                                 formatter.MISSING);
-          return 1;
+          throw new HiveException(ErrorMsg.INVALID_PARTITION,
+                  StringUtils.join(alterTbl.getPartSpec().keySet(), ',') + " for table " + alterTbl.getOldName());
         }
       }
       else {
@@ -3044,10 +2933,7 @@ public class DDLTask extends Task<DDLWor
           while (iterOldCols.hasNext()) {
             String oldColName = iterOldCols.next().getName();
             if (oldColName.equalsIgnoreCase(newColName)) {
-              formatter.consoleError(console,
-                                     "Column '" + newColName + "' exists",
-                                     formatter.CONFLICT);
-              return 1;
+              throw new HiveException(ErrorMsg.DUPLICATE_COLUMN_NAMES, newColName);
             }
           }
           oldCols.add(newCol);
@@ -3078,10 +2964,7 @@ public class DDLTask extends Task<DDLWor
         String oldColName = col.getName();
         if (oldColName.equalsIgnoreCase(newName)
             && !oldColName.equalsIgnoreCase(oldName)) {
-          formatter.consoleError(console,
-                                 "Column '" + newName + "' exists",
-                                 formatter.CONFLICT);
-          return 1;
+          throw new HiveException(ErrorMsg.DUPLICATE_COLUMN_NAMES, newName);
         } else if (oldColName.equalsIgnoreCase(oldName)) {
           col.setName(newName);
           if (type != null && !type.trim().equals("")) {
@@ -3108,17 +2991,11 @@ public class DDLTask extends Task<DDLWor
 
       // did not find the column
       if (!found) {
-        formatter.consoleError(console,
-                               "Column '" + oldName + "' does not exists",
-                               formatter.MISSING);
-        return 1;
+        throw new HiveException(ErrorMsg.INVALID_COLUMN, oldName);
       }
       // after column is not null, but we did not find it.
       if ((afterCol != null && !afterCol.trim().equals("")) && position < 0) {
-        formatter.consoleError(console,
-                               "Column '" + afterCol + "' does not exists",
-                               formatter.MISSING);
-        return 1;
+        throw new HiveException(ErrorMsg.INVALID_COLUMN, afterCol);
       }
 
       if (position >= 0) {
@@ -3139,11 +3016,7 @@ public class DDLTask extends Task<DDLWor
           && !tbl.getSerializationLib().equals(LazySimpleSerDe.class.getName())
           && !tbl.getSerializationLib().equals(ColumnarSerDe.class.getName())
           && !tbl.getSerializationLib().equals(DynamicSerDe.class.getName())) {
-        formatter.consoleError(console,
-                               "Replace columns is not supported for this table. "
-                               + "SerDe may be incompatible.",
-                               formatter.ERROR);
-        return 1;
+        throw new HiveException(ErrorMsg.CANNOT_REPLACE_COLUMNS, alterTbl.getOldName());
       }
       tbl.getTTable().getSd().setCols(alterTbl.getNewCols());
     } else if (alterTbl.getOp() == AlterTableDesc.AlterTableTypes.ADDPROPS) {
@@ -3242,10 +3115,7 @@ public class DDLTask extends Task<DDLWor
         URI locUri = new URI(newLocation);
         if (!locUri.isAbsolute() || locUri.getScheme() == null
             || locUri.getScheme().trim().equals("")) {
-          throw new HiveException(
-              newLocation
-                  + " is not absolute or has no scheme information. "
-                  + "Please specify a complete absolute uri with scheme information.");
+          throw new HiveException(ErrorMsg.BAD_LOCATION_VALUE, newLocation);
         }
         if (part != null) {
           part.setLocation(newLocation);
@@ -3313,34 +3183,18 @@ public class DDLTask extends Task<DDLWor
         tbl.setNumBuckets(alterTbl.getNumberBuckets());
       }
     } else {
-      formatter.consoleError(console,
-                             "Unsupported Alter commnad",
-                             formatter.ERROR);
-      return 1;
+      throw new HiveException(ErrorMsg.UNSUPPORTED_ALTER_TBL_OP, alterTbl.getOp().toString());
     }
 
     if (part == null && allPartitions == null) {
-      if (!updateModifiedParameters(tbl.getTTable().getParameters(), conf)) {
-        return 1;
-      }
-      try {
-        tbl.checkValidity();
-      } catch (HiveException e) {
-        formatter.consoleError(console,
-                               "Invalid table columns : " + e.getMessage(),
-                               formatter.ERROR);
-        return 1;
-      }
+      updateModifiedParameters(tbl.getTTable().getParameters(), conf);
+      tbl.checkValidity();
     } else if (part != null) {
-      if (!updateModifiedParameters(part.getParameters(), conf)) {
-        return 1;
-      }
+      updateModifiedParameters(part.getParameters(), conf);
     }
     else {
       for (Partition tmpPart: allPartitions) {
-        if (!updateModifiedParameters(tmpPart.getParameters(), conf)) {
-          return 1;
-        }
+        updateModifiedParameters(tmpPart.getParameters(), conf);
       }
     }
 
@@ -3354,11 +3208,8 @@ public class DDLTask extends Task<DDLWor
         db.alterPartitions(tbl.getTableName(), allPartitions);
       }
     } catch (InvalidOperationException e) {
-      console.printError("Invalid alter operation: " + e.getMessage());
       LOG.info("alter table: " + stringifyException(e));
-      return 1;
-    } catch (HiveException e) {
-      return 1;
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR);
     }
 
     // This is kind of hacky - the read entity contains the old table, whereas
@@ -3525,16 +3376,12 @@ public class DDLTask extends Task<DDLWor
    * @param user
    *          user that is doing the updating.
    */
-  private boolean updateModifiedParameters(Map<String, String> params, HiveConf conf) {
+  private boolean updateModifiedParameters(Map<String, String> params, HiveConf conf) throws HiveException {
     String user = null;
     try {
       user = conf.getUser();
     } catch (IOException e) {
-      formatter.consoleError(console,
-                             "Unable to get current user: " + e.getMessage(),
-                             stringifyException(e),
-                             formatter.ERROR);
-      return false;
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "Unable to get current user");
     }
 
     params.put("last_modified_by", user);
@@ -3562,17 +3409,21 @@ public class DDLTask extends Task<DDLWor
    * @param crtDb
    * @return Always returns 0
    * @throws HiveException
-   * @throws AlreadyExistsException
    */
   private int createDatabase(Hive db, CreateDatabaseDesc crtDb)
-      throws HiveException, AlreadyExistsException {
+      throws HiveException {
     Database database = new Database();
     database.setName(crtDb.getName());
     database.setDescription(crtDb.getComment());
     database.setLocationUri(crtDb.getLocationUri());
     database.setParameters(crtDb.getDatabaseProperties());
-
-    db.createDatabase(database, crtDb.getIfNotExists());
+    try {
+      db.createDatabase(database, crtDb.getIfNotExists());
+    }
+    catch (AlreadyExistsException ex) {
+      //it would be better if AlreadyExistsException had an errorCode field....
+      throw new HiveException(ex, ErrorMsg.DATABSAE_ALREADY_EXISTS, crtDb.getName());
+    }
     return 0;
   }
 
@@ -3582,11 +3433,15 @@ public class DDLTask extends Task<DDLWor
    * @param dropDb
    * @return Always returns 0
    * @throws HiveException
-   * @throws NoSuchObjectException
    */
   private int dropDatabase(Hive db, DropDatabaseDesc dropDb)
-      throws HiveException, NoSuchObjectException {
-    db.dropDatabase(dropDb.getDatabaseName(), true, dropDb.getIfExists(), dropDb.isCasdade());
+      throws HiveException {
+    try {
+      db.dropDatabase(dropDb.getDatabaseName(), true, dropDb.getIfExists(), dropDb.isCasdade());
+    }
+    catch (NoSuchObjectException ex) {
+      throw new HiveException(ex, ErrorMsg.DATABASE_NOT_EXISTS, dropDb.getDatabaseName());
+    }
     return 0;
   }
 
@@ -3601,7 +3456,7 @@ public class DDLTask extends Task<DDLWor
       throws HiveException {
     String dbName = switchDb.getDatabaseName();
     if (!db.databaseExists(dbName)) {
-      throw new HiveException("ERROR: The database " + dbName + " does not exist.");
+      throw new HiveException(ErrorMsg.DATABASE_NOT_EXISTS, dbName);
     }
     db.setCurrentDatabase(dbName);
 
@@ -3988,7 +3843,7 @@ public class DDLTask extends Task<DDLWor
         fs.mkdirs(location);
       }
     } catch (Exception e) {
-      throw new HiveException(e);
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR);
     }
     return 0;
   }
@@ -4023,15 +3878,11 @@ public class DDLTask extends Task<DDLWor
     return locations;
   }
 
-  private int setGenericTableAttributes(Table tbl) {
+  private int setGenericTableAttributes(Table tbl) throws HiveException {
     try {
       tbl.setOwner(conf.getUser());
     } catch (IOException e) {
-      formatter.consoleError(console,
-                             "Unable to get current user: " + e.getMessage(),
-                             stringifyException(e),
-                             formatter.ERROR);
-      return 1;
+      throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "Unable to get current user");
     }
     // set create time
     tbl.setCreateTime((int) (System.currentTimeMillis() / 1000));

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Task.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Task.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Task.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Task.java Tue Jul  9 03:41:36 2013
@@ -95,6 +95,12 @@ public abstract class Task<T extends Ser
 
   protected List<Task<? extends Serializable>> childTasks;
   protected List<Task<? extends Serializable>> parentTasks;
+  /**
+   * this can be set by the Task, to provide more info about the failure in TaskResult
+   * where the Driver can find it.  This is checked if {@link Task#execute(org.apache.hadoop.hive.ql.DriverContext)}
+   * returns non-0 code.
+   */
+  private Throwable exception;
 
   public Task() {
     isdone = false;
@@ -494,4 +500,10 @@ public abstract class Task<T extends Ser
   public List<FieldSchema> getResultSchema() {
     return null;
   }
+  Throwable getException() {
+    return exception;
+  }
+  void setException(Throwable ex) {
+    exception = ex;
+  }
 }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskResult.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskResult.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskResult.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskResult.java Tue Jul  9 03:41:36 2013
@@ -20,11 +20,13 @@ package org.apache.hadoop.hive.ql.exec;
 
 /**
  * TaskResult implementation.
+ * Note that different threads may be reading/writing this object
  **/
 
 public class TaskResult {
-  protected int exitVal;
-  protected boolean runStatus;
+  protected volatile int exitVal;
+  protected volatile boolean runStatus;
+  private volatile Throwable taskError;
 
   public TaskResult() {
     exitVal = -1;
@@ -35,11 +37,21 @@ public class TaskResult {
     this.exitVal = exitVal;
     setRunning(false);
   }
+  public void setExitVal(int exitVal, Throwable taskError) {
+    this.setExitVal(exitVal);
+    this.taskError = taskError;
+  }
 
   public int getExitVal() {
     return exitVal;
   }
 
+  /**
+   * @return may contain details of the error which caused the task to fail or null
+   */
+  public Throwable getTaskError() {
+    return taskError;
+  }
   public boolean isRunning() {
     return runStatus;
   }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskRunner.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskRunner.java?rev=1501053&r1=1501052&r2=1501053&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskRunner.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/TaskRunner.java Tue Jul  9 03:41:36 2013
@@ -66,7 +66,7 @@ public class TaskRunner extends Thread {
     } catch (Throwable t) {
       t.printStackTrace();
     }
-    result.setExitVal(exitVal);
+    result.setExitVal(exitVal, tsk.getException());
   }
 
   public static long getTaskRunnerID () {