Return-Path: X-Original-To: apmail-incubator-cloudstack-commits-archive@minotaur.apache.org Delivered-To: apmail-incubator-cloudstack-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 1BF73E199 for ; Thu, 10 Jan 2013 22:47:28 +0000 (UTC) Received: (qmail 37515 invoked by uid 500); 10 Jan 2013 22:47:21 -0000 Delivered-To: apmail-incubator-cloudstack-commits-archive@incubator.apache.org Received: (qmail 37480 invoked by uid 500); 10 Jan 2013 22:47:21 -0000 Mailing-List: contact cloudstack-commits-help@incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: cloudstack-dev@incubator.apache.org Delivered-To: mailing list cloudstack-commits@incubator.apache.org Received: (qmail 37427 invoked by uid 99); 10 Jan 2013 22:47:21 -0000 Received: from tyr.zones.apache.org (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Thu, 10 Jan 2013 22:47:21 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id 3B70217B5F; Thu, 10 Jan 2013 22:47:21 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: ahuang@apache.org To: cloudstack-commits@incubator.apache.org X-Mailer: ASF-Git Admin Mailer Subject: [3/25] removed componentlocator and inject Message-Id: <20130110224721.3B70217B5F@tyr.zones.apache.org> Date: Thu, 10 Jan 2013 22:47:20 +0000 (UTC) http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/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..9b1afb2 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -24,76 +24,69 @@ 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.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.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; + @Inject ConfigurationDao _configDao = null; - Map> _daoNameMap = new HashMap>(); - // singleton class - private static ApiDispatcher s_instance = ApiDispatcher.getInstance(); - - public static ApiDispatcher getInstance() { - if (s_instance == null) { - s_instance = ComponentLocator.inject(ApiDispatcher.class); - } - return s_instance; - } + private static ApiDispatcher s_instance; protected ApiDispatcher() { super(); - _locator = ComponentLocator.getLocator(ManagementServer.Name); - ConfigurationDao configDao = _locator.getDao(ConfigurationDao.class); - Map configs = configDao.getConfiguration(); + Map configs = _configDao.getConfiguration(); String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key()); if (strSnapshotLimit != null) { Long snapshotLimit = NumbersUtil.parseLong(strSnapshotLimit, 1L); @@ -104,12 +97,11 @@ public class ApiDispatcher { _createSnapshotQueueSizeLimit = snapshotLimit; } } - _daoNameMap.put("com.cloud.network.Network", NetworkDao.class); - _daoNameMap.put("com.cloud.template.VirtualMachineTemplate", VMTemplateDao.class); + s_instance = this; } public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map params) { - processParameters(cmd, params); + processParameters(cmd, params); try { UserContext ctx = UserContext.current(); @@ -206,113 +198,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 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 idList = ref.getIdProxyList(); + ArrayList 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 idList = ref.getIdProxyList(); + ArrayList 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 idList = ref.getIdProxyList(); + ArrayList 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 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 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 +315,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 params) { + public static void processParameters(BaseCmd cmd, Map params) { List entitiesToAccess = new ArrayList(); Map unpackedParams = cmd.unpackParams(params); @@ -348,7 +340,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 +391,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 +418,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 listParam = (List) 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 listParam = (List) field.get(cmd); + for (Long entityId : listParam) { + Object entityObj = s_instance._entityMgr.findById(entity, entityId); + entitiesToAccess.add(entityObj); + } + break; /* * case STRING: List listParam = * new ArrayList(); listParam = @@ -448,17 +440,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,17 +466,17 @@ 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]"); + } } @@ -533,7 +525,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 +590,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 +598,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 +611,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 +637,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,30 +678,26 @@ 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]"); + } + } - 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); } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/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..4e2355e 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; @@ -97,15 +98,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 +114,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; @@ -137,7 +135,7 @@ public class QueryManagerImpl implements QueryService, Manager { private String _name; - // public static ViewResponseHelper _responseGenerator; + // public static ViewResponseHelper _responseGenerator; @Inject private AccountManager _accountMgr; @@ -214,7 +212,7 @@ public class QueryManagerImpl implements QueryService, Manager { @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; - // _responseGenerator = new ViewResponseHelper(); + // _responseGenerator = new ViewResponseHelper(); return false; } @@ -717,7 +715,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 +881,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 +972,10 @@ public class QueryManagerImpl implements QueryService, Manager { //Filter searchFilter = new Filter(DomainRouterJoinVO.class, null, true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder 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 +1093,7 @@ public class QueryManagerImpl implements QueryService, Manager { Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize); SearchBuilder 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 +1300,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 +1544,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/f40e7b75/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java index 1ce9b33..54c276d 100755 --- a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java @@ -81,7 +81,7 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; @@ -181,7 +181,7 @@ public class BareMetalVmManagerImpl extends UserVmManagerImpl implements BareMet * prepare() will check if current account has right for creating * template */ - TemplateAdapter adapter = Adapters.getAdapterByName(_adapters, TemplateAdapterType.BareMetal.getName()); + TemplateAdapter adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.BareMetal.getName()); Long userId = UserContext.current().getCallerUserId(); userId = (userId == null ? User.UID_SYSTEM : userId); AccountVO account = _accountDao.findById(vm.getAccountId()); http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/server/src/com/cloud/baremetal/PxeServerManagerImpl.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/baremetal/PxeServerManagerImpl.java b/server/src/com/cloud/baremetal/PxeServerManagerImpl.java index 6e123af..7a9a783 100755 --- a/server/src/com/cloud/baremetal/PxeServerManagerImpl.java +++ b/server/src/com/cloud/baremetal/PxeServerManagerImpl.java @@ -41,7 +41,7 @@ import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; import com.cloud.uservm.UserVm; -import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.AdapterBase; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.ReservationContext; import com.cloud.vm.UserVmVO; @@ -87,7 +87,7 @@ public class PxeServerManagerImpl implements PxeServerManager, ResourceStateAdap protected PxeServerService getServiceByType(String type) { PxeServerService _service; - _service = Adapters.getAdapterByName(_services, type); + _service = AdapterBase.getAdapterByName(_services, type); if (_service == null) { throw new CloudRuntimeException("Cannot find PXE service for " + type); } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/server/src/com/cloud/configuration/ConfigurationManagerImpl.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index bb943c9..a8c1743 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -39,30 +39,32 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; +import org.apache.cloudstack.acl.SecurityChecker; +import org.apache.cloudstack.api.ApiConstants.LDAPParams; import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd; import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd; import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd; -import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd; import org.apache.cloudstack.api.command.admin.offering.CreateDiskOfferingCmd; -import org.apache.cloudstack.api.command.admin.offering.*; +import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.UpdateDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.UpdateServiceOfferingCmd; import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd; import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd; import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd; import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd; import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd; -import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; -import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd; -import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import org.apache.cloudstack.acl.SecurityChecker; import com.cloud.alert.AlertManager; -import org.apache.cloudstack.api.ApiConstants.LDAPParams; import com.cloud.api.ApiDBUtils; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.Resource.ResourceType; @@ -153,8 +155,6 @@ import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.utils.NumbersUtil; import com.cloud.utils.StringUtils; -import com.cloud.utils.component.Adapters; -import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; @@ -216,7 +216,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // @com.cloud.utils.component.Inject(adapter = SecurityChecker.class) @Inject List _secChecker; - + @Inject CapacityDao _capacityDao; @Inject @@ -438,7 +438,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String name = cmd.getCfgName(); String value = cmd.getValue(); UserContext.current().setEventDetails(" Name: " + name + " New Value: " + (((name.toLowerCase()).contains("password")) ? "*****" : - (((value == null) ? "" : value)))); + (((value == null) ? "" : value)))); // check if config value exists ConfigurationVO config = _configDao.findByName(name); if (config == null) { @@ -1454,9 +1454,9 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (internalDns2 == null) { - internalDns2 = zone.getInternalDns2(); + internalDns2 = zone.getInternalDns2(); } - + if (guestCidr == null) { guestCidr = zone.getGuestNetworkCidr(); } @@ -1915,8 +1915,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String description = cmd.getDisplayText(); Long numGibibytes = cmd.getDiskSize(); boolean isCustomized = cmd.isCustomized() != null ? cmd.isCustomized() : false; // false - // by - // default + // by + // default String tags = cmd.getTags(); // Long domainId = cmd.getDomainId() != null ? cmd.getDomainId() : // Long.valueOf(DomainVO.ROOT_DOMAIN); // disk offering @@ -2106,7 +2106,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura physicalNetworkId = network.getPhysicalNetworkId(); } } - + // Verify that zone exists DataCenterVO zone = _zoneDao.findById(zoneId); if (zone == null) { @@ -2148,8 +2148,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } } - - + + // Check if zone is enabled Account caller = UserContext.current().getCaller(); if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { @@ -2234,7 +2234,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura //check resource limits _resourceLimitMgr.checkResourceLimit(vlanOwner, ResourceType.public_ip, accountIpRange); - + associateIpRangeToAccount = true; } } @@ -2272,24 +2272,24 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId, boolean forVirtualNetwork, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, String vlanId, Account vlanOwner) { - - + + Network network = _networkMgr.getNetwork(networkId); - + //Validate the zone DataCenterVO zone = _zoneDao.findById(zoneId); if (zone == null) { throw new InvalidParameterValueException("Please specify a valid zone."); } - + // ACL check checkZoneAccess(UserContext.current().getCaller(), zone); - + //Validate the physical network if (_physicalNetworkDao.findById(physicalNetworkId) == null) { throw new InvalidParameterValueException("Please specify a valid physical network id"); } - + //Validate the pod if (podId != null) { Pod pod = _podDao.findById(podId); @@ -2302,10 +2302,10 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura //pod vlans can be created in basic zone only if (zone.getNetworkType() != NetworkType.Basic || network.getTrafficType() != TrafficType.Guest) { throw new InvalidParameterValueException("Pod id can be specified only for the networks of type " - + TrafficType.Guest + " in zone of type " + NetworkType.Basic); + + TrafficType.Guest + " in zone of type " + NetworkType.Basic); } } - + //1) if vlan is specified for the guest network range, it should be the same as network's vlan //2) if vlan is missing, default it to the guest network's vlan if (network.getTrafficType() == TrafficType.Guest) { @@ -2315,7 +2315,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String[] vlan = uri.toString().split("vlan:\\/\\/"); networkVlanId = vlan[1]; } - + if (vlanId != null) { // if vlan is specified, throw an error if it's not equal to network's vlanId if (networkVlanId != null && !networkVlanId.equalsIgnoreCase(vlanId)) { @@ -2328,14 +2328,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura //vlan id is required for public network throw new InvalidParameterValueException("Vlan id is required when add ip range to the public network"); } - + if (vlanId == null) { vlanId = Vlan.UNTAGGED; } VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; - - + + if (vlanOwner != null && zone.getNetworkType() != NetworkType.Advanced) { throw new InvalidParameterValueException("Vlan owner can be defined only in the zone of type " + NetworkType.Advanced); } @@ -2484,7 +2484,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (vlan == null) { throw new InvalidParameterValueException("Please specify a valid IP range id."); } - + boolean isAccountSpecific = false; List acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlan.getId()); // Check for account wide pool. It will have an entry for account_vlan_map. @@ -2502,25 +2502,25 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (vlan == null) { throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId); } - + if (s_logger.isDebugEnabled()) { s_logger.debug("lock vlan " + vlanDbId + " is acquired"); } - + List ips = _publicIpAddressDao.listByVlanId(vlanDbId); - + for (IPAddressVO ip : ips) { if (ip.isOneToOneNat()) { throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is used for static nat purposes. Cleanup the rules first"); } - + if (ip.isSourceNat() && _networkMgr.getNetwork(ip.getAssociatedWithNetworkId()) != null) { throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() + ". IP range with the source nat ip address can be removed either as a part of Network, or account removal"); } - + if (_firewallDao.countRulesByIpId(ip.getId()) > 0) { throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range has firewall rules applied. Cleanup the rules first"); @@ -2613,7 +2613,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura return true; } - + @DB protected boolean savePublicIPRange(String startIP, String endIP, long zoneId, long vlanDbId, long sourceNetworkid, long physicalNetworkId) { @@ -2816,7 +2816,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - + private boolean validPod(long podId) { return (_podDao.findById(podId) != null); } @@ -3021,7 +3021,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // in Acton, don't allow to specify more than 1 provider per service if (svcPrv.get(serviceStr) != null && svcPrv.get(serviceStr).size() > 1) { throw new InvalidParameterValueException("In the current release only one provider can be " + - "specified for the service"); + "specified for the service"); } for (String prvNameStr : svcPrv.get(serviceStr)) { // check if provider is supported @@ -3033,7 +3033,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (provider == Provider.JuniperSRX) { firewallProvider = Provider.JuniperSRX; } - + if ((service == Service.PortForwarding || service == Service.StaticNat) && provider == Provider.VirtualRouter){ firewallProvider = Provider.VirtualRouter; } @@ -3053,7 +3053,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura serviceProviderMap.put(service, providers); } else { throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network " + - "offering, can't add a provider to it"); + "offering, can't add a provider to it"); } } } @@ -3202,7 +3202,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String multicastRateStr = _configDao.getValue("multicast.throttling.rate"); int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr)); tags = cleanupTags(tags); - + if (specifyVlan != specifyIpRanges) { throw new InvalidParameterValueException("SpecifyVlan should be equal to specifyIpRanges which is " + specifyIpRanges); } @@ -3211,11 +3211,11 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!specifyVlan && type == GuestType.Shared) { throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type); } - + //specifyIpRanges should always be false for Isolated offering with Source nat service enabled if (specifyVlan && type == GuestType.Isolated && serviceProviderMap.containsKey(Service.SourceNat)) { throw new InvalidParameterValueException("SpecifyVlan should be false if the network offering type is " - + type + " and service " + Service.SourceNat.getName() + " is supported"); + + type + " and service " + Service.SourceNat.getName() + " is supported"); } // validate availability value @@ -3235,7 +3235,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } } - + boolean dedicatedLb = false; boolean elasticLb = false; boolean sharedSourceNat = false; @@ -3245,7 +3245,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura boolean inline = false; if (serviceCapabilityMap != null && !serviceCapabilityMap.isEmpty()) { Map lbServiceCapabilityMap = serviceCapabilityMap.get(Service.Lb); - + if ((lbServiceCapabilityMap != null) && (!lbServiceCapabilityMap.isEmpty())) { String isolationCapability = lbServiceCapabilityMap.get(Capability.SupportedLBIsolation); if (isolationCapability != null) { @@ -3259,7 +3259,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (param != null) { elasticLb = param.contains("true"); } - + String inlineMode = lbServiceCapabilityMap.get(Capability.InlineMode); if (inlineMode != null) { _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.InlineMode, inlineMode); @@ -3326,7 +3326,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura _ntwkOffServiceMapDao.persist(offService); s_logger.trace("Added service for the network offering: " + offService + " with provider " + provider.getName()); } - + if (vpcOff) { List supportedSvcs = new ArrayList(); supportedSvcs.addAll(serviceProviderMap.keySet()); @@ -3547,7 +3547,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (sourceNatSupported != null) { addOffering = addOffering && (_networkMgr.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported); } - + if (forVpc != null) { addOffering = addOffering && (isOfferingForVpc(offering) == forVpc.booleanValue()); } else if (network != null){ @@ -3666,14 +3666,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura } if (availability == null) { throw new InvalidParameterValueException("Invalid value for Availability. Supported types: " - + Availability.Required + ", " + Availability.Optional); + + Availability.Required + ", " + Availability.Optional); } else { if (availability == NetworkOffering.Availability.Required) { boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkMgr.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat)); if (!canOffBeRequired) { throw new InvalidParameterValueException("Availability can be " + - NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled"); } @@ -3681,7 +3681,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura List offerings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (!offerings.isEmpty() && offerings.get(0).getId() != offeringToUpdate.getId()) { throw new InvalidParameterValueException("System already has network offering id=" + - offerings.get(0).getId() + " with availability " + Availability.Required); + offerings.get(0).getId() + " with availability " + Availability.Required); } } offering.setAvailability(availability); @@ -3697,12 +3697,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Override @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE, eventDescription = "Marking account with the " + - "default zone", async=true) + "default zone", async=true) public AccountVO markDefaultZone(String accountName, long domainId, long defaultZoneId) { - - // Check if the account exists - Account account = _accountDao.findEnabledAccount(accountName, domainId); - if (account == null) { + + // Check if the account exists + Account account = _accountDao.findEnabledAccount(accountName, domainId); + if (account == null) { s_logger.error("Unable to find account by name: " + accountName + " in domain " + domainId); throw new InvalidParameterValueException("Account by name: " + accountName + " doesn't exist in domain " + domainId); } @@ -3710,20 +3710,20 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura // Don't allow modification of system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new InvalidParameterValueException("Can not modify system account"); - } - - AccountVO acctForUpdate = _accountDao.findById(account.getId()); - - acctForUpdate.setDefaultZoneId(defaultZoneId); - - if (_accountDao.update(account.getId(), acctForUpdate)) { - UserContext.current().setEventDetails("Default zone id= " + defaultZoneId); - return _accountDao.findById(account.getId()); - } else { - return null; - } - } - + } + + AccountVO acctForUpdate = _accountDao.findById(account.getId()); + + acctForUpdate.setDefaultZoneId(defaultZoneId); + + if (_accountDao.update(account.getId(), acctForUpdate)) { + UserContext.current().setEventDetails("Default zone id= " + defaultZoneId); + return _accountDao.findById(account.getId()); + } else { + return null; + } + } + // Note: This method will be used for entity name validations in the coming // releases (place holder for now) private void validateEntityName(String str) { @@ -3851,31 +3851,31 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura public ClusterVO getCluster(long id) { return _clusterDao.findById(id); } - + @Override public AllocationState findClusterAllocationState(ClusterVO cluster){ - - if(cluster.getAllocationState() == AllocationState.Disabled){ - return AllocationState.Disabled; - }else if(ApiDBUtils.findPodById(cluster.getPodId()).getAllocationState() == AllocationState.Disabled){ - return AllocationState.Disabled; - }else { - DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); - return zone.getAllocationState(); - } + + if(cluster.getAllocationState() == AllocationState.Disabled){ + return AllocationState.Disabled; + }else if(ApiDBUtils.findPodById(cluster.getPodId()).getAllocationState() == AllocationState.Disabled){ + return AllocationState.Disabled; + }else { + DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); + return zone.getAllocationState(); + } } @Override public AllocationState findPodAllocationState(HostPodVO pod){ - - if(pod.getAllocationState() == AllocationState.Disabled){ - return AllocationState.Disabled; - }else { - DataCenterVO zone = ApiDBUtils.findZoneById(pod.getDataCenterId()); - return zone.getAllocationState(); - } - } - + + if(pod.getAllocationState() == AllocationState.Disabled){ + return AllocationState.Disabled; + }else { + DataCenterVO zone = ApiDBUtils.findZoneById(pod.getDataCenterId()); + return zone.getAllocationState(); + } + } + private boolean allowIpRangeOverlap(VlanVO vlan, boolean forVirtualNetwork, long networkId) { // FIXME - delete restriction for virtual network in the future if (vlan.getVlanType() == VlanType.DirectAttached && !forVirtualNetwork) { http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/server/src/com/cloud/network/NetworkManagerImpl.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 5b8109f..b6f69d1 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -64,12 +64,7 @@ import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.*; import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.Pod; -import com.cloud.dc.PodVlanMapVO; -import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; -import com.cloud.dc.VlanVO; import com.cloud.dc.dao.AccountVlanMapDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.PodVlanMapDao; @@ -112,13 +107,6 @@ import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; import com.cloud.network.lb.LoadBalancingRulesManager; import com.cloud.network.rules.*; import com.cloud.network.rules.FirewallRule.Purpose; -import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.PortForwardingRuleVO; -import com.cloud.network.rules.RulesManager; -import com.cloud.network.rules.StaticNat; -import com.cloud.network.rules.StaticNatRule; -import com.cloud.network.rules.StaticNatRuleImpl; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.vpc.NetworkACLManager; import com.cloud.network.vpc.PrivateIpVO; @@ -143,7 +131,7 @@ import com.cloud.user.dao.UserStatisticsDao; import com.cloud.utils.AnnotationHelper; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.JoinBuilder.JoinType; @@ -306,7 +294,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public NetworkElement getElementImplementingProvider(String providerName) { String elementName = s_providerToNetworkElementMap.get(providerName); - NetworkElement element = Adapters.getAdapterByName(_networkElements, elementName); + NetworkElement element = AdapterBase.getAdapterByName(_networkElements, elementName); return element; } @@ -1813,7 +1801,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO ntwkVO = _networksDao.findById(network.getId()); s_logger.debug("Allocating nic for vm " + vm.getVirtualMachine() + " in network " + network + " with requested profile " + requested); - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, ntwkVO.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, ntwkVO.getGuruName()); if (requested != null && requested.getMode() == null) { requested.setMode(network.getMode()); @@ -1958,7 +1946,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } try { - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); Network.State state = network.getState(); if (state == Network.State.Implemented || state == Network.State.Implementing) { s_logger.debug("Network id=" + networkId + " is already implemented"); @@ -2165,7 +2153,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { Integer networkRate = getNetworkRate(network.getId(), vmProfile.getId()); - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); NicVO nic = _nicDao.findById(nicId); NicProfile profile = null; @@ -2227,7 +2215,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO network = _networksDao.findById(nic.getNetworkId()); Integer networkRate = getNetworkRate(network.getId(), vm.getId()); - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); guru.updateNicProfile(profile, network); @@ -2271,7 +2259,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (originalState == Nic.State.Reserved || originalState == Nic.State.Reserving) { if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); nic.setState(Nic.State.Releasing); _nicDao.update(nic.getId(), nic); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, @@ -2321,7 +2309,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO network = _networksDao.findById(nic.getNetworkId()); Integer networkRate = getNetworkRate(network.getId(), vm.getId()); - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); guru.updateNicProfile(profile, network); @@ -2342,7 +2330,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO network = _networksDao.findById(networkId); Integer networkRate = getNetworkRate(network.getId(), vm.getId()); - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); guru.updateNicProfile(profile, network); @@ -2497,7 +2485,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag NetworkVO network = _networksDao.findById(nic.getNetworkId()); NicProfile profile = new NicProfile(nic, network, null, null, null, isSecurityGroupSupportedInNetwork(network), getNetworkTag(vm.getHypervisorType(), network)); - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); guru.deallocate(network, profile, vm); _nicDao.remove(nic.getId()); s_logger.debug("Removed nic id=" + nic.getId()); @@ -3560,7 +3548,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Network id=" + networkId + " is shutdown successfully, cleaning up corresponding resources now."); } - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); NetworkProfile profile = convertNetworkToNetworkProfile(network.getId()); guru.shutdown(profile, _networkOfferingDao.findById(network.getNetworkOfferingId())); @@ -3726,7 +3714,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Network id=" + networkId + " is destroyed successfully, cleaning up corresponding resources now."); } - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); Account owner = _accountMgr.getAccount(network.getAccountId()); Transaction txn = Transaction.currentTxn(); @@ -4429,7 +4417,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag @Override public NetworkProfile convertNetworkToNetworkProfile(long networkId) { NetworkVO network = _networksDao.findById(networkId); - NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); + NetworkGuru guru = AdapterBase.getAdapterByName(_networkGurus, network.getGuruName()); NetworkProfile profile = new NetworkProfile(network); guru.updateNetworkProfile(profile); http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/server/src/com/cloud/servlet/CloudStartupServlet.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/servlet/CloudStartupServlet.java b/server/src/com/cloud/servlet/CloudStartupServlet.java index de133ab..4b66291 100755 --- a/server/src/com/cloud/servlet/CloudStartupServlet.java +++ b/server/src/com/cloud/servlet/CloudStartupServlet.java @@ -45,11 +45,11 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi initLog4j(); // Save Configuration Values - ConfigurationServer c = ComponentContext.getCompanent(ConfigurationServer.class); + ConfigurationServer c = ComponentContext.getComponent(ConfigurationServer.class); try { c.persistDefaultValues(); - ManagementServer ms = ComponentContext.getCompanent(ManagementServer.class); + ManagementServer ms = ComponentContext.getComponent(ManagementServer.class); ms.startup(); ms.enableAdminUser("password"); ApiServer.initApiServer(ms.getPropertiesFiles()); http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/server/src/com/cloud/template/TemplateManagerImpl.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index 0e91472..0c20853 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -130,7 +130,7 @@ import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -216,10 +216,10 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe private TemplateAdapter getAdapter(HypervisorType type) { TemplateAdapter adapter = null; if (type == HypervisorType.BareMetal) { - adapter = Adapters.getAdapterByName(_adapters, TemplateAdapterType.BareMetal.getName()); + adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.BareMetal.getName()); } else { // see HyervisorTemplateAdapter - adapter = Adapters.getAdapterByName(_adapters, TemplateAdapterType.Hypervisor.getName()); + adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.Hypervisor.getName()); } if (adapter == null) { http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/f40e7b75/server/test/com/cloud/async/TestAsyncJobManager.java ---------------------------------------------------------------------- diff --git a/server/test/com/cloud/async/TestAsyncJobManager.java b/server/test/com/cloud/async/TestAsyncJobManager.java index 8ce51fa..d45ca4d 100644 --- a/server/test/com/cloud/async/TestAsyncJobManager.java +++ b/server/test/com/cloud/async/TestAsyncJobManager.java @@ -20,7 +20,10 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import javax.inject.Inject; + import junit.framework.Assert; +import junit.framework.TestCase; import org.apache.log4j.Logger; @@ -31,102 +34,99 @@ import com.cloud.exception.PermissionDeniedException; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDaoImpl; -import com.cloud.server.ManagementServer; -import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.Transaction; -import com.cloud.utils.testcase.ComponentSetup; -import com.cloud.utils.testcase.ComponentTestCase; -@ComponentSetup(managerName="management-server", setupXml="async-job-component.xml") -public class TestAsyncJobManager extends ComponentTestCase { +public class TestAsyncJobManager extends TestCase { public static final Logger s_logger = Logger.getLogger(TestAsyncJobManager.class.getName()); - + volatile long s_count = 0; - public void asyncCall() { - AsyncJobManager asyncMgr = ComponentLocator.getLocator(ManagementServer.Name).getManager(AsyncJobManager.class); + @Inject AsyncJobManager asyncMgr; + public void asyncCall() { // long jobId = mgr.rebootVirtualMachineAsync(1, 1); long jobId = 0L; - s_logger.info("Async-call job id: " + jobId); - - while(true) { - AsyncJobResult result; - try { - result = asyncMgr.queryAsyncJobResult(jobId); - - if(result.getJobStatus() != AsyncJobResult.STATUS_IN_PROGRESS) { - s_logger.info("Async-call completed, result: " + result.toString()); - break; - } - s_logger.info("Async-call is in progress, progress: " + result.toString()); - - } catch (PermissionDeniedException e1) { - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - } - - public void sequence() { - final HostDao hostDao = new HostDaoImpl(); - long seq = hostDao.getNextSequence(1); - s_logger.info("******* seq : " + seq + " ********"); - - HashMap hashMap = new HashMap(); - final Map map = Collections.synchronizedMap(hashMap); - - s_count = 0; - final long maxCount = 1000000; // test one million times - - Thread t1 = new Thread(new Runnable() { - public void run() { - while(s_count < maxCount) { - s_count++; - long seq = hostDao.getNextSequence(1); - Assert.assertTrue(map.put(seq, seq) == null); - } - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - while(s_count < maxCount) { - s_count++; - long seq = hostDao.getNextSequence(1); - Assert.assertTrue(map.put(seq, seq) == null); - } - } - }); - - t1.start(); - t2.start(); - - try { - t1.join(); - t2.join(); - } catch (InterruptedException e) { - } - } + s_logger.info("Async-call job id: " + jobId); + + while(true) { + AsyncJobResult result; + try { + result = asyncMgr.queryAsyncJobResult(jobId); + + if(result.getJobStatus() != AsyncJobResult.STATUS_IN_PROGRESS) { + s_logger.info("Async-call completed, result: " + result.toString()); + break; + } + s_logger.info("Async-call is in progress, progress: " + result.toString()); + + } catch (PermissionDeniedException e1) { + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } + } + + public void sequence() { + final HostDao hostDao = new HostDaoImpl(); + long seq = hostDao.getNextSequence(1); + s_logger.info("******* seq : " + seq + " ********"); + + HashMap hashMap = new HashMap(); + final Map map = Collections.synchronizedMap(hashMap); + + s_count = 0; + final long maxCount = 1000000; // test one million times + + Thread t1 = new Thread(new Runnable() { + @Override + public void run() { + while(s_count < maxCount) { + s_count++; + long seq = hostDao.getNextSequence(1); + Assert.assertTrue(map.put(seq, seq) == null); + } + } + }); - /* + Thread t2 = new Thread(new Runnable() { + @Override + public void run() { + while(s_count < maxCount) { + s_count++; + long seq = hostDao.getNextSequence(1); + Assert.assertTrue(map.put(seq, seq) == null); + } + } + }); + + t1.start(); + t2.start(); + + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + } + } + + /* public void ipAssignment() { final IPAddressDao ipAddressDao = new IPAddressDaoImpl(); - + final ConcurrentHashMap map = new ConcurrentHashMap(); //final Map map = Collections.synchronizedMap(hashMap); - + s_count = 0; final long maxCount = 1000000; // test one million times - + Thread t1 = new Thread(new Runnable() { public void run() { while(s_count < maxCount) { s_count++; - + Transaction txn = Transaction.open("Alex1"); try { IPAddressVO addr = ipAddressDao.assignIpAddress(1, 0, 1, false); @@ -141,12 +141,12 @@ public class TestAsyncJobManager extends ComponentTestCase { } } }); - + Thread t2 = new Thread(new Runnable() { public void run() { while(s_count < maxCount) { s_count++; - + Transaction txn = Transaction.open("Alex2"); try { IPAddressVO addr = ipAddressDao.assignIpAddress(1, 0, 1, false); @@ -157,96 +157,97 @@ public class TestAsyncJobManager extends ComponentTestCase { } } }); - + t1.start(); t2.start(); - + try { t1.join(); t2.join(); } catch (InterruptedException e) { } } - */ - - private long getRandomLockId() { - return 1L; - - /* - * will use in the future test cases + */ + + private long getRandomLockId() { + return 1L; + + /* + * will use in the future test cases int i = new Random().nextInt(); if(i % 2 == 0) return 1L; return 2L; - */ - } - - public void tstLocking() { - - int testThreads = 20; - Thread[] threads = new Thread[testThreads]; - - for(int i = 0; i < testThreads; i++) { - final int current = i; - threads[i] = new Thread(new Runnable() { - public void run() { - - final HostDao hostDao = new HostDaoImpl(); - while(true) { - Transaction txn = Transaction.currentTxn(); - try { - HostVO host = hostDao.acquireInLockTable(getRandomLockId(), 10); - if(host != null) { - s_logger.info("Thread " + (current + 1) + " acquired lock"); - - try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} - - s_logger.info("Thread " + (current + 1) + " released lock"); - hostDao.releaseFromLockTable(host.getId()); - - try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} - } else { - s_logger.info("Thread " + (current + 1) + " is not able to acquire lock"); - } - } finally { - txn.close(); - } - } - } - }); - threads[i].start(); - } - - try { - for(int i = 0; i < testThreads; i++) - threads[i].join(); - } catch(InterruptedException e) { - } - } - - public void testDomain() { - getRandomMilliseconds(1, 100); - DomainDao domainDao = new DomainDaoImpl(); - - DomainVO domain1 = new DomainVO("d1", 2L, 1L, null); - domainDao.create(domain1); - - DomainVO domain2 = new DomainVO("d2", 2L, 1L, null); - domainDao.create(domain2); - - DomainVO domain3 = new DomainVO("d3", 2L, 1L, null); - domainDao.create(domain3); - - DomainVO domain11 = new DomainVO("d11", 2L, domain1.getId(), null); - domainDao.create(domain11); - - domainDao.remove(domain11.getId()); - - DomainVO domain12 = new DomainVO("d12", 2L, domain1.getId(), null); - domainDao.create(domain12); - - domainDao.remove(domain3.getId()); - DomainVO domain4 = new DomainVO("d4", 2L, 1L, null); - domainDao.create(domain4); - } + */ + } + + public void tstLocking() { + + int testThreads = 20; + Thread[] threads = new Thread[testThreads]; + + for(int i = 0; i < testThreads; i++) { + final int current = i; + threads[i] = new Thread(new Runnable() { + @Override + public void run() { + + final HostDao hostDao = new HostDaoImpl(); + while(true) { + Transaction txn = Transaction.currentTxn(); + try { + HostVO host = hostDao.acquireInLockTable(getRandomLockId(), 10); + if(host != null) { + s_logger.info("Thread " + (current + 1) + " acquired lock"); + + try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} + + s_logger.info("Thread " + (current + 1) + " released lock"); + hostDao.releaseFromLockTable(host.getId()); + + try { Thread.sleep(getRandomMilliseconds(1000, 5000)); } catch (InterruptedException e) {} + } else { + s_logger.info("Thread " + (current + 1) + " is not able to acquire lock"); + } + } finally { + txn.close(); + } + } + } + }); + threads[i].start(); + } + + try { + for(int i = 0; i < testThreads; i++) + threads[i].join(); + } catch(InterruptedException e) { + } + } + + public void testDomain() { + getRandomMilliseconds(1, 100); + DomainDao domainDao = new DomainDaoImpl(); + + DomainVO domain1 = new DomainVO("d1", 2L, 1L, null); + domainDao.create(domain1); + + DomainVO domain2 = new DomainVO("d2", 2L, 1L, null); + domainDao.create(domain2); + + DomainVO domain3 = new DomainVO("d3", 2L, 1L, null); + domainDao.create(domain3); + + DomainVO domain11 = new DomainVO("d11", 2L, domain1.getId(), null); + domainDao.create(domain11); + + domainDao.remove(domain11.getId()); + + DomainVO domain12 = new DomainVO("d12", 2L, domain1.getId(), null); + domainDao.create(domain12); + + domainDao.remove(domain3.getId()); + DomainVO domain4 = new DomainVO("d4", 2L, 1L, null); + domainDao.create(domain4); + } }