You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mc...@apache.org on 2013/01/18 00:17:48 UTC

[5/13] Clean up ApiServer, ApiServlet and ApiDispatcher flow to handle various CloudRuntimeException and CloudException in one place, and Introduced ApiErrorCode to handle CloudStack API error code to standard Http code mapping.

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/3dabd5fb/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java
index 19091f2..92d3137 100755
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
+import org.apache.cloudstack.api.ApiErrorCode;
 import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.log4j.Logger;
@@ -128,7 +129,7 @@ public class ApiServlet extends HttpServlet {
             reqStr = auditTrailSb.toString() + " " + req.getQueryString();
             s_logger.debug("===START=== " + StringUtils.cleanString(reqStr));
         }
-        
+
         try {
             HttpSession session = req.getSession(false);
             Object[] responseTypeParam = params.get("response");
@@ -192,7 +193,7 @@ public class ApiServlet extends HttpServlet {
                             s_logger.warn("Invalid domain id entered by user");
                             auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one");
                             String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params,
-                                    responseType, null);
+                                    responseType);
                             writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
                         }
                     }
@@ -227,10 +228,10 @@ public class ApiServlet extends HttpServlet {
                             } catch (IllegalStateException ise) {
                             }
 
-                            auditTrailSb.append(" " + BaseCmd.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct");
-                            String serializedResponse = _apiServer.getSerializedApiError(BaseCmd.ACCOUNT_ERROR, ex.getMessage() != null ? ex.getMessage()
-                                    : "failed to authenticate user, check if username/password are correct", params, responseType, null);
-                            writeResponse(resp, serializedResponse, BaseCmd.ACCOUNT_ERROR, responseType);
+                            auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage() : "failed to authenticate user, check if username/password are correct");
+                            String serializedResponse = _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), ex.getMessage() != null ? ex.getMessage()
+                                    : "failed to authenticate user, check if username/password are correct", params, responseType);
+                            writeResponse(resp, serializedResponse, ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), responseType);
                             return;
                         }
                     }
@@ -257,7 +258,7 @@ public class ApiServlet extends HttpServlet {
                     } catch (IllegalStateException ise) {
                     }
                     auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
-                    String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType, null);
+                    String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
                     writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
                     return;
                 }
@@ -269,7 +270,7 @@ public class ApiServlet extends HttpServlet {
                     if (command == null) {
                         s_logger.info("missing command, ignoring request...");
                         auditTrailSb.append(" " + HttpServletResponse.SC_BAD_REQUEST + " " + "no command specified");
-                        String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType, null);
+                        String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "no command specified", params, responseType);
                         writeResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST, responseType);
                         return;
                     }
@@ -283,7 +284,7 @@ public class ApiServlet extends HttpServlet {
                     }
 
                     auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials");
-                    String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType, null);
+                    String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials", params, responseType);
                     writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
                     return;
                 }
@@ -298,7 +299,7 @@ public class ApiServlet extends HttpServlet {
                  * params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj }); } else {
                  * params.put(BaseCmd.Properties.USER_ID.getName(), new String[] { userId });
                  * params.put(BaseCmd.Properties.ACCOUNT_OBJ.getName(), new Object[] { accountObj }); } }
-                 * 
+                 *
                  * // update user context info here so that we can take information if the request is authenticated // via api
                  * key mechanism updateUserContext(params, session != null ? session.getId() : null);
                  */
@@ -307,15 +308,9 @@ public class ApiServlet extends HttpServlet {
                         "(userId=" + UserContext.current().getCallerUserId() + " accountId=" + UserContext.current().getCaller().getId() + " sessionId=" + (session != null ? session.getId() : null)
                                 + ")");
 
-                try {
-                    String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
-                    writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
-                } catch (ServerApiException se) {
-                    String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType, null);
-                    resp.setHeader("X-Description", se.getDescription());
-                    writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
-                    auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
-                }
+                String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
+                writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK, responseType);
+
             } else {
                 if (session != null) {
                     try {
@@ -325,21 +320,18 @@ public class ApiServlet extends HttpServlet {
                 }
 
                 auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "unable to verify user credentials and/or request signature");
-                String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params, responseType, null);
+                String serializedResponse = _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "unable to verify user credentials and/or request signature", params, responseType);
                 writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED, responseType);
 
             }
+        } catch (ServerApiException se) {
+            String serializedResponseText = _apiServer.getSerializedApiError(se, params, responseType);
+            resp.setHeader("X-Description", se.getDescription());
+            writeResponse(resp, serializedResponseText, se.getErrorCode().getHttpCode(), responseType);
+            auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
         } catch (Exception ex) {
-            if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) {
-                ServerApiException se = (ServerApiException) ex;
-                String serializedResponseText = _apiServer.getSerializedApiError(se.getErrorCode(), se.getDescription(), params, responseType, null);
-                resp.setHeader("X-Description", se.getDescription());
-                writeResponse(resp, serializedResponseText, se.getErrorCode(), responseType);
-                auditTrailSb.append(" " + se.getErrorCode() + " " + se.getDescription());
-            } else {
-                s_logger.error("unknown exception writing api response", ex);
-                auditTrailSb.append(" unknown exception writing api response");
-            }
+            s_logger.error("unknown exception writing api response", ex);
+            auditTrailSb.append(" unknown exception writing api response");
         } finally {
             s_accessLogger.info(auditTrailSb.toString());
             if (s_logger.isDebugEnabled()) {
@@ -354,9 +346,9 @@ public class ApiServlet extends HttpServlet {
      * private void updateUserContext(Map<String, Object[]> requestParameters, String sessionId) { String userIdStr =
      * (String)(requestParameters.get(BaseCmd.Properties.USER_ID.getName())[0]); Account accountObj =
      * (Account)(requestParameters.get(BaseCmd.Properties.ACCOUNT_OBJ.getName())[0]);
-     * 
+     *
      * Long userId = null; Long accountId = null; if(userIdStr != null) userId = Long.parseLong(userIdStr);
-     * 
+     *
      * if(accountObj != null) accountId = accountObj.getId(); UserContext.updateContext(userId, accountId, sessionId); }
      */
 
@@ -386,7 +378,7 @@ public class ApiServlet extends HttpServlet {
     private String getLoginSuccessResponse(HttpSession session, String responseType) {
         StringBuffer sb = new StringBuffer();
         int inactiveInterval = session.getMaxInactiveInterval();
-        
+
         String user_UUID = (String)session.getAttribute("user_UUID");
         session.removeAttribute("user_UUID");
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/3dabd5fb/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
index fdbbbe4..cdf83ae 100644
--- a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
+++ b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
@@ -97,9 +97,9 @@ public class AddTrafficMonitorCmd extends BaseCmd {
 			response.setResponseName(getCommandName());
 			this.setResponseObject(response);
 		} catch (InvalidParameterValueException ipve) {
-			throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage());
+			throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage());
 		} catch (CloudRuntimeException cre) {
-			throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage());
+			throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage());
 		}
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/3dabd5fb/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
index 4c7d3a7..d39323a 100644
--- a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
+++ b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
@@ -20,6 +20,7 @@ import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.log4j.Logger;
 
 import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
 import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.Parameter;
@@ -33,25 +34,25 @@ import com.cloud.utils.component.ComponentLocator;
 
 @APICommand(name = "deleteTrafficMonitor", description="Deletes an traffic monitor host.", responseObject = SuccessResponse.class)
 public class DeleteTrafficMonitorCmd extends BaseCmd {
-	public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName());	
-	private static final String s_name = "deletetrafficmonitorresponse";	
-	
+	public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName());
+	private static final String s_name = "deletetrafficmonitorresponse";
+
 	/////////////////////////////////////////////////////
     //////////////// API parameters /////////////////////
     /////////////////////////////////////////////////////
-	
+
 	@Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class,
             required = true, description="Id of the Traffic Monitor Host.")
 	private Long id;
-	
+
 	///////////////////////////////////////////////////
 	/////////////////// Accessors ///////////////////////
 	/////////////////////////////////////////////////////
-	 
+
 	public Long getId() {
 		return id;
 	}
-	 
+
 	/////////////////////////////////////////////////////
 	/////////////// API Implementation///////////////////
 	/////////////////////////////////////////////////////
@@ -60,12 +61,12 @@ public class DeleteTrafficMonitorCmd extends BaseCmd {
 	public String getCommandName() {
 		return s_name;
 	}
-	
+
 	@Override
     public long getEntityOwnerId() {
         return Account.ACCOUNT_ID_SYSTEM;
     }
-	 
+
 	@Override
     public void execute(){
 		try {
@@ -77,10 +78,10 @@ public class DeleteTrafficMonitorCmd extends BaseCmd {
 			response.setResponseName(getCommandName());
 			this.setResponseObject(response);
 			} else {
-				throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic monitor.");
+				throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete traffic monitor.");
 			}
 		} catch (InvalidParameterValueException e) {
-			throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete traffic monitor.");
+			throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Failed to delete traffic monitor.");
 		}
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/3dabd5fb/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java
index aa3c082..4206cf8 100644
--- a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java
+++ b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java
@@ -85,7 +85,7 @@ public class GenerateUsageRecordsCmd extends BaseCmd {
             SuccessResponse response = new SuccessResponse(getCommandName());
             this.setResponseObject(response);
         } else {
-            throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to generate usage records");
+            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to generate usage records");
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/3dabd5fb/server/src/com/cloud/async/AsyncJobManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/async/AsyncJobManagerImpl.java b/server/src/com/cloud/async/AsyncJobManagerImpl.java
index 7bf5c5a..05d305e 100644
--- a/server/src/com/cloud/async/AsyncJobManagerImpl.java
+++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java
@@ -41,6 +41,8 @@ import org.apache.log4j.NDC;
 import com.cloud.api.ApiDispatcher;
 import com.cloud.api.ApiGsonHelper;
 import com.cloud.api.ApiSerializerHelper;
+
+import org.apache.cloudstack.api.ApiErrorCode;
 import org.apache.cloudstack.api.BaseAsyncCmd;
 import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ServerApiException;
@@ -78,13 +80,13 @@ import com.google.gson.reflect.TypeToken;
 public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener {
     public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName());
 	private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; 	// 3 seconds
-    
+
     private static final int MAX_ONETIME_SCHEDULE_SIZE = 50;
     private static final int HEARTBEAT_INTERVAL = 2000;
     private static final int GC_INTERVAL = 10000;				// 10 seconds
-    
+
     private String _name;
-    
+
     private AsyncJobExecutorContext _context;
     private SyncQueueManager _queueMgr;
     private ClusterManager _clusterMgr;
@@ -93,7 +95,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     private AsyncJobDao _jobDao;
     private long _jobExpireSeconds = 86400;                 // 1 day
     private long _jobCancelThresholdSeconds = 3600;         // 1 hour (for cancelling the jobs blocking other jobs)
-    
+
     private ApiDispatcher _dispatcher;
 
     private final ScheduledExecutorService _heartbeatScheduler =
@@ -104,7 +106,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     public AsyncJobExecutorContext getExecutorContext() {
         return _context;
     }
-    
+
     @Override
     public AsyncJobVO getAsyncJob(long jobId) {
         return _jobDao.findById(jobId);
@@ -119,7 +121,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     public List<AsyncJobVO> findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId) {
     	return _jobDao.findInstancePendingAsyncJobs(instanceType, accountId);
     }
-    
+
     @Override
 	public long submitAsyncJob(AsyncJobVO job) {
     	return submitAsyncJob(job, false);
@@ -155,7 +157,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
             s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus +
     			", resultCode: " + resultCode + ", result: " + resultObject);
         }
-    	
+
     	Transaction txt = Transaction.currentTxn();
     	try {
     		txt.start();
@@ -165,7 +167,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
                     s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus +
     	    			", resultCode: " + resultCode + ", result: " + resultObject);
                 }
-    			
+
     			txt.rollback();
     			return;
     		}
@@ -197,7 +199,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
             s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus +
     			", result: " + resultObject);
         }
-    	
+
     	Transaction txt = Transaction.currentTxn();
     	try {
     		txt.start();
@@ -206,11 +208,11 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     	    	if(s_logger.isDebugEnabled()) {
                     s_logger.debug("job-" + jobId + " no longer exists, we just log progress info here. progress status: " + processStatus);
                 }
-    			
+
     			txt.rollback();
     			return;
     		}
-    		
+
     		job.setProcessStatus(processStatus);
     		if(resultObject != null) {
                 job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject));
@@ -258,7 +260,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
         if (job.getSyncSource() != null) {
             return;
         }
-    	
+
         if(s_logger.isDebugEnabled()) {
             s_logger.debug("Sync job-" + job.getId() + " execution on object " + syncObjType + "." + syncObjId);
         }
@@ -287,7 +289,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
 		    throw new AsyncCommandQueued(queue, "job-" + job.getId() + " queued");
 		}
     }
-    
+
     @Override
     public AsyncJob queryAsyncJobResult(QueryAsyncJobResultCmd cmd) {
         Account caller = UserContext.current().getCaller();
@@ -296,10 +298,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
         if (job == null) {
             throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId());
         }
-       
+
         User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId());
         Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId());
-        
+
         //check permissions
         if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
             //regular user can see only jobs he owns
@@ -309,7 +311,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
         } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
             _accountMgr.checkAccess(caller, null, true, jobOwner);
         }
-        
+
         //poll the job
         queryAsyncJobResult(cmd.getId());
         return _jobDao.findById(cmd.getId());
@@ -320,10 +322,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     	if(s_logger.isTraceEnabled()) {
             s_logger.trace("Query async-job status, job-" + jobId);
         }
-    	
+
     	Transaction txt = Transaction.currentTxn();
     	AsyncJobResult jobResult = new AsyncJobResult(jobId);
-    	
+
     	try {
     		txt.start();
     		AsyncJobVO job = _jobDao.findById(jobId);
@@ -334,10 +336,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     			jobResult.setResult(job.getResult());
     			jobResult.setResultCode(job.getResultCode());
     			jobResult.setUuid(job.getUuid());
-    			
+
     			if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED ||
     				job.getStatus() == AsyncJobResult.STATUS_FAILED) {
-    				
+
     		    	if(s_logger.isDebugEnabled()) {
                         s_logger.debug("Async job-" + jobId + " completed");
                     }
@@ -349,23 +351,23 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     	    	if(s_logger.isDebugEnabled()) {
                     s_logger.debug("Async job-" + jobId + " does not exist, invalid job id?");
                 }
-    			
+
     			jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED);
     			jobResult.setResult("job-" + jobId + " does not exist");
     		}
     		txt.commit();
     	} catch(Exception e) {
     		s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e);
-    		
+
 			jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED);
 			jobResult.setResult("Exception: " + e.toString());
     		txt.rollback();
     	}
-    	
+
     	if(s_logger.isTraceEnabled()) {
             s_logger.trace("Job status: " + jobResult.toString());
         }
-    	
+
     	return jobResult;
     }
 
@@ -388,66 +390,66 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
             public void run() {
                 try {
                     long jobId = 0;
-                    
+
                     try {
                     	JmxUtil.registerMBean("AsyncJobManager", "Active Job " + job.getId(), new AsyncJobMBeanImpl(job));
                     } catch(Exception e) {
                     	s_logger.warn("Unable to register active job " + job.getId() + " to JMX monitoring due to exception " + ExceptionUtil.toString(e));
                     }
-    
+
                     BaseAsyncCmd cmdObj = null;
                     Transaction txn = Transaction.open(Transaction.CLOUD_DB);
                     try {
                         jobId = job.getId();
                         NDC.push("job-" + jobId);
-    
+
                         if(s_logger.isDebugEnabled()) {
                             s_logger.debug("Executing " + job.getCmd() + " for job-" + jobId);
                         }
-    
+
                         Class<?> cmdClass = Class.forName(job.getCmd());
                         cmdObj = (BaseAsyncCmd)cmdClass.newInstance();
                         cmdObj.setJob(job);
-    
+
                         Type mapType = new TypeToken<Map<String, String>>() {}.getType();
                         Gson gson = ApiGsonHelper.getBuilder().create();
                         Map<String, String> params = gson.fromJson(job.getCmdInfo(), mapType);
-    
+
                         // whenever we deserialize, the UserContext needs to be updated
                         String userIdStr = params.get("ctxUserId");
                         String acctIdStr = params.get("ctxAccountId");
                         Long userId = null;
                         Account accountObject = null;
-    
+
                         if (userIdStr != null) {
                             userId = Long.parseLong(userIdStr);
                         }
-    
+
                         if (acctIdStr != null) {
                             accountObject = _accountDao.findById(Long.parseLong(acctIdStr));
                         }
-    
+
                         UserContext.registerContext(userId, accountObject, null, false);
                         try {
                             // dispatch could ultimately queue the job
                             _dispatcher.dispatch(cmdObj, params);
-        
+
                             // serialize this to the async job table
                             completeAsyncJob(jobId, AsyncJobResult.STATUS_SUCCEEDED, 0, cmdObj.getResponseObject());
                         } finally {
                             UserContext.unregisterContext();
                         }
-    
+
                         // commands might need to be queued as part of synchronization here, so they just have to be re-dispatched from the queue mechanism...
                         if (job.getSyncSource() != null) {
                             _queueMgr.purgeItem(job.getSyncSource().getId());
                             checkQueue(job.getSyncSource().getQueueId());
                         }
-    
+
                         if (s_logger.isDebugEnabled()) {
                             s_logger.debug("Done executing " + job.getCmd() + " for job-" + jobId);
                         }
-                        
+
                     } catch(Throwable e) {
                         if (e instanceof AsyncCommandQueued) {
                             if (s_logger.isDebugEnabled()) {
@@ -456,25 +458,25 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
                             checkQueue(((AsyncCommandQueued)e).getQueue().getId());
                         } else {
                             String errorMsg = null;
-                            int errorCode = BaseCmd.INTERNAL_ERROR;
+                            int errorCode = ApiErrorCode.INTERNAL_ERROR.getHttpCode();
                             if (!(e instanceof ServerApiException)) {
                                 s_logger.error("Unexpected exception while executing " + job.getCmd(), e);
                                 errorMsg = e.getMessage();
                             } else {
                                 ServerApiException sApiEx = (ServerApiException)e;
                                 errorMsg = sApiEx.getDescription();
-                                errorCode = sApiEx.getErrorCode();
+                                errorCode = sApiEx.getErrorCode().getHttpCode();
                             }
-    
+
                             ExceptionResponse response = new ExceptionResponse();
                             response.setErrorCode(errorCode);
                             response.setErrorText(errorMsg);
                             response.setResponseName((cmdObj == null) ? "unknowncommandresponse" : cmdObj.getCommandName());
-    
-                            // FIXME:  setting resultCode to BaseCmd.INTERNAL_ERROR is not right, usually executors have their exception handling
+
+                            // FIXME:  setting resultCode to ApiErrorCode.INTERNAL_ERROR is not right, usually executors have their exception handling
                             //         and we need to preserve that as much as possible here
-                            completeAsyncJob(jobId, AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, response);
-    
+                            completeAsyncJob(jobId, AsyncJobResult.STATUS_FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), response);
+
                             // need to clean up any queue that happened as part of the dispatching and move on to the next item in the queue
                             try {
                                 if (job.getSyncSource() != null) {
@@ -486,13 +488,13 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
                             }
                         }
                     } finally {
-                    	
+
                         try {
                         	JmxUtil.unregisterMBean("AsyncJobManager", "Active Job " + job.getId());
                         } catch(Exception e) {
                         	s_logger.warn("Unable to unregister active job " + job.getId() + " from JMX monitoring");
                         }
-                    	
+
                         StackMaid.current().exitCleanup();
                         txn.close();
                         NDC.pop();
@@ -516,17 +518,17 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
 
             job.setFromPreviousSession(fromPreviousSession);
             job.setSyncSource(item);
-            
+
             job.setCompleteMsid(getMsid());
             _jobDao.update(job.getId(), job);
-            
+
             try {
             	scheduleExecution(job);
 			} catch(RejectedExecutionException e) {
 				s_logger.warn("Execution for job-" + job.getId() + " is rejected, return it to the queue for next turn");
 				_queueMgr.returnItem(item.getId());
 			}
-            
+
         } else {
             if(s_logger.isDebugEnabled()) {
                 s_logger.debug("Unable to find related job for queue item: " + item.toString());
@@ -544,12 +546,12 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
 					+ executor.getSyncSource().getContentType() + "-"
 					+ executor.getSyncSource().getContentId());
             }
-    		
+
 			_queueMgr.purgeItem(executor.getSyncSource().getId());
 			checkQueue(executor.getSyncSource().getQueueId());
     	}
     }
-    
+
     private void checkQueue(long queueId) {
     	while(true) {
     		try {
@@ -558,7 +560,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
 		    		if(s_logger.isDebugEnabled()) {
                         s_logger.debug("Executing sync queue item: " + item.toString());
                     }
-		    		
+
 		    		executeQueueItem(item, false);
 		    	} else {
 		    		break;
@@ -569,7 +571,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     		}
     	}
     }
-    
+
 	private Runnable getHeartbeatTask() {
 		return new Runnable() {
 			@Override
@@ -592,7 +594,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
 			}
 		};
 	}
-	
+
 	@DB
 	private Runnable getGCTask() {
 		return new Runnable() {
@@ -611,7 +613,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
                     scanLock.releaseRef();
                 }
             }
-            
+
             public void reallyRun() {
                 try {
                     s_logger.trace("Begin cleanup expired async-jobs");
@@ -649,10 +651,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
                 }
             }
 
-           
+
         };
     }
-    
+
     @DB
     protected void expungeAsyncJob(AsyncJobVO job) {
         Transaction txn = Transaction.currentTxn();
@@ -667,10 +669,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
         if(_clusterMgr != null) {
             return _clusterMgr.getManagementNodeId();
         }
-		
+
 		return MacAddress.getMacAddress().toLong();
 	}
-	
+
 	private void cleanupPendingJobs(List<SyncQueueItemVO> l) {
 		if(l != null && l.size() > 0) {
 			for(SyncQueueItemVO item: l) {
@@ -701,7 +703,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
         if (configDao == null) {
             throw new ConfigurationException("Unable to get the configuration dao.");
         }
-        
+
         int expireMinutes = NumbersUtil.parseInt(
                 configDao.getValue(Config.JobExpireMinutes.key()), 24*60);
         _jobExpireSeconds = (long)expireMinutes*60;
@@ -719,48 +721,48 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
 			throw new ConfigurationException("Unable to get "
 					+ AsyncJobDao.class.getName());
 		}
-		
+
 		_context = 	locator.getManager(AsyncJobExecutorContext.class);
 		if (_context == null) {
 			throw new ConfigurationException("Unable to get "
 					+ AsyncJobExecutorContext.class.getName());
 		}
-		
+
 		_queueMgr = locator.getManager(SyncQueueManager.class);
 		if(_queueMgr == null) {
 			throw new ConfigurationException("Unable to get "
 					+ SyncQueueManager.class.getName());
 		}
-		
+
 		_clusterMgr = locator.getManager(ClusterManager.class);
-		
+
 		_accountMgr = locator.getManager(AccountManager.class);
 
 		_dispatcher = ApiDispatcher.getInstance();
-		
+
 
 		try {
 	        final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties");
 	        final Properties dbProps = new Properties();
 	        dbProps.load(new FileInputStream(dbPropsFile));
-	        
+
             final int cloudMaxActive = Integer.parseInt(dbProps.getProperty("db.cloud.maxActive"));
-            
+
             int poolSize = (cloudMaxActive * 2) / 3;
-            
+
             s_logger.info("Start AsyncJobManager thread pool in size " + poolSize);
             _executor = Executors.newFixedThreadPool(poolSize, new NamedThreadFactory("Job-Executor"));
 		} catch (final Exception e) {
 			throw new ConfigurationException("Unable to load db.properties to configure AsyncJobManagerImpl");
 		}
-		
+
 		return true;
     }
-    
+
     @Override
 	public void onManagementNodeJoined(List<ManagementServerHostVO> nodeList, long selfNodeId) {
     }
-    
+
     @Override
     public void onManagementNodeLeft(List<ManagementServerHostVO> nodeList, long selfNodeId) {
         for(ManagementServerHostVO msHost : nodeList) {
@@ -769,7 +771,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
                 txn.start();
                 List<SyncQueueItemVO> items = _queueMgr.getActiveQueueItems(msHost.getId(), true);
                 cleanupPendingJobs(items);
-                _jobDao.resetJobProcess(msHost.getId(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart"));
+                _jobDao.resetJobProcess(msHost.getId(), ApiErrorCode.INTERNAL_ERROR.getHttpCode(), getSerializedErrorMessage("job cancelled because of management server restart"));
                 txn.commit();
             } catch(Throwable e) {
                 s_logger.warn("Unexpected exception ", e);
@@ -779,7 +781,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
             }
         }
     }
-    
+
     @Override
 	public void onManagementNodeIsolated() {
 	}
@@ -789,7 +791,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
         try {
             List<SyncQueueItemVO> l = _queueMgr.getActiveQueueItems(getMsid(), false);
             cleanupPendingJobs(l);
-            _jobDao.resetJobProcess(getMsid(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart"));
+            _jobDao.resetJobProcess(getMsid(), ApiErrorCode.INTERNAL_ERROR.getHttpCode(), getSerializedErrorMessage("job cancelled because of management server restart"));
         } catch(Throwable e) {
             s_logger.error("Unexpected exception " + e.getMessage(), e);
         }
@@ -801,14 +803,14 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
 
         return true;
     }
-    
+
     private static ExceptionResponse getResetResultResponse(String errorMessage) {
 		ExceptionResponse resultObject = new ExceptionResponse();
-		resultObject.setErrorCode(BaseCmd.INTERNAL_ERROR);
+		resultObject.setErrorCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode());
 		resultObject.setErrorText(errorMessage);
     	return resultObject;
     }
-    
+
     private static String getSerializedErrorMessage(String errorMessage) {
         return ApiSerializerHelper.toSerializedStringOld(getResetResultResponse(errorMessage));
     }
@@ -819,7 +821,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe
     	_executor.shutdown();
         return true;
     }
-    
+
     @Override
     public String getName() {
     	return _name;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/3dabd5fb/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java b/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java
index 303e0d6..1a09699 100755
--- a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java
+++ b/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java
@@ -37,15 +37,12 @@ public class CSExceptionErrorCode {
         try {
             ExceptionErrorCodeMap = new HashMap<String, Integer>();
             ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250);
-            ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExceptionUtil", 4255);
             ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260);
             ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265);
-            ExceptionErrorCodeMap.put("com.cloud.utils.exception.RuntimeCloudException", 4270);
             ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275);
             ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280);
             ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285);
             ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290);
-            ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4295);
             ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300);
             ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305);
             ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310);
@@ -66,35 +63,6 @@ public class CSExceptionErrorCode {
             ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385);
             ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390);
             ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395);
-
-            ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4400);
-            ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4405);
-            ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4410);
-            ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4415);
-            ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4420);
-            ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4425);
-            ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4430);
-            ExceptionErrorCodeMap.put("com.cloud.exception.ConnectionException", 4435);
-            ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4440);
-            ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveryException", 4445);
-            ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4450);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4455);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4460);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4465);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4470);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4475);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapcityException", 4480);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4485);
-            ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4490);
-            ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4495);
-            ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4500);
-            ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4505);
-            ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4510);
-            ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4515);
-            ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4520);
-            ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4525);
-            ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4530);
-            ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4535);
             ExceptionErrorCodeMap.put("com.cloud.async.AsyncCommandQueued", 4540);
 
             // Have a special error code for ServerApiException when it is