cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From edi...@apache.org
Subject [16/44] Revert "Merge remote-tracking branch 'origin/javelin' into javelin"
Date Tue, 15 Jan 2013 02:04:54 GMT
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/ApiDispatcher.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java
index a0ef6e2..0df37f1 100755
--- a/server/src/com/cloud/api/ApiDispatcher.java
+++ b/server/src/com/cloud/api/ApiDispatcher.java
@@ -24,92 +24,82 @@ import java.text.ParseException;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Date;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.StringTokenizer;
 import java.util.regex.Matcher;
 
-import com.cloud.dao.EntityManager;
-import com.cloud.utils.ReflectUtil;
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.InfrastructureEntity;
-import org.apache.cloudstack.acl.Role;
-import org.apache.cloudstack.api.*;
+import org.apache.cloudstack.api.ACL;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseAsyncCmd;
+import org.apache.cloudstack.api.BaseAsyncCreateCmd;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.BaseCmd.CommandType;
+import org.apache.cloudstack.api.BaseListCmd;
+import org.apache.cloudstack.api.EntityReference;
+import org.apache.cloudstack.api.InternalIdentity;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.PlugService;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.Validate;
+import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
-import org.apache.cloudstack.api.BaseCmd.CommandType;
-import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
 import com.cloud.async.AsyncCommandQueued;
 import com.cloud.async.AsyncJobManager;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.dao.EntityManager;
 import com.cloud.exception.AccountLimitException;
 import com.cloud.exception.InsufficientCapacityException;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.exception.PermissionDeniedException;
 import com.cloud.exception.ResourceAllocationException;
 import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.network.dao.NetworkDao;
-import com.cloud.server.ManagementServer;
-import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.user.UserContext;
 import com.cloud.utils.DateUtil;
-import com.cloud.utils.NumbersUtil;
-import com.cloud.utils.component.ComponentLocator;
-import com.cloud.utils.component.Inject;
-import com.cloud.utils.component.PluggableService;
-import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.ReflectUtil;
+import com.cloud.utils.component.ComponentContext;
 import com.cloud.utils.exception.CSExceptionErrorCode;
 import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.uuididentity.dao.IdentityDao;
 
-// ApiDispatcher: A class that dispatches API commands to the appropriate manager for execution.
+@Component
 public class ApiDispatcher {
     private static final Logger s_logger = Logger.getLogger(ApiDispatcher.class.getName());
 
-    ComponentLocator _locator;
     Long _createSnapshotQueueSizeLimit;
-    @Inject private AsyncJobManager _asyncMgr = null;
-    @Inject private AccountManager _accountMgr = null;
+    @Inject AsyncJobManager _asyncMgr = null;
+    @Inject AccountManager _accountMgr = null;
     @Inject EntityManager _entityMgr = null;
-    @Inject IdentityDao _identityDao = null;
 
-    Map<String, Class<? extends GenericDao>> _daoNameMap = new HashMap<String, Class<? extends GenericDao>>();
-    // singleton class
-    private static ApiDispatcher s_instance = ApiDispatcher.getInstance();
+    private static ApiDispatcher s_instance;
 
     public static ApiDispatcher getInstance() {
-        if (s_instance == null) {
-            s_instance = ComponentLocator.inject(ApiDispatcher.class);
-        }
         return s_instance;
     }
 
-    protected ApiDispatcher() {
-        super();
-        _locator = ComponentLocator.getLocator(ManagementServer.Name);
-        ConfigurationDao configDao = _locator.getDao(ConfigurationDao.class);
-        Map<String, String> configs = configDao.getConfiguration();
-        String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key());
-        if (strSnapshotLimit != null) {
-            Long snapshotLimit = NumbersUtil.parseLong(strSnapshotLimit, 1L);
-            if (snapshotLimit <= 0) {
-                s_logger.debug("Global config parameter " + Config.ConcurrentSnapshotsThresholdPerHost.toString()
-                        + " is less or equal 0; defaulting to unlimited");
-            } else {
-                _createSnapshotQueueSizeLimit = snapshotLimit;
-            }
-        }
-        _daoNameMap.put("com.cloud.network.Network", NetworkDao.class);
-        _daoNameMap.put("com.cloud.template.VirtualMachineTemplate", VMTemplateDao.class);
+    public ApiDispatcher() {
+    }
+    
+    @PostConstruct
+    void init() {
+    	s_instance = this;
+    }
+
+    public void setCreateSnapshotQueueSizeLimit(Long snapshotLimit) {
+        _createSnapshotQueueSizeLimit = snapshotLimit;
     }
 
     public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map<String, String> params) {
-    	processParameters(cmd, params);
+        processParameters(cmd, params);
 
         try {
             UserContext ctx = UserContext.current();
@@ -206,113 +196,113 @@ public class ApiDispatcher {
 
         } catch (Throwable t) {
             if (t instanceof InvalidParameterValueException) {
-            	// earlier, we'd log the db id as part of the log message, but now since we've pushed
-            	// the id into a IdentityProxy object, we would need to dump that object alongwith the
-            	// message.
-            	InvalidParameterValueException ref = (InvalidParameterValueException) t;
-            	ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
+                // earlier, we'd log the db id as part of the log message, but now since we've pushed
+                // the id into a IdentityProxy object, we would need to dump that object alongwith the
+                // message.
+                InvalidParameterValueException ref = (InvalidParameterValueException) t;
+                ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
                 // copy over the IdentityProxy information as well and throw the serverapiexception.
                 ArrayList<String> idList = ref.getIdProxyList();
                 if (idList != null) {
-                	// Iterate through entire arraylist and copy over each proxy id.
-                	for (int i = 0 ; i < idList.size(); i++) {
-                		ex.addProxyObject(idList.get(i));
-                		s_logger.info(t.getMessage() + " uuid: " + idList.get(i));
-                	}
+                    // Iterate through entire arraylist and copy over each proxy id.
+                    for (int i = 0 ; i < idList.size(); i++) {
+                        ex.addProxyObject(idList.get(i));
+                        s_logger.info(t.getMessage() + " uuid: " + idList.get(i));
+                    }
                 } else {
-                	s_logger.info(t.getMessage());
+                    s_logger.info(t.getMessage());
                 }
                 // Also copy over the cserror code.
-    			ex.setCSErrorCode(ref.getCSErrorCode());
+                ex.setCSErrorCode(ref.getCSErrorCode());
                 throw ex;
             } else if(t instanceof IllegalArgumentException) {            	
-            	throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
+                throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage());
             } else if (t instanceof PermissionDeniedException) {            	
-            	PermissionDeniedException ref = (PermissionDeniedException)t;
-            	ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage());
+                PermissionDeniedException ref = (PermissionDeniedException)t;
+                ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage());
                 // copy over the IdentityProxy information as well and throw the serverapiexception.
-            	ArrayList<String> idList = ref.getIdProxyList();
+                ArrayList<String> idList = ref.getIdProxyList();
                 if (idList != null) {
-                	// Iterate through entire arraylist and copy over each proxy id.
-                	for (int i = 0 ; i < idList.size(); i++) {
-                 		ex.addProxyObject(idList.get(i));
-                 		s_logger.info("PermissionDenied: " + t.getMessage() + "uuid: " + idList.get(i));
-                 	}
-                 } else {
-                	 s_logger.info("PermissionDenied: " + t.getMessage());
-                 }
+                    // Iterate through entire arraylist and copy over each proxy id.
+                    for (int i = 0 ; i < idList.size(); i++) {
+                        ex.addProxyObject(idList.get(i));
+                        s_logger.info("PermissionDenied: " + t.getMessage() + "uuid: " + idList.get(i));
+                    }
+                } else {
+                    s_logger.info("PermissionDenied: " + t.getMessage());
+                }
                 // Also copy over the cserror code.
-    			ex.setCSErrorCode(ref.getCSErrorCode());
-    			throw ex;
+                ex.setCSErrorCode(ref.getCSErrorCode());
+                throw ex;
             } else if (t instanceof AccountLimitException) {            	
-            	AccountLimitException ref = (AccountLimitException)t;
-            	ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage());
+                AccountLimitException ref = (AccountLimitException)t;
+                ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage());
                 // copy over the IdentityProxy information as well and throw the serverapiexception.
-            	ArrayList<String> idList = ref.getIdProxyList();
+                ArrayList<String> idList = ref.getIdProxyList();
                 if (idList != null) {
-                	// Iterate through entire arraylist and copy over each proxy id.
-                	for (int i = 0 ; i < idList.size(); i++) {
-                 		ex.addProxyObject(idList.get(i));
-                 		s_logger.info(t.getMessage() + "uuid: " + idList.get(i));
-                	}
+                    // Iterate through entire arraylist and copy over each proxy id.
+                    for (int i = 0 ; i < idList.size(); i++) {
+                        ex.addProxyObject(idList.get(i));
+                        s_logger.info(t.getMessage() + "uuid: " + idList.get(i));
+                    }
                 } else {
-                	s_logger.info(t.getMessage());
+                    s_logger.info(t.getMessage());
                 }
                 // Also copy over the cserror code.
-    			ex.setCSErrorCode(ref.getCSErrorCode());
+                ex.setCSErrorCode(ref.getCSErrorCode());
                 throw ex;
             } else if (t instanceof InsufficientCapacityException) {            	
-            	InsufficientCapacityException ref = (InsufficientCapacityException)t;
-            	ServerApiException ex = new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage());
+                InsufficientCapacityException ref = (InsufficientCapacityException)t;
+                ServerApiException ex = new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage());
                 // copy over the IdentityProxy information as well and throw the serverapiexception.
-            	ArrayList<String> idList = ref.getIdProxyList();
+                ArrayList<String> idList = ref.getIdProxyList();
                 if (idList != null) {
-                	// Iterate through entire arraylist and copy over each proxy id.
-                	for (int i = 0 ; i < idList.size(); i++) {
-                 		ex.addProxyObject(idList.get(i));
-                 		s_logger.info(t.getMessage() + "uuid: " + idList.get(i));
-                	}
+                    // Iterate through entire arraylist and copy over each proxy id.
+                    for (int i = 0 ; i < idList.size(); i++) {
+                        ex.addProxyObject(idList.get(i));
+                        s_logger.info(t.getMessage() + "uuid: " + idList.get(i));
+                    }
                 } else {
-                	s_logger.info(t.getMessage());
+                    s_logger.info(t.getMessage());
                 }
                 // Also copy over the cserror code
-    			ex.setCSErrorCode(ref.getCSErrorCode());
+                ex.setCSErrorCode(ref.getCSErrorCode());
                 throw ex;
             } else if (t instanceof ResourceAllocationException) {
-            	ResourceAllocationException ref = (ResourceAllocationException)t;
+                ResourceAllocationException ref = (ResourceAllocationException)t;
                 ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage());
                 // copy over the IdentityProxy information as well and throw the serverapiexception.
                 ArrayList<String> idList = ref.getIdProxyList();
                 if (idList != null) {
-                	// Iterate through entire arraylist and copy over each proxy id.
-                	for (int i = 0 ; i < idList.size(); i++) {
-                 		String id = idList.get(i);
-                 		ex.addProxyObject(id);
-                 		s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id);
-                	}
+                    // Iterate through entire arraylist and copy over each proxy id.
+                    for (int i = 0 ; i < idList.size(); i++) {
+                        String id = idList.get(i);
+                        ex.addProxyObject(id);
+                        s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id);
+                    }
                 } else {
-                	s_logger.warn("Exception: ", t);
+                    s_logger.warn("Exception: ", t);
                 }
                 // Also copy over the cserror code.
-    			ex.setCSErrorCode(ref.getCSErrorCode());
+                ex.setCSErrorCode(ref.getCSErrorCode());
                 throw ex;
             } else if (t instanceof ResourceUnavailableException) {
-            	ResourceUnavailableException ref = (ResourceUnavailableException)t;
+                ResourceUnavailableException ref = (ResourceUnavailableException)t;
                 ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, t.getMessage());
                 // copy over the IdentityProxy information as well and throw the serverapiexception.
                 ArrayList<String> idList = ref.getIdProxyList();
                 if (idList != null) {
-                	// Iterate through entire arraylist and copy over each proxy id.
-                	for (int i = 0 ; i < idList.size(); i++) {
-                 		String id = idList.get(i);
-                 		ex.addProxyObject(id);
-                 		s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id);
-                	}
+                    // Iterate through entire arraylist and copy over each proxy id.
+                    for (int i = 0 ; i < idList.size(); i++) {
+                        String id = idList.get(i);
+                        ex.addProxyObject(id);
+                        s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id);
+                    }
                 } else {
-                	s_logger.warn("Exception: ", t);
+                    s_logger.warn("Exception: ", t);
                 }
                 // Also copy over the cserror code.
-    			ex.setCSErrorCode(ref.getCSErrorCode());
+                ex.setCSErrorCode(ref.getCSErrorCode());
                 throw ex;
             } else if (t instanceof AsyncCommandQueued) {            	
                 throw (AsyncCommandQueued) t;
@@ -323,18 +313,18 @@ public class ApiDispatcher {
                 s_logger.error("Exception while executing " + cmd.getClass().getSimpleName() + ":", t);
                 ServerApiException ex;
                 if (UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
-                	ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
+                    ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage());
                 } else {
                     ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE);
                 }                
                 ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName()));
-            	throw ex;
+                throw ex;
             }
         }
     }
 
     @SuppressWarnings({ "unchecked", "rawtypes" })
-	public static void processParameters(BaseCmd cmd, Map<String, String> params) {
+    public static void processParameters(BaseCmd cmd, Map<String, String> params) {
         List<Object> entitiesToAccess = new ArrayList<Object>();
         Map<String, Object> unpackedParams = cmd.unpackParams(params);
 
@@ -348,7 +338,7 @@ public class ApiDispatcher {
             if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && pageSize != BaseListCmd.PAGESIZE_UNLIMITED)) {
                 ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified");                
                 ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName()));
-            	throw ex;
+                throw ex;
             } else if (pageSize == null && (unpackedParams.get(ApiConstants.PAGE) != null)) {
                 throw new ServerApiException(BaseCmd.PARAM_ERROR, "\"pagesize\" parameter is required when \"page\" is specified");
             }
@@ -399,14 +389,14 @@ public class ApiDispatcher {
                 throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage());
             } catch (CloudRuntimeException cloudEx) {
                 // FIXME: Better error message? This only happens if the API command is not executable, which typically
-            	//means
+                //means
                 // there was
                 // and IllegalAccessException setting one of the parameters.
                 throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8));
             }
 
             //check access on the resource this field points to
-	        try {
+            try {
                 ACL checkAccess = field.getAnnotation(ACL.class);
                 CommandType fieldType = parameterAnnotation.type();
 
@@ -426,17 +416,17 @@ public class ApiDispatcher {
                             // Check if the parameter type is a single
                             // Id or list of id's/name's
                             switch (fieldType) {
-                                case LIST:
-                                    CommandType listType = parameterAnnotation.collectionType();
-                                    switch (listType) {
-                                        case LONG:
-                                        case UUID:
-                                            List<Long> listParam = (List<Long>) field.get(cmd);
-                                            for (Long entityId : listParam) {
-                                                Object entityObj = s_instance._entityMgr.findById(entity, entityId);
-                                                entitiesToAccess.add(entityObj);
-                                            }
-                                            break;
+                            case LIST:
+                                CommandType listType = parameterAnnotation.collectionType();
+                                switch (listType) {
+                                case LONG:
+                                case UUID:
+                                    List<Long> listParam = (List<Long>) field.get(cmd);
+                                    for (Long entityId : listParam) {
+                                        Object entityObj = s_instance._entityMgr.findById(entity, entityId);
+                                        entitiesToAccess.add(entityObj);
+                                    }
+                                    break;
                                     /*
                                      * case STRING: List<String> listParam =
                                      * new ArrayList<String>(); listParam =
@@ -448,17 +438,17 @@ public class ApiDispatcher {
                                      * entitiesToAccess.add(entityObj); }
                                      * break;
                                      */
-                                        default:
-                                            break;
-        }
-                                    break;
-                                case LONG:
-                                case UUID:
-                                    Object entityObj = s_instance._entityMgr.findById(entity, (Long) field.get(cmd));
-                                    entitiesToAccess.add(entityObj);
-                                    break;
                                 default:
                                     break;
+                                }
+                                break;
+                            case LONG:
+                            case UUID:
+                                Object entityObj = s_instance._entityMgr.findById(entity, (Long) field.get(cmd));
+                                entitiesToAccess.add(entityObj);
+                                break;
+                            default:
+                                break;
                             }
 
                             if (ControlledEntity.class.isAssignableFrom(entity)) {
@@ -474,22 +464,22 @@ public class ApiDispatcher {
                             }
                         }
 
-	            	}
+                    }
 
-	            }
+                }
 
-			} catch (IllegalArgumentException e) {
-	            s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
-	            throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
-			} catch (IllegalAccessException e) {
-	            s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
-	            throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
-			}
+            } catch (IllegalArgumentException e) {
+                s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
+                throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
+            } catch (IllegalAccessException e) {
+                s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
+                throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
+            }
 
         }
 
         //check access on the entities.
-        s_instance.doAccessChecks(cmd, entitiesToAccess);
+        getInstance().doAccessChecks(cmd, entitiesToAccess);
 
     }
 
@@ -533,7 +523,7 @@ public class ApiDispatcher {
             // Invoke the getId method, get the internal long ID
             // If that fails hide exceptions as the uuid may not exist
             try {
-                internalId = (Long) ((InternalIdentity)objVO).getId();
+                internalId = ((InternalIdentity)objVO).getId();
             } catch (IllegalArgumentException e) {
             } catch (NullPointerException e) {
             }
@@ -598,7 +588,7 @@ public class ApiDispatcher {
                 // we ignore blank or null values and defer to the command to set a default
                 // value for optional parameters ...
                 if (paramObj != null && isNotBlank(paramObj.toString())) {
-                field.set(cmdObj, Float.valueOf(paramObj.toString()));
+                    field.set(cmdObj, Float.valueOf(paramObj.toString()));
                 }
                 break;
             case INTEGER:
@@ -606,7 +596,7 @@ public class ApiDispatcher {
                 // we ignore blank or null values and defer to the command to set a default
                 // value for optional parameters ...
                 if (paramObj != null && isNotBlank(paramObj.toString())) {
-                field.set(cmdObj, Integer.valueOf(paramObj.toString()));
+                    field.set(cmdObj, Integer.valueOf(paramObj.toString()));
                 }
                 break;
             case LIST:
@@ -619,16 +609,16 @@ public class ApiDispatcher {
                     case INTEGER:
                         listParam.add(Integer.valueOf(token));
                         break;
-                            case UUID:
-                                if (token.isEmpty())
-                                    break;
-                                Long internalId = translateUuidToInternalId(token, annotation);
-                                listParam.add(internalId);
-                                break;
+                    case UUID:
+                        if (token.isEmpty())
+                            break;
+                        Long internalId = translateUuidToInternalId(token, annotation);
+                        listParam.add(internalId);
+                        break;
                     case LONG: {
-                                listParam.add(Long.valueOf(token));
+                        listParam.add(Long.valueOf(token));
                     }
-                        break;
+                    break;
                     case SHORT:
                         listParam.add(Short.valueOf(token));
                     case STRING:
@@ -645,7 +635,7 @@ public class ApiDispatcher {
                 field.set(cmdObj, internalId);
                 break;
             case LONG:
-                    field.set(cmdObj, Long.valueOf(paramObj.toString()));
+                field.set(cmdObj, Long.valueOf(paramObj.toString()));
                 break;
             case SHORT:
                 field.set(cmdObj, Short.valueOf(paramObj.toString()));
@@ -686,31 +676,23 @@ public class ApiDispatcher {
     }
 
     public static void plugService(Field field, BaseCmd cmd) {
-        ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
 
-                Class<?> fc = field.getType();
-                Object instance = null;
-                if (PluggableService.class.isAssignableFrom(fc)) {
-                    instance = locator.getPluggableService(fc);
-                }
+        Class<?> fc = field.getType();
+        Object instance = null;
 
-                if (instance == null) {
+        if (instance == null) {
             throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + cmd.getClass().getSimpleName());
-                }
+        }
 
-                try {
-                    field.setAccessible(true);
-                    field.set(cmd, instance);
-                } catch (IllegalArgumentException e) {
-                    s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName() + ", field " + field.getName());
-                    throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [Illegal argumet at field " + field.getName() + "]");
-                } catch (IllegalAccessException e) {
-                    s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
-                    throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
-                }
-            }
-    
-    public static Long getIdentiyId(String tableName, String token) {
-        return s_instance._identityDao.getIdentityId(tableName, token);
+        try {
+            field.setAccessible(true);
+            field.set(cmd, instance);
+        } catch (IllegalArgumentException e) {
+            s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName() + ", field " + field.getName());
+            throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [Illegal argumet at field " + field.getName() + "]");
+        } catch (IllegalAccessException e) {
+            s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
+            throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/ApiGsonHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiGsonHelper.java b/server/src/com/cloud/api/ApiGsonHelper.java
index 6e64f71..6163860 100644
--- a/server/src/com/cloud/api/ApiGsonHelper.java
+++ b/server/src/com/cloud/api/ApiGsonHelper.java
@@ -17,7 +17,6 @@
 package com.cloud.api;
 
 import com.google.gson.GsonBuilder;
-import com.cloud.utils.IdentityProxy;
 import org.apache.cloudstack.api.ResponseObject;
 
 import java.util.Map;
@@ -28,7 +27,6 @@ public class ApiGsonHelper {
         s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
         s_gBuilder.setVersion(1.3);
         s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter());
-        s_gBuilder.registerTypeAdapter(IdentityProxy.class, new IdentityTypeAdapter());
         s_gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter());
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/ApiResponseGsonHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseGsonHelper.java b/server/src/com/cloud/api/ApiResponseGsonHelper.java
index c71193e..6bccf9a 100644
--- a/server/src/com/cloud/api/ApiResponseGsonHelper.java
+++ b/server/src/com/cloud/api/ApiResponseGsonHelper.java
@@ -17,7 +17,6 @@
 package com.cloud.api;
 
 import com.google.gson.GsonBuilder;
-import com.cloud.utils.IdentityProxy;
 import org.apache.cloudstack.api.ResponseObject;
 
 /**
@@ -25,13 +24,12 @@ import org.apache.cloudstack.api.ResponseObject;
  */
 public class ApiResponseGsonHelper {
     private static final GsonBuilder s_gBuilder;
-    
+
     static {
         s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
         s_gBuilder.setVersion(1.3);
         s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter());
         s_gBuilder.registerTypeAdapter(String.class, new EncodedStringTypeAdapter());
-        s_gBuilder.registerTypeAdapter(IdentityProxy.class, new IdentityTypeAdapter());
     }
 
     public static GsonBuilder getBuilder() {

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index 37be83e..c346a6b 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -482,7 +482,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         response.setEndPoint(result.getEndPoint());
         response.setHttpsFlag(result.getHttpsFlag());
         response.setMaxErrorRetry(result.getMaxErrorRetry());
-        response.setObjectId(result.getId());
+        response.setObjectId(result.getUuid());
         response.setSecretKey(result.getSecretKey());
         response.setSocketTimeout(result.getSocketTimeout());
         response.setTemplateBucketName(result.getBucketName());
@@ -1265,6 +1265,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         templateResponse.setFeatured(template.isFeatured());
         templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
         templateResponse.setPasswordEnabled(template.getEnablePassword());
+        templateResponse.setSshKeyEnabled(template.getEnableSshKey());
         templateResponse.setCrossZones(template.isCrossZones());
         templateResponse.setFormat(template.getFormat());
         templateResponse.setDetails(template.getDetails());
@@ -1346,6 +1347,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         templateResponse.setFeatured(template.isFeatured());
         templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
         templateResponse.setPasswordEnabled(template.getEnablePassword());
+        templateResponse.setSshKeyEnabled(template.getEnableSshKey());
         templateResponse.setCrossZones(template.isCrossZones());
         templateResponse.setFormat(template.getFormat());
         if (template.getTemplateType() != null) {
@@ -2790,11 +2792,6 @@ public class ApiResponseHelper implements ResponseGenerator {
     }
 
     @Override
-    public Long getIdentiyId(String tableName, String token) {
-        return ApiDispatcher.getIdentiyId(tableName, token);
-    }
-
-    @Override
     public ResourceTagResponse createResourceTagResponse(ResourceTag resourceTag, boolean keyValueOnly) {
         ResourceTagJoinVO rto = ApiDBUtils.newResourceTagView(resourceTag);
         return ApiDBUtils.newResourceTagResponse(rto, keyValueOnly);

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/ApiServer.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java
index 6e13f13..8a2c675 100755
--- a/server/src/com/cloud/api/ApiServer.java
+++ b/server/src/com/cloud/api/ApiServer.java
@@ -45,13 +45,16 @@ import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 
+import javax.annotation.PostConstruct;
 import javax.crypto.Mac;
 import javax.crypto.spec.SecretKeySpec;
 import javax.inject.Inject;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
-import org.apache.cloudstack.acl.APIAccessChecker;
+import org.apache.cloudstack.acl.APIChecker;
+import org.apache.cloudstack.acl.RoleType;
+import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.BaseAsyncCmd;
 import org.apache.cloudstack.api.BaseAsyncCreateCmd;
 import org.apache.cloudstack.api.BaseCmd;
@@ -74,7 +77,6 @@ import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd;
 import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
 import org.apache.cloudstack.api.response.ExceptionResponse;
 import org.apache.cloudstack.api.response.ListResponse;
-import org.apache.cloudstack.discovery.ApiDiscoveryService;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.http.ConnectionClosedException;
 import org.apache.http.HttpException;
@@ -104,12 +106,12 @@ import org.apache.http.protocol.ResponseContent;
 import org.apache.http.protocol.ResponseDate;
 import org.apache.http.protocol.ResponseServer;
 import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
 
 import com.cloud.api.response.ApiResponseSerializer;
 import com.cloud.async.AsyncJob;
 import com.cloud.async.AsyncJobManager;
 import com.cloud.async.AsyncJobVO;
-import com.cloud.cluster.StackMaid;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.ConfigurationVO;
 import com.cloud.configuration.dao.ConfigurationDao;
@@ -127,70 +129,61 @@ import com.cloud.user.UserAccount;
 import com.cloud.user.UserContext;
 import com.cloud.user.UserVO;
 import com.cloud.utils.Pair;
+import com.cloud.utils.NumbersUtil;
+import com.cloud.utils.ReflectUtil;
 import com.cloud.utils.StringUtils;
-import com.cloud.utils.component.ComponentContext;
 import com.cloud.utils.component.PluggableService;
 import com.cloud.utils.concurrency.NamedThreadFactory;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CSExceptionErrorCode;
-import com.cloud.uuididentity.dao.IdentityDao;
 
+@Component
 public class ApiServer implements HttpRequestHandler {
     private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName());
     private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
 
     public static boolean encodeApiResponse = false;
     public static String jsonContentType = "text/javascript";
-    private ApiDispatcher _dispatcher;
+    @Inject ApiDispatcher _dispatcher;
 
-    @Inject private final AccountManager _accountMgr = null;
-    @Inject private final DomainManager _domainMgr = null;
-    @Inject private final AsyncJobManager _asyncMgr = null;
+    @Inject private AccountManager _accountMgr;
+    @Inject private DomainManager _domainMgr;
+    @Inject private AsyncJobManager _asyncMgr;
     @Inject private ConfigurationDao _configDao;
-    @Inject protected List<APIAccessChecker> _apiAccessCheckers;
 
     @Inject List<PluggableService> _pluggableServices;
-    @Inject IdentityDao _identityDao;
 
-    protected List<ApiDiscoveryService> _apiDiscoveryServices;
+    @Inject List<APIChecker> _apiAccessCheckers;
 
     private Account _systemAccount = null;
     private User _systemUser = null;
     private static int _workerCount = 0;
     private static ApiServer s_instance = null;
     private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
-    private final Map<String, Class<?>> _apiNameCmdClassMap = new HashMap<String, Class<?>>();
+    private static Map<String, Class<?>> _apiNameCmdClassMap = new HashMap<String, Class<?>>();
 
     private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("ApiServer"));
 
-    protected ApiServer() {
-        super();
+    public ApiServer() {
     }
-
-    public static void initApiServer(String[] apiConfig) {
-        if (s_instance == null) {
-            s_instance = new ApiServer();
-            s_instance = ComponentContext.inject(s_instance);
-            s_instance.init(apiConfig);
-        }
+    
+    @PostConstruct
+    void initComponent() {
+    	s_instance = this;
+    	init();
     }
 
     public static ApiServer getInstance() {
-        // Assumption: CloudStartupServlet would initialize ApiServer
-        if (s_instance == null) {
-            s_logger.fatal("ApiServer instance failed to initialize");
-        }
         return s_instance;
     }
 
-    public void init(String[] apiConfig) {
+    public void init() {
         BaseCmd.setComponents(new ApiResponseHelper());
         BaseListCmd.configure();
 
         _systemAccount = _accountMgr.getSystemAccount();
         _systemUser = _accountMgr.getSystemUser();
-        _dispatcher = ApiDispatcher.getInstance();
 
         Integer apiPort = null; // api port, null by default
         SearchCriteria<ConfigurationVO> sc = _configDao.createSearchCriteria();
@@ -203,13 +196,28 @@ public class ApiServer implements HttpRequestHandler {
             }
         }
 
-        for (ApiDiscoveryService discoveryService: _apiDiscoveryServices) {
-            _apiNameCmdClassMap.putAll(discoveryService.getApiNameCmdClassMapping());
+        Map<String, String> configs = _configDao.getConfiguration();
+        String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key());
+        if (strSnapshotLimit != null) {
+            Long snapshotLimit = NumbersUtil.parseLong(strSnapshotLimit, 1L);
+            if (snapshotLimit <= 0) {
+                s_logger.debug("Global config parameter " + Config.ConcurrentSnapshotsThresholdPerHost.toString()
+                        + " is less or equal 0; defaulting to unlimited");
+            } else {
+                _dispatcher.setCreateSnapshotQueueSizeLimit(snapshotLimit);
+            }
         }
 
-        if (_apiNameCmdClassMap.size() == 0) {
-            s_logger.fatal("ApiServer failed to generate apiname, cmd class mappings."
-                    + "Please check and enable at least one ApiDiscovery adapter.");
+        Set<Class<?>> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class,
+                new String[]{"org.apache.cloudstack.api", "com.cloud.api"});
+
+        for(Class<?> cmdClass: cmdClasses) {
+            String apiName = cmdClass.getAnnotation(APICommand.class).name();
+            if (_apiNameCmdClassMap.containsKey(apiName)) {
+                s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName);
+                continue;
+            }
+            _apiNameCmdClassMap.put(apiName, cmdClass);
         }
 
         encodeApiResponse = Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key()));
@@ -403,12 +411,12 @@ public class ApiServer implements HttpRequestHandler {
         // BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized and returned.
         if (cmdObj instanceof BaseAsyncCmd) {
             Long objectId = null;
-            String objectEntityTable = null;
+            String objectUuid = null;
             if (cmdObj instanceof BaseAsyncCreateCmd) {
                 BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
                 _dispatcher.dispatchCreateCmd(createCmd, params);
                 objectId = createCmd.getEntityId();
-                objectEntityTable = createCmd.getEntityTable();
+                objectUuid = createCmd.getEntityUuid();
                 params.put("id", objectId.toString());
             } else {
                 ApiDispatcher.processParameters(cmdObj, params);
@@ -452,8 +460,8 @@ public class ApiServer implements HttpRequestHandler {
             }
 
             if (objectId != null) {
-                SerializationContext.current().setUuidTranslation(true);
-                return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objectId, objectEntityTable);
+                String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid;
+                return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objUuid);
             }
 
             SerializationContext.current().setUuidTranslation(true);
@@ -463,6 +471,7 @@ public class ApiServer implements HttpRequestHandler {
 
             // if the command is of the listXXXCommand, we will need to also return the
             // the job id and status if possible
+            // For those listXXXCommand which we have already created DB views, this step is not needed since async job is joined in their db views.
             if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListRoutersCmd)
                     && !(cmdObj instanceof ListSecurityGroupsCmd)
                     && !(cmdObj instanceof ListTagsCmd)
@@ -553,14 +562,14 @@ public class ApiServer implements HttpRequestHandler {
             if (userId != null) {
                 User user = ApiDBUtils.findUserById(userId);
                 if (!isCommandAvailable(user, commandName)) {
-                    s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user");
+                    s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId);
                     throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user");
                 }
                 return true;
             } else {
                 // check against every available command to see if the command exists or not
-                if (!isCommandAvailable(null, commandName) && !commandName.equals("login") && !commandName.equals("logout")) {
-                    s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user");
+                if (!_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) {
+                    s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId);
                     throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user");
                 }
             }
@@ -604,30 +613,29 @@ public class ApiServer implements HttpRequestHandler {
 
             // if api/secret key are passed to the parameters
             if ((signature == null) || (apiKey == null)) {
-                if (s_logger.isDebugEnabled()) {
-                    s_logger.info("expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
-                }
+                s_logger.debug("Expired session, missing signature, or missing apiKey -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
                 return false; // no signature, bad request
             }
 
             Date expiresTS = null;
+            // FIXME: Hard coded signature, why not have an enum
             if ("3".equals(signatureVersion)) {
                 // New signature authentication. Check for expire parameter and its validity
                 if (expires == null) {
-                    s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
+                    s_logger.debug("Missing Expires parameter -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey);
                     return false;
                 }
                 synchronized (_dateFormat) {
                     try {
                         expiresTS = _dateFormat.parse(expires);
                     } catch (ParseException pe) {
-                        s_logger.info("Incorrect date format for Expires parameter", pe);
+                        s_logger.debug("Incorrect date format for Expires parameter", pe);
                         return false;
                     }
                 }
                 Date now = new Date(System.currentTimeMillis());
                 if (expiresTS.before(now)) {
-                    s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
+                    s_logger.debug("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
                     return false;
                 }
             }
@@ -638,7 +646,7 @@ public class ApiServer implements HttpRequestHandler {
             // verify there is a user with this api key
             Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey);
             if (userAcctPair == null) {
-                s_logger.info("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
+                s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
                 return false;
             }
 
@@ -654,8 +662,8 @@ public class ApiServer implements HttpRequestHandler {
             UserContext.updateContext(user.getId(), account, null);
 
             if (!isCommandAvailable(user, commandName)) {
-                s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user");
-                throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user");
+                s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user");
+                throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + userId);
             }
 
             // verify secret key exists
@@ -682,18 +690,13 @@ public class ApiServer implements HttpRequestHandler {
             if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) {
                 throw (ServerApiException) ex;
             }
-            s_logger.error("unable to verifty request signature", ex);
+            s_logger.error("unable to verify request signature", ex);
         }
         return false;
     }
 
-    public Long fetchDomainId(String domainUUID){
-        try{
-            Long domainId = _identityDao.getIdentityId("domain", domainUUID);
-            return domainId;
-        }catch(InvalidParameterValueException ex){
-            return null;
-        }
+    public Long fetchDomainId(String domainUUID) {
+        return _domainMgr.getDomain(domainUUID).getId();
     }
 
     public void loginUser(HttpSession session, String username, String password, Long domainId, String domainPath, String loginIpAddress ,Map<String, Object[]> requestParameters) throws CloudAuthenticationException {
@@ -789,10 +792,16 @@ public class ApiServer implements HttpRequestHandler {
         return true;
     }
 
-    private boolean isCommandAvailable(User user, String commandName) {
-        for (APIAccessChecker apiChecker : _apiAccessCheckers) {
+    private boolean isCommandAvailable(User user, String commandName) throws PermissionDeniedException {
+        if (user == null) {
+            throw new PermissionDeniedException("User is null for role based API access check for command" + commandName);
+        }
+
+        Account account = _accountMgr.getAccount(user.getAccountId());
+        RoleType roleType = _accountMgr.getRoleType(account);
+        for (APIChecker apiChecker : _apiAccessCheckers) {
             // Fail the checking if any checker fails to verify
-            if (!apiChecker.canAccessAPI(user, commandName))
+            if (!apiChecker.checkAccess(roleType, commandName))
                 return false;
         }
         return true;
@@ -907,12 +916,8 @@ public class ApiServer implements HttpRequestHandler {
             HttpContext context = new BasicHttpContext(null);
             try {
                 while (!Thread.interrupted() && _conn.isOpen()) {
-                    try {
-                        _httpService.handleRequest(_conn, context);
-                        _conn.close();
-                    } finally {
-                        StackMaid.current().exitCleanup();
-                    }
+                    _httpService.handleRequest(_conn, context);
+                    _conn.close();
                 }
             } catch (ConnectionClosedException ex) {
                 if (s_logger.isTraceEnabled()) {

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/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..e535030 100755
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@ -23,6 +23,7 @@ import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
 
+import javax.inject.Inject;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
@@ -31,51 +32,42 @@ import javax.servlet.http.HttpSession;
 import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
 
-import com.cloud.cluster.StackMaid;
 import com.cloud.exception.CloudAuthenticationException;
-import com.cloud.server.ManagementServer;
 import com.cloud.user.Account;
 import com.cloud.user.AccountService;
 import com.cloud.user.UserContext;
 import com.cloud.utils.StringUtils;
-import com.cloud.utils.component.ComponentLocator;
+import com.cloud.utils.component.ComponentContext;
 import com.cloud.utils.exception.CloudRuntimeException;
 
+@Component("apiServlet")
 @SuppressWarnings("serial")
 public class ApiServlet extends HttpServlet {
     public static final Logger s_logger = Logger.getLogger(ApiServlet.class.getName());
     private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
 
-    private ApiServer _apiServer = null;
-    private AccountService _accountMgr = null;
+    ApiServer _apiServer;
+    AccountService _accountMgr;
 
     public ApiServlet() {
         super();
         _apiServer = ApiServer.getInstance();
+        _accountMgr = ComponentContext.getComponent(AccountService.class);
         if (_apiServer == null) {
             throw new CloudRuntimeException("ApiServer not initialized");
         }
-        ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
-        _accountMgr = locator.getManager(AccountService.class);
     }
 
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
-        try {
-            processRequest(req, resp);
-        } finally {
-            StackMaid.current().exitCleanup();
-        }
+        processRequest(req, resp);
     }
 
     @Override
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
-        try {
-            processRequest(req, resp);
-        } finally {
-            StackMaid.current().exitCleanup();
-        }
+        processRequest(req, resp);
     }
 
     private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) {
@@ -128,7 +120,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");
@@ -305,7 +297,7 @@ public class ApiServlet extends HttpServlet {
 
                 auditTrailSb.insert(0,
                         "(userId=" + UserContext.current().getCallerUserId() + " accountId=" + UserContext.current().getCaller().getId() + " sessionId=" + (session != null ? session.getId() : null)
-                                + ")");
+                        + ")");
 
                 try {
                     String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
@@ -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/110465b5/server/src/com/cloud/api/IdentityTypeAdapter.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/IdentityTypeAdapter.java b/server/src/com/cloud/api/IdentityTypeAdapter.java
deleted file mode 100644
index 369c202..0000000
--- a/server/src/com/cloud/api/IdentityTypeAdapter.java
+++ /dev/null
@@ -1,80 +0,0 @@
-// 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 com.cloud.api;
-
-import java.lang.reflect.Type;
-
-import com.cloud.uuididentity.dao.IdentityDao;
-import com.cloud.uuididentity.dao.IdentityDaoImpl;
-import com.google.gson.Gson;
-import com.google.gson.JsonDeserializationContext;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonPrimitive;
-import com.google.gson.JsonSerializationContext;
-import com.google.gson.JsonSerializer;
-import com.cloud.utils.IdentityProxy;
-
-
-public class IdentityTypeAdapter implements JsonSerializer<IdentityProxy>, JsonDeserializer<IdentityProxy> {
-	
-	@Override
-	public JsonElement serialize(IdentityProxy src, Type srcType, JsonSerializationContext context) {
-		if(SerializationContext.current().getUuidTranslation()) {
-			assert(src != null);
-			if(src.getValue() == null)
-				return context.serialize(null);
-	
-			IdentityDao identityDao = new IdentityDaoImpl();
-			if(src.getTableName() != null) {
-				String uuid = identityDao.getIdentityUuid(src.getTableName(), String.valueOf(src.getValue()));
-				if(uuid == null)
-					return context.serialize(null);
-				
-				// Exceptions set the _idFieldName in the IdentityProxy structure. So if this field is not
-				// null, prepare a structure of uuid and idFieldName and return the json representation of that.
-				String idName = src.getidFieldName();
-				if (idName != null) {
-					// Prepare a structure.
-					JsonObject jsonObj = new JsonObject();
-					jsonObj.add("uuid", new JsonPrimitive(uuid));
-					jsonObj.add("uuidProperty", new JsonPrimitive(idName));
-					return jsonObj;
-				}
-				return new JsonPrimitive(uuid);
-			} else {
-				return new JsonPrimitive(String.valueOf(src.getValue()));
-			}
-		} else {
-	        return new Gson().toJsonTree(src);
-		}
-	}
-	
-	@Override
-	public IdentityProxy deserialize(JsonElement src, Type srcType,
-			JsonDeserializationContext context) throws JsonParseException {
-
-		IdentityProxy obj = new IdentityProxy();
-		JsonObject json = src.getAsJsonObject();
-		obj.setTableName(json.get("_tableName").getAsString());
-		if(json.get("_value") != null)
-			obj.setValue(json.get("_value").getAsLong());
-		return obj;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/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..c80a62b 100644
--- a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
+++ b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java
@@ -16,91 +16,93 @@
 // under the License.
 package com.cloud.api.commands;
 
-import org.apache.cloudstack.api.*;
+import javax.inject.Inject;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.TrafficMonitorResponse;
 import org.apache.cloudstack.api.response.ZoneResponse;
 import org.apache.log4j.Logger;
 
-import org.apache.cloudstack.api.APICommand;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.host.Host;
 import com.cloud.network.NetworkUsageManager;
-import com.cloud.server.ManagementService;
-import org.apache.cloudstack.api.response.TrafficMonitorResponse;
 import com.cloud.user.Account;
-import com.cloud.utils.component.ComponentLocator;
 import com.cloud.utils.exception.CloudRuntimeException;
 
 @APICommand(name = "addTrafficMonitor", description="Adds Traffic Monitor Host for Direct Network Usage", responseObject = TrafficMonitorResponse.class)
 public class AddTrafficMonitorCmd extends BaseCmd {
-	public static final Logger s_logger = Logger.getLogger(AddTrafficMonitorCmd.class.getName());	
-	private static final String s_name = "addtrafficmonitorresponse";	
-	
-	/////////////////////////////////////////////////////
+    public static final Logger s_logger = Logger.getLogger(AddTrafficMonitorCmd.class.getName());	
+    private static final String s_name = "addtrafficmonitorresponse";	
+    @Inject NetworkUsageManager networkUsageMgr;
+
+    /////////////////////////////////////////////////////
     //////////////// API parameters /////////////////////
     /////////////////////////////////////////////////////
-	
-	@Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class,
+
+    @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class,
             required = true, description="Zone in which to add the external firewall appliance.")
-	private Long zoneId;
-	
-	@Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the traffic monitor Host")
-	private String url;	 
-
-	@Parameter(name=ApiConstants.INCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will be metered")
-	private String inclZones;	 
-	
-	@Parameter(name=ApiConstants.EXCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will not be metered")
-	private String exclZones;	 
-	
-	///////////////////////////////////////////////////
-	/////////////////// Accessors ///////////////////////
-	/////////////////////////////////////////////////////
-	 
-	public String getInclZones() {
-		return inclZones;
-	}
-	
-	public String getExclZones() {
-		return exclZones;
-	}
-
-	public Long getZoneId() {
-	    return zoneId;
-	}
-
-	public String getUrl() {
-		return url;
-	}
-	
-	/////////////////////////////////////////////////////
-	/////////////// API Implementation///////////////////
-	/////////////////////////////////////////////////////
-
-	@Override
-	public String getCommandName() {
-		return s_name;
-	}
-	
-	@Override
+    private Long zoneId;
+
+    @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the traffic monitor Host")
+    private String url;	 
+
+    @Parameter(name=ApiConstants.INCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will be metered")
+    private String inclZones;	 
+
+    @Parameter(name=ApiConstants.EXCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will not be metered")
+    private String exclZones;	 
+
+    ///////////////////////////////////////////////////
+    /////////////////// Accessors ///////////////////////
+    /////////////////////////////////////////////////////
+
+    public String getInclZones() {
+        return inclZones;
+    }
+
+    public String getExclZones() {
+        return exclZones;
+    }
+
+    public Long getZoneId() {
+        return zoneId;
+    }
+
+    public String getUrl() {
+        return url;
+    }
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
     public long getEntityOwnerId() {
         return Account.ACCOUNT_ID_SYSTEM;
     }
-	 
-	@Override
+
+    @Override
     public void execute(){
-		try {
-		    ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
-		    NetworkUsageManager networkUsageMgr = locator.getManager(NetworkUsageManager.class);
-			Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this);
-			TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor);
-			response.setObjectName("trafficmonitor");
-			response.setResponseName(getCommandName());
-			this.setResponseObject(response);
-		} catch (InvalidParameterValueException ipve) {
-			throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage());
-		} catch (CloudRuntimeException cre) {
-			throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage());
-		}
+        try {
+            Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this);
+            TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor);
+            response.setObjectName("trafficmonitor");
+            response.setResponseName(getCommandName());
+            this.setResponseObject(response);
+        } catch (InvalidParameterValueException ipve) {
+            throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage());
+        } catch (CloudRuntimeException cre) {
+            throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage());
+        }
     }
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/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..9e84f03 100644
--- a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
+++ b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java
@@ -16,71 +16,70 @@
 // under the License.
 package com.cloud.api.commands;
 
-import org.apache.cloudstack.api.response.HostResponse;
-import org.apache.log4j.Logger;
+import javax.inject.Inject;
 
+import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.ApiConstants;
 import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.Parameter;
 import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.cloudstack.api.response.SuccessResponse;
+import org.apache.log4j.Logger;
+
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.network.NetworkUsageManager;
-import com.cloud.server.ManagementService;
 import com.cloud.user.Account;
-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";	
+    @Inject NetworkUsageManager _networkUsageMgr;
+
+    /////////////////////////////////////////////////////
     //////////////// API parameters /////////////////////
     /////////////////////////////////////////////////////
-	
-	@Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class,
+
+    @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///////////////////
-	/////////////////////////////////////////////////////
+    private Long id;
 
-	@Override
-	public String getCommandName() {
-		return s_name;
-	}
-	
-	@Override
+    ///////////////////////////////////////////////////
+    /////////////////// Accessors ///////////////////////
+    /////////////////////////////////////////////////////
+
+    public Long getId() {
+        return id;
+    }
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
     public long getEntityOwnerId() {
         return Account.ACCOUNT_ID_SYSTEM;
     }
-	 
-	@Override
+
+    @Override
     public void execute(){
-		try {
-		    ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
-		    NetworkUsageManager _networkUsageMgr = locator.getManager(NetworkUsageManager.class);
-			boolean result = _networkUsageMgr.deleteTrafficMonitor(this);
-			if (result) {
-			SuccessResponse response = new SuccessResponse(getCommandName());
-			response.setResponseName(getCommandName());
-			this.setResponseObject(response);
-			} else {
-				throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic monitor.");
-			}
-		} catch (InvalidParameterValueException e) {
-			throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete traffic monitor.");
-		}
+        try {
+            boolean result = _networkUsageMgr.deleteTrafficMonitor(this);
+            if (result) {
+                SuccessResponse response = new SuccessResponse(getCommandName());
+                response.setResponseName(getCommandName());
+                this.setResponseObject(response);
+            } else {
+                throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic monitor.");
+            }
+        } catch (InvalidParameterValueException e) {
+            throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete traffic monitor.");
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java b/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java
index 21ad339..645bf3b 100644
--- a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java
+++ b/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java
@@ -19,26 +19,28 @@ package com.cloud.api.commands;
 import java.util.ArrayList;
 import java.util.List;
 
-import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd;
-import org.apache.cloudstack.api.response.ZoneResponse;
-import org.apache.log4j.Logger;
+import javax.inject.Inject;
 
+import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.ApiConstants;
 import org.apache.cloudstack.api.BaseListCmd;
-import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd;
 import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.TrafficMonitorResponse;
+import org.apache.cloudstack.api.response.ZoneResponse;
+import org.apache.log4j.Logger;
+
 import com.cloud.host.Host;
 import com.cloud.network.NetworkUsageManager;
-import com.cloud.server.ManagementService;
-import org.apache.cloudstack.api.response.TrafficMonitorResponse;
-import com.cloud.utils.component.ComponentLocator;
+
 
 @APICommand(name = "listTrafficMonitors", description="List traffic monitor Hosts.", responseObject = TrafficMonitorResponse.class)
 public class ListTrafficMonitorsCmd extends BaseListCmd {
-	public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName());
+    public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName());
     private static final String s_name = "listtrafficmonitorsresponse";
 
+    @Inject NetworkUsageManager networkUsageMgr;
     /////////////////////////////////////////////////////
     //////////////// API parameters /////////////////////
     /////////////////////////////////////////////////////
@@ -66,17 +68,15 @@ public class ListTrafficMonitorsCmd extends BaseListCmd {
 
     @Override
     public void execute(){
-        ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
-        NetworkUsageManager networkUsageMgr = locator.getManager(NetworkUsageManager.class);
-    	List<? extends Host> trafficMonitors = networkUsageMgr.listTrafficMonitors(this);
+        List<? extends Host> trafficMonitors = networkUsageMgr.listTrafficMonitors(this);
 
         ListResponse<TrafficMonitorResponse> listResponse = new ListResponse<TrafficMonitorResponse>();
         List<TrafficMonitorResponse> responses = new ArrayList<TrafficMonitorResponse>();
         for (Host trafficMonitor : trafficMonitors) {
             TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor);
-        	response.setObjectName("trafficmonitor");
-        	response.setResponseName(getCommandName());
-        	responses.add(response);
+            response.setObjectName("trafficmonitor");
+            response.setResponseName(getCommandName());
+            responses.add(response);
         }
 
         listResponse.setResponses(responses);

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/query/QueryManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java
index b61f10a..6760dec 100644
--- a/server/src/com/cloud/api/query/QueryManagerImpl.java
+++ b/server/src/com/cloud/api/query/QueryManagerImpl.java
@@ -22,6 +22,7 @@ import java.util.List;
 import java.util.Map;
 
 import javax.ejb.Local;
+import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.cloudstack.api.command.admin.host.ListHostsCmd;
@@ -57,6 +58,7 @@ import org.apache.cloudstack.api.response.UserVmResponse;
 import org.apache.cloudstack.api.response.VolumeResponse;
 import org.apache.cloudstack.query.QueryService;
 import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
 
 import com.cloud.api.query.dao.AccountJoinDao;
 import com.cloud.api.query.dao.AsyncJobJoinDao;
@@ -97,15 +99,13 @@ import com.cloud.ha.HighAvailabilityManager;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.network.security.SecurityGroupVMMapVO;
 import com.cloud.network.security.dao.SecurityGroupVMMapDao;
-import com.cloud.projects.ProjectInvitation;
-import com.cloud.projects.Project.ListProjectResourcesCriteria;
 import com.cloud.projects.Project;
+import com.cloud.projects.Project.ListProjectResourcesCriteria;
+import com.cloud.projects.ProjectInvitation;
 import com.cloud.projects.ProjectManager;
 import com.cloud.projects.dao.ProjectAccountDao;
 import com.cloud.projects.dao.ProjectDao;
 import com.cloud.server.Criteria;
-import com.cloud.storage.StoragePool;
-import com.cloud.storage.StoragePoolVO;
 import com.cloud.storage.Volume;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
@@ -115,7 +115,6 @@ import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.DateUtil;
 import com.cloud.utils.Pair;
 import com.cloud.utils.Ternary;
-import com.cloud.utils.component.Inject;
 import com.cloud.utils.component.Manager;
 import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.SearchBuilder;
@@ -130,6 +129,7 @@ import com.cloud.vm.dao.UserVmDao;
  * @author minc
  *
  */
+@Component
 @Local(value = {QueryService.class })
 public class QueryManagerImpl implements QueryService, Manager {
 
@@ -137,7 +137,7 @@ public class QueryManagerImpl implements QueryService, Manager {
 
     private String _name;
 
-   // public static ViewResponseHelper _responseGenerator;
+    // public static ViewResponseHelper _responseGenerator;
 
     @Inject
     private AccountManager _accountMgr;
@@ -214,8 +214,7 @@ public class QueryManagerImpl implements QueryService, Manager {
     @Override
     public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
         _name = name;
-       // _responseGenerator = new ViewResponseHelper();
-        return false;
+        return true;
     }
 
     @Override
@@ -717,7 +716,7 @@ public class QueryManagerImpl implements QueryService, Manager {
 
         if (tags != null && !tags.isEmpty()) {
             int count = 0;
-             for (String key : tags.keySet()) {
+            for (String key : tags.keySet()) {
                 sc.setParameters("key" + String.valueOf(count), key);
                 sc.setParameters("value" + String.valueOf(count), tags.get(key));
                 count++;
@@ -883,10 +882,10 @@ public class QueryManagerImpl implements QueryService, Manager {
         if (tags != null && !tags.isEmpty()) {
             int count = 0;
             for (String key : tags.keySet()) {
-               sc.setParameters("key" + String.valueOf(count), key);
-               sc.setParameters("value" + String.valueOf(count), tags.get(key));
-               count++;
-           }
+                sc.setParameters("key" + String.valueOf(count), key);
+                sc.setParameters("value" + String.valueOf(count), tags.get(key));
+                count++;
+            }
         }
 
         if (securityGroup != null) {
@@ -974,10 +973,10 @@ public class QueryManagerImpl implements QueryService, Manager {
         //Filter searchFilter = new Filter(DomainRouterJoinVO.class, null, true, cmd.getStartIndex(), cmd.getPageSizeVal());
         SearchBuilder<DomainRouterJoinVO> sb = _routerJoinDao.createSearchBuilder();
         sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
-                                                             // ids to get
-                                                             // number of
-                                                             // records with
-                                                             // pagination
+        // ids to get
+        // number of
+        // records with
+        // pagination
         _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE);
@@ -1095,7 +1094,7 @@ public class QueryManagerImpl implements QueryService, Manager {
         Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize);
         SearchBuilder<ProjectJoinVO> sb = _projectJoinDao.createSearchBuilder();
         sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
-                                                             // ids
+        // ids
 
         if (_accountMgr.isAdmin(caller.getType())) {
             if (domainId != null) {
@@ -1302,7 +1301,7 @@ public class QueryManagerImpl implements QueryService, Manager {
         Long startIndex = cmd.getStartIndex();
         Long pageSizeVal = cmd.getPageSizeVal();
 
-            //long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) {
+        //long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) {
         Account caller = UserContext.current().getCaller();
 
         //check that the project exists
@@ -1546,7 +1545,7 @@ public class QueryManagerImpl implements QueryService, Manager {
 
         if (tags != null && !tags.isEmpty()) {
             int count = 0;
-             for (String key : tags.keySet()) {
+            for (String key : tags.keySet()) {
                 sc.setParameters("key" + String.valueOf(count), key);
                 sc.setParameters("value" + String.valueOf(count), tags.get(key));
                 count++;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java
index cdfac3a..96b91df 100644
--- a/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java
+++ b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java
@@ -20,21 +20,19 @@ import java.util.ArrayList;
 import java.util.List;
 
 import javax.ejb.Local;
+import javax.inject.Inject;
 
+import org.apache.cloudstack.api.response.DomainRouterResponse;
+import org.apache.cloudstack.api.response.NicResponse;
 import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
 
 import com.cloud.api.ApiResponseHelper;
 import com.cloud.api.query.vo.DomainRouterJoinVO;
 import com.cloud.configuration.dao.ConfigurationDao;
-
-import org.apache.cloudstack.api.response.DomainRouterResponse;
-import org.apache.cloudstack.api.response.NicResponse;
-import org.springframework.stereotype.Component;
-
 import com.cloud.network.Networks.TrafficType;
 import com.cloud.network.router.VirtualRouter;
 import com.cloud.user.Account;
-import com.cloud.utils.component.Inject;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
@@ -47,9 +45,9 @@ public class DomainRouterJoinDaoImpl extends GenericDaoBase<DomainRouterJoinVO,
     @Inject
     private ConfigurationDao  _configDao;
 
-    private SearchBuilder<DomainRouterJoinVO> vrSearch;
+    private final SearchBuilder<DomainRouterJoinVO> vrSearch;
 
-    private SearchBuilder<DomainRouterJoinVO> vrIdSearch;
+    private final SearchBuilder<DomainRouterJoinVO> vrIdSearch;
 
     protected DomainRouterJoinDaoImpl() {
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java
index 9a7ba46..fa7618c 100644
--- a/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java
+++ b/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java
@@ -25,21 +25,19 @@ import java.util.List;
 import java.util.Set;
 
 import javax.ejb.Local;
+import javax.inject.Inject;
 
+import org.apache.cloudstack.api.ApiConstants.HostDetails;
+import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
 
 import com.cloud.api.ApiDBUtils;
 import com.cloud.api.query.vo.HostJoinVO;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.host.Host;
 import com.cloud.host.HostStats;
-
-import org.apache.cloudstack.api.ApiConstants.HostDetails;
-import org.apache.cloudstack.api.response.HostResponse;
-import org.springframework.stereotype.Component;
-
 import com.cloud.storage.StorageStats;
-import com.cloud.utils.component.Inject;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
@@ -52,9 +50,9 @@ public class HostJoinDaoImpl extends GenericDaoBase<HostJoinVO, Long> implements
     @Inject
     private ConfigurationDao  _configDao;
 
-    private SearchBuilder<HostJoinVO> hostSearch;
+    private final SearchBuilder<HostJoinVO> hostSearch;
 
-    private SearchBuilder<HostJoinVO> hostIdSearch;
+    private final SearchBuilder<HostJoinVO> hostIdSearch;
 
 
     protected HostJoinDaoImpl() {
@@ -97,14 +95,14 @@ public class HostJoinDaoImpl extends GenericDaoBase<HostJoinVO, Long> implements
         if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)
                 || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) {
 
-                hostResponse.setOsCategoryId(host.getOsCategoryUuid());
-                hostResponse.setOsCategoryName(host.getOsCategoryName());
-                hostResponse.setZoneName(host.getZoneName());
-                hostResponse.setPodName(host.getPodName());
-                if ( host.getClusterId() > 0) {
-                    hostResponse.setClusterName(host.getClusterName());
-                    hostResponse.setClusterType(host.getClusterType().toString());
-                }
+            hostResponse.setOsCategoryId(host.getOsCategoryUuid());
+            hostResponse.setOsCategoryName(host.getOsCategoryName());
+            hostResponse.setZoneName(host.getZoneName());
+            hostResponse.setPodName(host.getPodName());
+            if ( host.getClusterId() > 0) {
+                hostResponse.setClusterName(host.getClusterName());
+                hostResponse.setClusterType(host.getClusterType().toString());
+            }
         }
 
         DecimalFormat decimalFormat = new DecimalFormat("#.##");

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java
index 77f9303..5b2a350 100644
--- a/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java
+++ b/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java
@@ -20,19 +20,17 @@ import java.util.ArrayList;
 import java.util.List;
 
 import javax.ejb.Local;
+import javax.inject.Inject;
 
+import org.apache.cloudstack.api.response.ProjectResponse;
 import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
 
 import com.cloud.api.ApiDBUtils;
 import com.cloud.api.query.vo.ProjectJoinVO;
 import com.cloud.api.query.vo.ResourceTagJoinVO;
 import com.cloud.configuration.dao.ConfigurationDao;
-
-import org.apache.cloudstack.api.response.ProjectResponse;
-import org.springframework.stereotype.Component;
-
 import com.cloud.projects.Project;
-import com.cloud.utils.component.Inject;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
@@ -45,9 +43,9 @@ public class ProjectJoinDaoImpl extends GenericDaoBase<ProjectJoinVO, Long> impl
     @Inject
     private ConfigurationDao  _configDao;
 
-    private SearchBuilder<ProjectJoinVO> prjSearch;
+    private final SearchBuilder<ProjectJoinVO> prjSearch;
 
-    private SearchBuilder<ProjectJoinVO> prjIdSearch;
+    private final SearchBuilder<ProjectJoinVO> prjIdSearch;
 
     protected ProjectJoinDaoImpl() {
 


Mime
View raw message