diff --git a/api/src/com/cloud/api/commands/CreateProjectCmd.java b/api/src/com/cloud/api/commands/CreateProjectCmd.java index 0334d195f82..4b8606e4f4f 100644 --- a/api/src/com/cloud/api/commands/CreateProjectCmd.java +++ b/api/src/com/cloud/api/commands/CreateProjectCmd.java @@ -35,37 +35,37 @@ import com.cloud.projects.Project; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates a project", responseObject=ProjectResponse.class, since="3.0.0") +@Implementation(description = "Creates a project", responseObject = ProjectResponse.class, since = "3.0.0") public class CreateProjectCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateProjectCmd.class.getName()); private static final String s_name = "createprojectresponse"; - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will be Admin for the project") + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account who will be Admin for the project") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a project") + @IdentityMapper(entityTableName = "domain") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "domain ID of the account owning a project") private Long domainId; - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="name of the project") + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the project") private String name; - @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="display text of the project") + @Parameter(name = ApiConstants.DISPLAY_TEXT, type = CommandType.STRING, required = true, description = "display text of the project") private String displayText; - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public String getEntityTable() { - return "projects"; + return "projects"; } - + public String getAccountName() { if (accountName != null) { return accountName; @@ -80,7 +80,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { } else { return UserContext.current().getCaller().getDomainId(); } - + } public String getName() { @@ -95,29 +95,28 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account caller = UserContext.current().getCaller(); - + if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) { throw new InvalidParameterValueException("Account name and domain id must be specified together"); } - + if (accountName != null) { return _accountService.finalizeOwner(caller, accountName, domainId, null).getId(); } - + return caller.getId(); } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// @Override - public void execute(){ + public void execute() { Project project = _projectService.enableProject(this.getEntityId()); if (project != null) { ProjectResponse response = _responseGenerator.createProjectResponse(project); @@ -127,10 +126,10 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project"); } } - + @Override - public void create() throws ResourceAllocationException{ - UserContext.current().setEventDetails("Project Name: "+ getName()); + public void create() throws ResourceAllocationException { + UserContext.current().setEventDetails("Project Name: " + getName()); Project project = _projectService.createProject(getName(), getDisplayText(), getAccountName(), getDomainId()); if (project != null) { this.setEntityId(project.getId()); @@ -138,14 +137,15 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_CREATE; } - + @Override public String getEventDescription() { return "creating project"; } + } \ No newline at end of file diff --git a/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java b/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java index d9a00092347..cc6fa318a59 100644 --- a/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java +++ b/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java @@ -31,42 +31,42 @@ import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Accepts or declines project invitation", responseObject=SuccessResponse.class, since="3.0.0") +@Implementation(description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") public class DeleteProjectInvitationCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteProjectInvitationCmd.class.getName()); private static final String s_name = "deleteprojectinvitationresponse"; - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="project_invitations") - @Parameter(name=ApiConstants.ID, required=true, type=CommandType.LONG, description="id of the invitation") + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + @IdentityMapper(entityTableName = "project_invitations") + @Parameter(name = ApiConstants.ID, required = true, type = CommandType.LONG, description = "id of the invitation") private Long id; - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public Long getId() { return id; } - + @Override public String getCommandName() { return s_name; } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// @Override public long getEntityOwnerId() { - //TODO - return project entity ownerId - return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + // TODO - return project entity ownerId + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are +// tracked } - @Override - public void execute(){ + public void execute() { UserContext.current().setEventDetails("Project invitation id " + id); boolean result = _projectService.deleteProjectInvitation(id); if (result) { @@ -76,14 +76,15 @@ public class DeleteProjectInvitationCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete the project invitation"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_INVITATION_REMOVE; } - + @Override public String getEventDescription() { - return "Project invitatino id " + id + " is being removed"; + return "Project invitatino id " + id + " is being removed"; } + } diff --git a/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java b/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java index d36159efda6..d3d9e5f8c6a 100644 --- a/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java +++ b/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java @@ -31,30 +31,31 @@ import com.cloud.api.response.ListResponse; import com.cloud.api.response.ProjectInvitationResponse; import com.cloud.projects.ProjectInvitation; -@Implementation(description="Lists projects and provides detailed information for listed projects", responseObject=ProjectInvitationResponse.class, since="3.0.0") +@Implementation(description = "Lists projects and provides detailed information for listed projects", responseObject = ProjectInvitationResponse.class, since = "3.0.0") public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListProjectInvitationsCmd.class.getName()); private static final String s_name = "listprojectinvitationsresponse"; - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="list by project id") + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + @IdentityMapper(entityTableName = "projects") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "list by project id") private Long projectId; - - @Parameter(name=ApiConstants.ACTIVE_ONLY, type=CommandType.BOOLEAN, description="if true, list only active invitations - having Pending state and ones that are not timed out yet") + + @Parameter(name = ApiConstants.ACTIVE_ONLY, type = CommandType.BOOLEAN, description = "if true, list only active invitations - having Pending state and ones that are not timed out yet") private boolean activeOnly; - - @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list invitations by state") + + @Parameter(name = ApiConstants.STATE, type = CommandType.STRING, description = "list invitations by state") private String state; - - @IdentityMapper(entityTableName="project_invitations") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list invitations by id") + + @IdentityMapper(entityTableName = "project_invitations") + @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "list invitations by id") private Long id; - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public Long getProjectId() { return projectId; } @@ -66,7 +67,7 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { public String getState() { return state; } - + public Long getId() { return id; } @@ -75,14 +76,15 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { public String getCommandName() { return s_name; } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// @Override - public void execute(){ - List invites = _projectService.listProjectInvitations(id, projectId, this.getAccountName(), this.getDomainId(), state, activeOnly, this.getStartIndex(), this.getPageSizeVal(), this.isRecursive(), this.listAll()); + public void execute() { + List invites = _projectService.listProjectInvitations(id, projectId, this.getAccountName(), this.getDomainId(), state, activeOnly, this.getStartIndex(), this.getPageSizeVal(), + this.isRecursive(), this.listAll()); ListResponse response = new ListResponse(); List projectInvitationResponses = new ArrayList(); for (ProjectInvitation invite : invites) { @@ -91,7 +93,8 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { } response.setResponses(projectInvitationResponses); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } + } diff --git a/api/src/com/cloud/api/commands/StartVMCmd.java b/api/src/com/cloud/api/commands/StartVMCmd.java index c1969e1ae9d..141ed3d30ab 100644 --- a/api/src/com/cloud/api/commands/StartVMCmd.java +++ b/api/src/com/cloud/api/commands/StartVMCmd.java @@ -15,8 +15,8 @@ * along with this program. If not, see . * */ -package com.cloud.api.commands; - +package com.cloud.api.commands; + import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; @@ -40,40 +40,40 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; import com.cloud.utils.exception.ExecutionException; -@Implementation(responseObject=UserVmResponse.class, description="Starts a virtual machine.") -public class StartVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartVMCmd.class.getName()); - - private static final String s_name = "startvirtualmachineresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// +@Implementation(responseObject = UserVmResponse.class, description = "Starts a virtual machine.") +public class StartVMCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(StartVMCmd.class.getName()); - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + private static final String s_name = "startvirtualmachineresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @IdentityMapper(entityTableName = "vm_instance") + @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the virtual machine") private Long id; - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public Long getId() { return id; } - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; - } + public String getCommandName() { + return s_name; + } - public static String getResultObjectName() { - return "virtualmachine"; - } + public static String getResultObjectName() { + return "virtualmachine"; + } @Override public long getEntityOwnerId() { @@ -82,7 +82,8 @@ public class StartVMCmd extends BaseAsyncCmd { return vm.getAccountId(); } - return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are +// tracked } @Override @@ -92,44 +93,45 @@ public class StartVMCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "starting user vm: " + getId(); + return "starting user vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException{ + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { try { - UserContext.current().setEventDetails("Vm Id: "+getId()); + UserContext.current().setEventDetails("Vm Id: " + getId()); UserVm result; if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { - result = _bareMetalVmService.startVirtualMachine(this); + result = _bareMetalVmService.startVirtualMachine(this); } else { - result = _userVmService.startVirtualMachine(this); + result = _userVmService.startVirtualMachine(this); } - - if (result != null){ + + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to start a vm"); } - }catch (ConcurrentOperationException ex) { + } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - }catch (StorageUnavailableException ex) { + } catch (StorageUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); - }catch (ExecutionException ex) { + } catch (ExecutionException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - } - } -} + } + } + +} diff --git a/api/src/com/cloud/api/commands/StopVMCmd.java b/api/src/com/cloud/api/commands/StopVMCmd.java index 68b7d4b506b..b2f211b6c0c 100644 --- a/api/src/com/cloud/api/commands/StopVMCmd.java +++ b/api/src/com/cloud/api/commands/StopVMCmd.java @@ -35,41 +35,40 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(responseObject=UserVmResponse.class, description="Stops a virtual machine.") +@Implementation(responseObject = UserVmResponse.class, description = "Stops a virtual machine.") public class StopVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StopVMCmd.class.getName()); private static final String s_name = "stopvirtualmachineresponse"; - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @IdentityMapper(entityTableName = "vm_instance") + @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the virtual machine") private Long id; - - @Parameter(name=ApiConstants.FORCED, type=CommandType.BOOLEAN, required=false, description="Force stop the VM. The caller knows the VM is stopped.") + + @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force stop the VM. The caller knows the VM is stopped.") private Boolean forced; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public Long getId() { return id; } - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } - + public static String getResultObjectName() { return "virtualmachine"; } @@ -81,7 +80,8 @@ public class StopVMCmd extends BaseAsyncCmd { return vm.getAccountId(); } - return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are +// tracked } @Override @@ -91,34 +91,34 @@ public class StopVMCmd extends BaseAsyncCmd { @Override public String getEventDescription() { - return "stopping user vm: " + getId(); + return "stopping user vm: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + @Override public Long getInstanceId() { - return getId(); + return getId(); } - + public boolean isForced() { return (forced != null) ? forced : false; } @Override - public void execute() throws ServerApiException, ConcurrentOperationException{ - UserContext.current().setEventDetails("Vm Id: "+getId()); + public void execute() throws ServerApiException, ConcurrentOperationException { + UserContext.current().setEventDetails("Vm Id: " + getId()); UserVm result; - + if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { - result = _bareMetalVmService.stopVirtualMachine(getId(), isForced()); + result = _bareMetalVmService.stopVirtualMachine(getId(), isForced()); } else { - result = _userVmService.stopVirtualMachine(getId(), isForced()); + result = _userVmService.stopVirtualMachine(getId(), isForced()); } - + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java b/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java index c62c453d11b..e3e842af296 100644 --- a/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java +++ b/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java @@ -31,31 +31,30 @@ import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Accepts or declines project invitation", responseObject=SuccessResponse.class, since="3.0.0") +@Implementation(description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") public class UpdateProjectInvitationCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateProjectInvitationCmd.class.getName()); private static final String s_name = "updateprojectinvitationresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, required=true, type=CommandType.LONG, description="id of the project to join") + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + @IdentityMapper(entityTableName = "projects") + @Parameter(name = ApiConstants.PROJECT_ID, required = true, type = CommandType.LONG, description = "id of the project to join") private Long projectId; - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account that is joining the project") + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account that is joining the project") private String accountName; - - @Parameter(name=ApiConstants.TOKEN, type=CommandType.STRING, description="list invitations for specified account; this parameter has to be specified with domainId") + + @Parameter(name = ApiConstants.TOKEN, type = CommandType.STRING, description = "list invitations for specified account; this parameter has to be specified with domainId") private String token; - - @Parameter(name=ApiConstants.ACCEPT, type=CommandType.BOOLEAN, description="if true, accept the invitation, decline if false. True by default") + + @Parameter(name = ApiConstants.ACCEPT, type = CommandType.BOOLEAN, description = "if true, accept the invitation, decline if false. True by default") private Boolean accept; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// public Long getProjectId() { return projectId; } @@ -63,37 +62,36 @@ public class UpdateProjectInvitationCmd extends BaseAsyncCmd { public String getAccountName() { return accountName; } - + @Override public String getCommandName() { return s_name; } - + public String getToken() { return token; } - + public Boolean getAccept() { if (accept == null) { return true; } return accept; } - - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// @Override public long getEntityOwnerId() { - //TODO - return project entity ownerId - return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked + // TODO - return project entity ownerId + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are +// tracked } - @Override - public void execute(){ - UserContext.current().setEventDetails("Project id: "+ projectId + "; accountName " + accountName + "; accept " + getAccept()); + public void execute() { + UserContext.current().setEventDetails("Project id: " + projectId + "; accountName " + accountName + "; accept " + getAccept()); boolean result = _projectService.updateInvitation(projectId, accountName, token, getAccept()); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); @@ -102,14 +100,14 @@ public class UpdateProjectInvitationCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to join the project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_INVITATION_UPDATE; } - + @Override public String getEventDescription() { - return "Updating project invitation for projectId " + projectId; + return "Updating project invitation for projectId " + projectId; } } diff --git a/api/src/com/cloud/api/response/ProjectAccountResponse.java b/api/src/com/cloud/api/response/ProjectAccountResponse.java index 48a1e899d79..374b99df2bb 100644 --- a/api/src/com/cloud/api/response/ProjectAccountResponse.java +++ b/api/src/com/cloud/api/response/ProjectAccountResponse.java @@ -26,31 +26,40 @@ import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class ProjectAccountResponse extends BaseResponse implements ControlledEntityResponse { - @SerializedName(ApiConstants.PROJECT_ID) @Param(description="project id") + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "project id") private IdentityProxy projectId = new IdentityProxy("projects"); - - @SerializedName(ApiConstants.PROJECT) @Param(description="project name") + + @SerializedName(ApiConstants.PROJECT) + @Param(description = "project name") private String projectName; - - @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the id of the account") + + @SerializedName(ApiConstants.ACCOUNT_ID) + @Param(description = "the id of the account") private IdentityProxy id = new IdentityProxy("account"); - @SerializedName(ApiConstants.ACCOUNT) @Param(description="the name of the account") + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the name of the account") private String accountName; - @SerializedName(ApiConstants.ACCOUNT_TYPE) @Param(description="account type (admin, domain-admin, user)") + @SerializedName(ApiConstants.ACCOUNT_TYPE) + @Param(description = "account type (admin, domain-admin, user)") private Short accountType; - - @SerializedName(ApiConstants.ROLE) @Param(description="account role in the project (regular,owner)") + + @SerializedName(ApiConstants.ROLE) + @Param(description = "account role in the project (regular,owner)") private String role; - @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="id of the Domain the account belongs too") + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "id of the Domain the account belongs too") private IdentityProxy domainId = new IdentityProxy("domain"); - @SerializedName(ApiConstants.DOMAIN) @Param(description="name of the Domain the account belongs too") + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "name of the Domain the account belongs too") private String domainName; - - @SerializedName(ApiConstants.USER) @Param(description="the list of users associated with account", responseObject = UserResponse.class) + + @SerializedName(ApiConstants.USER) + @Param(description = "the list of users associated with account", responseObject = UserResponse.class) private List users; public void setProjectId(Long projectId) { diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index c216dda4574..8c05e3fbf33 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -175,12 +175,12 @@ public class ApiDispatcher { Map unpackedParams = cmd.unpackParams(params); if (cmd instanceof BaseListCmd) { - Object pageSizeObj = unpackedParams.get(ApiConstants.PAGE_SIZE); - Long pageSize = null; - if (pageSizeObj != null) { - pageSize = Long.valueOf((String)pageSizeObj); - } - + Object pageSizeObj = unpackedParams.get(ApiConstants.PAGE_SIZE); + Long pageSize = null; + if (pageSizeObj != null) { + pageSize = Long.valueOf((String) pageSizeObj); + } + if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && pageSize != BaseListCmd.PAGESIZE_UNLIMITED)) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); } else if (pageSize == null && (unpackedParams.get(ApiConstants.PAGE) != null)) { @@ -206,13 +206,14 @@ public class ApiDispatcher { if ((parameterAnnotation == null) || !parameterAnnotation.expose()) { continue; } - + IdentityMapper identityMapper = field.getAnnotation(IdentityMapper.class); Object paramObj = unpackedParams.get(parameterAnnotation.name()); if (paramObj == null) { if (parameterAnnotation.required()) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length()-8) + " due to missing parameter " + parameterAnnotation.name()); + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to missing parameter " + + parameterAnnotation.name()); } continue; } @@ -224,20 +225,23 @@ public class ApiDispatcher { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to execute API command " + cmd.getCommandName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name()); } - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length()-8) + " due to invalid value " + paramObj + " for parameter " + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value " + paramObj + + " for parameter " + parameterAnnotation.name()); } catch (ParseException parseEx) { if (s_logger.isDebugEnabled()) { - s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getCommandName().substring(0, cmd.getCommandName().length()-8)); + s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getCommandName().substring(0, cmd.getCommandName().length()-8) + ", please pass dates in the format mentioned in the api documentation"); - } catch (InvalidParameterValueException invEx){ - 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()); + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to parse date " + paramObj + " for command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + + ", please pass dates in the format mentioned in the api documentation"); + } catch (InvalidParameterValueException invEx) { + 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 + // FIXME: Better error message? This only happens if the API command is not executable, which typically +// 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)); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } } } @@ -252,28 +256,29 @@ public class ApiDispatcher { field.set(cmdObj, Boolean.valueOf(paramObj.toString())); break; case DATE: - // This piece of code is for maintaining backward compatibility and support both the date formats(Bug 9724) + // This piece of code is for maintaining backward compatibility and support both the date formats(Bug +// 9724) // Do the date massaging for ListEventsCmd only - if(cmdObj instanceof ListEventsCmd){ + if (cmdObj instanceof ListEventsCmd) { boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString()); - if (isObjInNewDateFormat){ + if (isObjInNewDateFormat) { DateFormat newFormat = BaseCmd.NEW_INPUT_FORMAT; synchronized (newFormat) { - field.set(cmdObj, newFormat.parse(paramObj.toString())); + field.set(cmdObj, newFormat.parse(paramObj.toString())); } - }else{ + } else { DateFormat format = BaseCmd.INPUT_FORMAT; synchronized (format) { - Date date = format.parse(paramObj.toString()); - if (field.getName().equals("startDate")){ + Date date = format.parse(paramObj.toString()); + if (field.getName().equals("startDate")) { date = massageDate(date, 0, 0, 0); - }else if (field.getName().equals("endDate")){ + } else if (field.getName().equals("endDate")) { date = massageDate(date, 23, 59, 59); } field.set(cmdObj, date); } - } - }else{ + } + } else { DateFormat format = BaseCmd.INPUT_FORMAT; format.setLenient(false); synchronized (format) { @@ -297,16 +302,15 @@ public class ApiDispatcher { case INTEGER: listParam.add(Integer.valueOf(token)); break; - case LONG: - { - Long val = null; - if(identityMapper != null) - val = s_instance._identityDao.getIdentityId(identityMapper, token); - else - val = Long.valueOf(token); - - listParam.add(val); - } + case LONG: { + Long val = null; + if (identityMapper != null) + val = s_instance._identityDao.getIdentityId(identityMapper, token); + else + val = Long.valueOf(token); + + listParam.add(val); + } break; case SHORT: listParam.add(Short.valueOf(token)); @@ -318,19 +322,19 @@ public class ApiDispatcher { field.set(cmdObj, listParam); break; case LONG: - if(identityMapper != null) - field.set(cmdObj, s_instance._identityDao.getIdentityId(identityMapper, paramObj.toString())); - else - field.set(cmdObj, Long.valueOf(paramObj.toString())); + if (identityMapper != null) + field.set(cmdObj, s_instance._identityDao.getIdentityId(identityMapper, paramObj.toString())); + else + field.set(cmdObj, Long.valueOf(paramObj.toString())); break; case SHORT: field.set(cmdObj, Short.valueOf(paramObj.toString())); break; case STRING: - if((paramObj != null) && paramObj.toString().length() > annotation.length()){ - s_logger.error("Value greater than max allowed length "+annotation.length()+" for param: "+field.getName()); - throw new InvalidParameterValueException("Value greater than max allowed length "+annotation.length()+" for param: "+field.getName()); - } + if ((paramObj != null) && paramObj.toString().length() > annotation.length()) { + s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); + throw new InvalidParameterValueException("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); + } field.set(cmdObj, paramObj.toString()); break; case TZDATE: @@ -346,12 +350,12 @@ public class ApiDispatcher { throw new CloudRuntimeException("Internal error initializing parameters for command " + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]"); } } - + private static boolean isObjInNewDateFormat(String string) { Matcher matcher = BaseCmd.newInputDateFormat.matcher(string); return matcher.matches(); } - + private static Date massageDate(Date date, int hourOfDay, int minute, int second) { Calendar cal = Calendar.getInstance(); cal.setTime(date); @@ -360,10 +364,10 @@ public class ApiDispatcher { cal.set(Calendar.SECOND, second); return cal.getTime(); } - + public static void plugService(BaseCmd cmd) { - - if(!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())){ + + if (!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())) { return; } Class clazz = cmd.getClass(); @@ -379,12 +383,12 @@ public class ApiDispatcher { Object instance = null; if (PluggableService.class.isAssignableFrom(fc)) { instance = locator.getPluggableService(fc); - } - + } + if (instance == null) { throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + clazz.getSimpleName()); } - + try { field.setAccessible(true); field.set(cmd, instance); diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 5676b3c3169..f506d64c2c1 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -335,7 +335,7 @@ public class ApiServer implements HttpRequestHandler { responseType = paramValue[1]; } else { // according to the servlet spec, the parameter map should be in the form (name=String, -// value=String[]), so + // value=String[]), so // parameter values will be stored in an array parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); } @@ -867,7 +867,7 @@ public class ApiServer implements HttpRequestHandler { // FIXME: the following two threads are copied from // http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java // we have to cite a license if we are using this code directly, so we need to add the appropriate citation or -// modify the + // modify the // code to be very specific to our needs static class ListenerThread extends Thread { private HttpService _httpService = null; diff --git a/server/src/com/cloud/projects/ProjectInvitationVO.java b/server/src/com/cloud/projects/ProjectInvitationVO.java index bbb42b70970..1db167edab2 100644 --- a/server/src/com/cloud/projects/ProjectInvitationVO.java +++ b/server/src/com/cloud/projects/ProjectInvitationVO.java @@ -16,49 +16,49 @@ import com.cloud.api.Identity; import com.cloud.utils.db.GenericDao; @Entity -@Table(name="project_invitations") +@Table(name = "project_invitations") public class ProjectInvitationVO implements ProjectInvitation, Identity { @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") private long id; - - @Column(name="project_id") + + @Column(name = "project_id") private long projectId; - @Column(name="account_id") + @Column(name = "account_id") private Long forAccountId; - - @Column(name="domain_id") + + @Column(name = "domain_id") private Long inDomainId; - - @Column(name="token") + + @Column(name = "token") private String token; - - @Column(name="email") + + @Column(name = "email") private String email; - - @Column(name="state") - @Enumerated(value=EnumType.STRING) + + @Column(name = "state") + @Enumerated(value = EnumType.STRING) private State state = State.Pending; - - @Column(name=GenericDao.CREATED_COLUMN) + + @Column(name = GenericDao.CREATED_COLUMN) private Date created; - @Column(name="uuid") + @Column(name = "uuid") private String uuid; - - protected ProjectInvitationVO(){ - this.uuid = UUID.randomUUID().toString(); + + protected ProjectInvitationVO() { + this.uuid = UUID.randomUUID().toString(); } - + public ProjectInvitationVO(long projectId, Long accountId, Long domainId, String email, String token) { - this.forAccountId = accountId; - this.inDomainId = domainId; - this.projectId = projectId; - this.email = email; - this.token = token; - this.uuid = UUID.randomUUID().toString(); + this.forAccountId = accountId; + this.inDomainId = domainId; + this.projectId = projectId; + this.email = email; + this.token = token; + this.uuid = UUID.randomUUID().toString(); } @Override @@ -89,8 +89,8 @@ public class ProjectInvitationVO implements ProjectInvitation, Identity { @Override public Date getCreated() { return created; - } - + } + @Override public State getState() { return state; @@ -99,7 +99,7 @@ public class ProjectInvitationVO implements ProjectInvitation, Identity { public void setState(State state) { this.state = state; } - + @Override public String toString() { StringBuilder buf = new StringBuilder("ProjectInvitation["); @@ -111,21 +111,21 @@ public class ProjectInvitationVO implements ProjectInvitation, Identity { public Long getInDomainId() { return inDomainId; } - + @Override public String getUuid() { - return this.uuid; + return this.uuid; } - + public void setUuid(String uuid) { - this.uuid = uuid; + this.uuid = uuid; } - + @Override public long getDomainId() { return inDomainId == null ? -1 : inDomainId; } - + @Override public long getAccountId() { return forAccountId == null ? -1 : forAccountId; diff --git a/server/src/com/cloud/projects/ProjectManager.java b/server/src/com/cloud/projects/ProjectManager.java index b99996be49a..358635424f9 100644 --- a/server/src/com/cloud/projects/ProjectManager.java +++ b/server/src/com/cloud/projects/ProjectManager.java @@ -1,4 +1,3 @@ - package com.cloud.projects; import java.util.List; @@ -11,10 +10,11 @@ public interface ProjectManager extends ProjectService { boolean canModifyProjectAccount(Account caller, long accountId); boolean deleteAccountFromProject(long projectId, long accountId); - + List listPermittedProjectAccounts(long accountId); - boolean projectInviteRequired(); - - boolean allowUserToCreateProject(); + boolean projectInviteRequired(); + + boolean allowUserToCreateProject(); + } diff --git a/server/src/com/cloud/projects/dao/ProjectAccountDao.java b/server/src/com/cloud/projects/dao/ProjectAccountDao.java index 47d8cdf8a1e..3e72eee9974 100644 --- a/server/src/com/cloud/projects/dao/ProjectAccountDao.java +++ b/server/src/com/cloud/projects/dao/ProjectAccountDao.java @@ -23,18 +23,20 @@ import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectAccountVO; import com.cloud.utils.db.GenericDao; -public interface ProjectAccountDao extends GenericDao{ +public interface ProjectAccountDao extends GenericDao { ProjectAccountVO getProjectOwner(long projectId); + List listByProjectId(long projectId); + ProjectAccountVO findByProjectIdAccountId(long projectId, long accountId); - + boolean canAccessProjectAccount(long accountId, long projectAccountId); - + boolean canModifyProjectAccount(long accountId, long projectAccountId); - + List listPermittedAccountIds(long accountId); - + List listAdministratedProjects(long adminAccountId); - + Long countByAccountIdAndRole(long accountId, ProjectAccount.Role role); } diff --git a/server/src/com/cloud/projects/dao/ProjectAccountDaoImpl.java b/server/src/com/cloud/projects/dao/ProjectAccountDaoImpl.java index c527f350745..1eb28cae1f9 100644 --- a/server/src/com/cloud/projects/dao/ProjectAccountDaoImpl.java +++ b/server/src/com/cloud/projects/dao/ProjectAccountDaoImpl.java @@ -30,13 +30,13 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; -@Local(value={ProjectAccountDao.class}) +@Local(value = { ProjectAccountDao.class }) public class ProjectAccountDaoImpl extends GenericDaoBase implements ProjectAccountDao { protected final SearchBuilder AllFieldsSearch; final GenericSearchBuilder AdminSearch; final GenericSearchBuilder ProjectAccountSearch; final GenericSearchBuilder CountByRoleSearch; - + protected ProjectAccountDaoImpl() { AllFieldsSearch = createSearchBuilder(); AllFieldsSearch.and("role", AllFieldsSearch.entity().getAccountRole(), SearchCriteria.Op.EQ); @@ -44,57 +44,57 @@ public class ProjectAccountDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("role", ProjectAccount.Role.Admin); sc.setParameters("projectId", projectId); - + return findOneBy(sc); } - + @Override public List listByProjectId(long projectId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("projectId", projectId); - + return listBy(sc); } - + @Override public ProjectAccountVO findByProjectIdAccountId(long projectId, long accountId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("projectId", projectId); sc.setParameters("accountId", accountId); - + return findOneBy(sc); } - + @Override public boolean canAccessProjectAccount(long accountId, long projectAccountId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("accountId", accountId); sc.setParameters("projectAccountId", projectAccountId); - + if (findOneBy(sc) != null) { return true; } else { @@ -108,21 +108,21 @@ public class ProjectAccountDaoImpl extends GenericDaoBase listPermittedAccountIds(long accountId) { SearchCriteria sc = ProjectAccountSearch.create(); sc.setParameters("accountId", accountId); return customSearch(sc, null); } - + @Override public List listAdministratedProjects(long adminAccountId) { SearchCriteria sc = AdminSearch.create(); @@ -130,12 +130,13 @@ public class ProjectAccountDaoImpl extends GenericDaoBase sc = CountByRoleSearch.create(); + SearchCriteria sc = CountByRoleSearch.create(); sc.setParameters("accountId", accountId); sc.setParameters("role", role); return customSearch(sc, null).get(0); } + } diff --git a/server/src/com/cloud/projects/dao/ProjectDao.java b/server/src/com/cloud/projects/dao/ProjectDao.java index 161995bb051..1e63f794a19 100644 --- a/server/src/com/cloud/projects/dao/ProjectDao.java +++ b/server/src/com/cloud/projects/dao/ProjectDao.java @@ -23,13 +23,14 @@ import com.cloud.projects.Project; import com.cloud.projects.ProjectVO; import com.cloud.utils.db.GenericDao; -public interface ProjectDao extends GenericDao{ +public interface ProjectDao extends GenericDao { ProjectVO findByNameAndDomain(String name, long domainId); Long countProjectsForDomain(long domainId); - + ProjectVO findByProjectAccountId(long projectAccountId); - + List listByState(Project.State state); + } diff --git a/server/src/com/cloud/projects/dao/ProjectDaoImpl.java b/server/src/com/cloud/projects/dao/ProjectDaoImpl.java index 72fcc5aed2d..41af4a1e887 100644 --- a/server/src/com/cloud/projects/dao/ProjectDaoImpl.java +++ b/server/src/com/cloud/projects/dao/ProjectDaoImpl.java @@ -16,13 +16,13 @@ import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.Transaction; -@Local(value={ProjectDao.class}) +@Local(value = { ProjectDao.class }) public class ProjectDaoImpl extends GenericDaoBase implements ProjectDao { private static final Logger s_logger = Logger.getLogger(ProjectDaoImpl.class); protected final SearchBuilder AllFieldsSearch; protected GenericSearchBuilder CountByDomain; protected GenericSearchBuilder ProjectAccountSearch; - + protected ProjectDaoImpl() { AllFieldsSearch = createSearchBuilder(); AllFieldsSearch.and("name", AllFieldsSearch.entity().getName(), SearchCriteria.Op.EQ); @@ -30,23 +30,24 @@ public class ProjectDaoImpl extends GenericDaoBase implements P AllFieldsSearch.and("projectAccountId", AllFieldsSearch.entity().getProjectAccountId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), SearchCriteria.Op.EQ); AllFieldsSearch.done(); - + CountByDomain = createSearchBuilder(Long.class); CountByDomain.select(null, Func.COUNT, null); - CountByDomain.and("domainId", CountByDomain.entity().getDomainId(), SearchCriteria.Op.EQ); + CountByDomain.and("domainId", CountByDomain.entity().getDomainId(), SearchCriteria.Op.EQ); CountByDomain.done(); } - + @Override public ProjectVO findByNameAndDomain(String name, long domainId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("name", name); sc.setParameters("domainId", domainId); - + return findOneBy(sc); } - - @Override @DB + + @Override + @DB public boolean remove(Long projectId) { boolean result = false; Transaction txn = Transaction.currentTxn(); @@ -57,34 +58,35 @@ public class ProjectDaoImpl extends GenericDaoBase implements P s_logger.warn("Failed to reset name for the project id=" + projectId + " as a part of project remove"); return false; } else { - + } result = super.remove(projectId); txn.commit(); - + return result; - + } - + @Override public Long countProjectsForDomain(long domainId) { SearchCriteria sc = CountByDomain.create(); sc.setParameters("domainId", domainId); - return customSearch(sc, null).get(0); + return customSearch(sc, null).get(0); } - + @Override - public ProjectVO findByProjectAccountId(long projectAccountId) { + public ProjectVO findByProjectAccountId(long projectAccountId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("projectAccountId", projectAccountId); - + return findOneBy(sc); } - + @Override public List listByState(Project.State state) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("state", state); return listBy(sc); } + } diff --git a/server/src/com/cloud/projects/dao/ProjectInvitationDao.java b/server/src/com/cloud/projects/dao/ProjectInvitationDao.java index 2c3218d77d4..cd58edb1699 100644 --- a/server/src/com/cloud/projects/dao/ProjectInvitationDao.java +++ b/server/src/com/cloud/projects/dao/ProjectInvitationDao.java @@ -23,14 +23,23 @@ import com.cloud.projects.ProjectInvitation.State; import com.cloud.projects.ProjectInvitationVO; import com.cloud.utils.db.GenericDao; -public interface ProjectInvitationDao extends GenericDao{ +public interface ProjectInvitationDao extends GenericDao { ProjectInvitationVO findByAccountIdProjectId(long accountId, long projectId, State... inviteState); + List listExpiredInvitations(); + boolean expirePendingInvitations(long timeOut); + boolean isActive(long id, long timeout); + ProjectInvitationVO findByEmailAndProjectId(String email, long projectId, State... inviteState); + ProjectInvitationVO findPendingByTokenAndProjectId(String token, long projectId, State... inviteState); - void cleanupInvitations(long projectId); + + void cleanupInvitations(long projectId); + ProjectInvitationVO findPendingById(long id); + List listInvitationsToExpire(long timeOut); + } diff --git a/server/src/com/cloud/projects/dao/ProjectInvitationDaoImpl.java b/server/src/com/cloud/projects/dao/ProjectInvitationDaoImpl.java index c260b64b92c..f844cae1845 100644 --- a/server/src/com/cloud/projects/dao/ProjectInvitationDaoImpl.java +++ b/server/src/com/cloud/projects/dao/ProjectInvitationDaoImpl.java @@ -14,12 +14,12 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -@Local(value={ProjectInvitationDao.class}) +@Local(value = { ProjectInvitationDao.class }) public class ProjectInvitationDaoImpl extends GenericDaoBase implements ProjectInvitationDao { private static final Logger s_logger = Logger.getLogger(ProjectInvitationDaoImpl.class); protected final SearchBuilder AllFieldsSearch; protected final SearchBuilder InactiveSearch; - + protected ProjectInvitationDaoImpl() { AllFieldsSearch = createSearchBuilder(); AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getForAccountId(), SearchCriteria.Op.EQ); @@ -31,7 +31,7 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("accountId", accountId); sc.setParameters("projectId", projectId); if (inviteState != null && inviteState.length > 0) { - sc.setParameters("state", (Object[])inviteState); + sc.setParameters("state", (Object[]) inviteState); } return findOneBy(sc); } - + @Override public List listExpiredInvitations() { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("state", State.Expired); - + return listBy(sc); } - + @Override public boolean expirePendingInvitations(long timeout) { boolean success = true; - + SearchCriteria sc = InactiveSearch.create(); sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime() >> 10) - timeout)); sc.setParameters("state", State.Pending); - + List invitationsToExpire = listBy(sc); for (ProjectInvitationVO invitationToExpire : invitationsToExpire) { invitationToExpire.setState(State.Expired); @@ -80,74 +79,75 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase listInvitationsToExpire (long timeOut) { - SearchCriteria sc = InactiveSearch.create(); + public List listInvitationsToExpire(long timeOut) { + SearchCriteria sc = InactiveSearch.create(); sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - timeOut)); sc.setParameters("state", State.Pending); return listBy(sc); } - + @Override public boolean isActive(long id, long timeout) { SearchCriteria sc = InactiveSearch.create(); - + sc.setParameters("id", id); - + if (findOneBy(sc) == null) { s_logger.warn("Unable to find project invitation by id " + id); return false; } - + sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - timeout)); - + if (findOneBy(sc) == null) { return true; } else { return false; } } - + @Override public ProjectInvitationVO findByEmailAndProjectId(String email, long projectId, State... inviteState) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("email", email); sc.setParameters("projectId", projectId); if (inviteState != null && inviteState.length > 0) { - sc.setParameters("state", (Object[])inviteState); + sc.setParameters("state", (Object[]) inviteState); } - + return findOneBy(sc); } - + @Override public ProjectInvitationVO findPendingByTokenAndProjectId(String token, long projectId, State... inviteState) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("token", token); sc.setParameters("projectId", projectId); if (inviteState != null && inviteState.length > 0) { - sc.setParameters("state", (Object[])inviteState); + sc.setParameters("state", (Object[]) inviteState); } - + return findOneBy(sc); } - + @Override public ProjectInvitationVO findPendingById(long id) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("id", id); sc.setParameters("state", State.Pending); - + return findOneBy(sc); } - + @Override public void cleanupInvitations(long projectId) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("projectId", projectId); - + int numberRemoved = remove(sc); s_logger.debug("Removed " + numberRemoved + " invitations for project id=" + projectId); } + } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 1119b3f3c1a..25e8a10a32a 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -298,17 +298,18 @@ public class ManagementServerImpl implements ManagementServer { private final LoadBalancerDao _loadbalancerDao; private final HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; private final Adapters _hostAllocators; - @Inject ProjectManager _projectMgr; + @Inject + ProjectManager _projectMgr; private final ResourceManager _resourceMgr; @Inject SnapshotManager _snapshotMgr; - + private final KeystoreManager _ksMgr; private final ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker")); private final Map _configs; - + private final StatsCollector _statsCollector; private final Map _availableIdsMap; @@ -366,18 +367,17 @@ public class ManagementServerImpl implements ManagementServer { _itMgr = locator.getManager(VirtualMachineManager.class); _ksMgr = locator.getManager(KeystoreManager.class); _resourceMgr = locator.getManager(ResourceManager.class); - + _hypervisorCapabilitiesDao = locator.getDao(HypervisorCapabilitiesDao.class); - - + _hostAllocators = locator.getAdapters(HostAllocator.class); if (_hostAllocators == null || !_hostAllocators.isSet()) { s_logger.error("Unable to find HostAllocators"); } - + String value = _configs.get("account.cleanup.interval"); int cleanup = NumbersUtil.parseInt(value, 60 * 60 * 24); // 1 day. - + _statsCollector = StatsCollector.getInstance(_configs); _purgeDelay = NumbersUtil.parseInt(_configs.get("event.purge.delay"), 0); @@ -414,10 +414,10 @@ public class ManagementServerImpl implements ManagementServer { // right now, we made the decision to only list zones associated with this domain dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private zones } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { - if (keyword != null) { + if (keyword != null) { dcs = _dcDao.findByKeyword(keyword); } else { - dcs = _dcDao.listAll(); // all zones + dcs = _dcDao.listAll(); // all zones } } else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) { // it was decided to return all zones for the user's domain, and everything above till root @@ -616,10 +616,11 @@ public class ManagementServerImpl implements ManagementServer { // The list method for offerings is being modified in accordance with discussion with Will/Kevin // For now, we will be listing the following based on the usertype // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way till + // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way +// till // root - Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); - isAscending = (isAscending == null ? true : isAscending); + Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); + isAscending = (isAscending == null ? true : isAscending); Filter searchFilter = new Filter(ServiceOfferingVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _offeringsDao.createSearchCriteria(); @@ -634,8 +635,8 @@ public class ManagementServerImpl implements ManagementServer { if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && isSystem) { throw new InvalidParameterValueException("Only ROOT admins can access system's offering"); - } - + } + // Keeping this logic consistent with domain specific zones // if a domainId is provided, we just return the so associated with this domain if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { @@ -647,14 +648,14 @@ public class ManagementServerImpl implements ManagementServer { // For non-root users if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - if (isSystem){ + if (isSystem) { throw new InvalidParameterValueException("Only root admins can access system's offering"); } return searchServiceOfferingsInternal(caller, name, id, vmId, keyword, searchFilter); } // for root users, the existing flow - if (caller.getDomainId() != 1 && isSystem){ //NON ROOT admin + if (caller.getDomainId() != 1 && isSystem) { // NON ROOT admin throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering"); } @@ -669,7 +670,7 @@ public class ManagementServerImpl implements ManagementServer { if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } - + _accountMgr.checkAccess(caller, null, true, vmInstance); ServiceOfferingVO offering = _offeringsDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); @@ -682,7 +683,7 @@ public class ManagementServerImpl implements ManagementServer { if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } - + if (isSystem != null) { sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem); } @@ -690,12 +691,12 @@ public class ManagementServerImpl implements ManagementServer { if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - + if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } - - if (vm_type_str != null){ + + if (vm_type_str != null) { sc.addAnd("vm_type", SearchCriteria.Op.EQ, vm_type_str); } @@ -707,7 +708,8 @@ public class ManagementServerImpl implements ManagementServer { private List searchServiceOfferingsInternal(Account account, Object name, Object id, Long vmId, Object keyword, Filter searchFilter) { - // it was decided to return all offerings for the user's domain, and everything above till root (for normal user or + // it was decided to return all offerings for the user's domain, and everything above till root (for normal user +// or // domain admin) // list all offerings belonging to this domain, and all of its parents // check the parent, if not null, add offerings for that parent to list @@ -763,8 +765,8 @@ public class ManagementServerImpl implements ManagementServer { // for this domain sc.addAnd("domainId", SearchCriteria.Op.EQ, domainRecord.getId()); - - //don't return removed service offerings + + // don't return removed service offerings sc.addAnd("removed", SearchCriteria.Op.NULL); // search and add for this domain @@ -840,7 +842,7 @@ public class ManagementServerImpl implements ManagementServer { ssc.addOr("hypervisorType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - + return _clusterDao.search(sc, searchFilter); } @@ -870,11 +872,11 @@ public class ManagementServerImpl implements ManagementServer { } throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!"); } - + VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId); - } + } // business logic if (vm.getState() != State.Running) { if (s_logger.isDebugEnabled()) { @@ -883,7 +885,8 @@ public class ManagementServerImpl implements ManagementServer { throw new InvalidParameterValueException("VM is not Running, unable to migrate the vm " + vm); } - if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { + if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) + && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is not XenServer/VMware/KVM/OVM, cannot migrate this VM."); } @@ -922,7 +925,6 @@ public class ManagementServerImpl implements ManagementServer { s_logger.debug("Calling HostAllocators to search for hosts in cluster: " + cluster + " having enough capacity and suitable for migration"); } - List suitableHosts = new ArrayList(); Enumeration enHost = _hostAllocators.enumeration(); @@ -939,9 +941,9 @@ public class ManagementServerImpl implements ManagementServer { } } - if(suitableHosts.isEmpty()){ + if (suitableHosts.isEmpty()) { s_logger.debug("No suitable hosts found"); - }else{ + } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Hosts having capacity and suitable for migration: " + suitableHosts); } @@ -1065,8 +1067,8 @@ public class ManagementServerImpl implements ManagementServer { vlanType = VlanType.DirectAttached.toString(); } } - - //set project information + + // set project information if (projectId != null) { Project project = _projectMgr.getProject(projectId); if (project == null) { @@ -1185,16 +1187,16 @@ public class ManagementServerImpl implements ManagementServer { public Set> listIsos(ListIsosCmd cmd) throws IllegalArgumentException, InvalidParameterValueException { TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter()); Account caller = UserContext.current().getCaller(); - + boolean listAll = (caller.getType() != Account.ACCOUNT_TYPE_NORMAL && (isoFilter != null && isoFilter == TemplateFilter.all)); List permittedAccountIds = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + List permittedAccounts = new ArrayList(); for (Long accountId : permittedAccountIds) { - permittedAccounts.add(_accountMgr.getAccount(accountId)); + permittedAccounts.add(_accountMgr.getAccount(accountId)); } HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); @@ -1206,9 +1208,9 @@ public class ManagementServerImpl implements ManagementServer { public Set> listTemplates(ListTemplatesCmd cmd) throws IllegalArgumentException, InvalidParameterValueException { TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter()); Long id = cmd.getId(); - + Account caller = UserContext.current().getCaller(); - + boolean listAll = (caller.getType() != Account.ACCOUNT_TYPE_NORMAL && (templateFilter != null && templateFilter == TemplateFilter.all)); List permittedAccountIds = new ArrayList(); Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); @@ -1216,19 +1218,19 @@ public class ManagementServerImpl implements ManagementServer { ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); List permittedAccounts = new ArrayList(); for (Long accountId : permittedAccountIds) { - permittedAccounts.add(_accountMgr.getAccount(accountId)); + permittedAccounts.add(_accountMgr.getAccount(accountId)); } - + boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured)); HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - + return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria); } private Set> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, List permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria) { - + VMTemplateVO template = null; if (templateId != null) { template = _templateDao.findById(templateId); @@ -1251,10 +1253,10 @@ public class ManagementServerImpl implements ManagementServer { } else { domain = _domainDao.findById(DomainVO.ROOT_DOMAIN); } - + List hypers = null; - if(!isIso) { - hypers = _resourceMgr.listAvailHypervisorInZone(null, null); + if (!isIso) { + hypers = _resourceMgr.listAvailHypervisorInZone(null, null); } Set> templateZonePairSet = new HashSet>(); if (_swiftMgr.isSwiftEnabled()) { @@ -1295,7 +1297,6 @@ public class ManagementServerImpl implements ManagementServer { return templateZonePairSet; } - @Override public VMTemplateVO updateTemplate(UpdateIsoCmd cmd) { return updateTemplateOrIso(cmd); @@ -1345,9 +1346,9 @@ public class ManagementServerImpl implements ManagementServer { if (displayText != null) { template.setDisplayText(displayText); } - + if (sortKey != null) { - template.setSortKey(sortKey); + template.setSortKey(sortKey); } ImageFormat imageFormat = null; @@ -1384,10 +1385,9 @@ public class ManagementServerImpl implements ManagementServer { return _templateDao.findById(id); } - @Override public List searchForEvents(ListEventsCmd cmd) { - Account caller = UserContext.current().getCaller(); + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); Long id = cmd.getId(); @@ -1403,12 +1403,12 @@ public class ManagementServerImpl implements ManagementServer { _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(EventVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _eventDao.createSearchBuilder(); - - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); + + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true @@ -1416,18 +1416,18 @@ public class ManagementServerImpl implements ManagementServer { domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + if (listProjectResourcesCriteria != null) { - SearchBuilder accountSearch = _accountDao.createSearchBuilder(); - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } + SearchBuilder accountSearch = _accountDao.createSearchBuilder(); + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.EQ); + sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); + sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } } - + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE); sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ); @@ -1435,15 +1435,15 @@ public class ManagementServerImpl implements ManagementServer { sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ); sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ); - sb.and("state", sb.entity().getState(),SearchCriteria.Op.NEQ); - sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ); - sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ); + sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); SearchCriteria sc = sb.create(); if (listProjectResourcesCriteria != null) { - sc.setJoinParameters("accountSearch","accountType", Account.ACCOUNT_TYPE_PROJECT); + sc.setJoinParameters("accountSearch", "accountType", Account.ACCOUNT_TYPE_PROJECT); } - + if (!permittedAccounts.isEmpty()) { sc.setParameters("accountIdIN", permittedAccounts.toArray()); } else if (domainId != null) { @@ -1454,11 +1454,11 @@ public class ManagementServerImpl implements ManagementServer { sc.setParameters("domainId", domainId); } } - + if (id != null) { sc.setParameters("id", id); } - + if (keyword != null) { SearchCriteria ssc = _eventDao.createSearchCriteria(); ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -1475,14 +1475,14 @@ public class ManagementServerImpl implements ManagementServer { sc.setParameters("type", type); } - if (startDate != null && endDate != null) { + if (startDate != null && endDate != null) { sc.setParameters("createDateB", startDate, endDate); - } else if (startDate != null) { + } else if (startDate != null) { sc.setParameters("createDateG", startDate); } else if (endDate != null) { sc.setParameters("createDateL", endDate); } - + if ((entryTime != null) && (duration != null)) { if (entryTime <= duration) { throw new InvalidParameterValueException("Entry time must be greater than duration"); @@ -1493,8 +1493,8 @@ public class ManagementServerImpl implements ManagementServer { calMax.add(Calendar.SECOND, -duration); Date minTime = calMin.getTime(); Date maxTime = calMax.getTime(); - - sc.setParameters("state", com.cloud.event.Event.State.Completed); + + sc.setParameters("state", com.cloud.event.Event.State.Completed); sc.setParameters("startId", 0); sc.setParameters("createDate", minTime, maxTime); List startedEvents = _eventDao.searchAllEvents(sc, searchFilter); @@ -1506,15 +1506,14 @@ public class ManagementServerImpl implements ManagementServer { } } return pendingEvents; - } else { - return _eventDao.searchAllEvents(sc, searchFilter); + } else { + return _eventDao.searchAllEvents(sc, searchFilter); } } - @Override public List searchForRouters(ListRoutersCmd cmd) { - Long id = cmd.getId(); + Long id = cmd.getId(); String name = cmd.getRouterName(); String state = cmd.getState(); Long zone = cmd.getZoneId(); @@ -1522,7 +1521,7 @@ public class ManagementServerImpl implements ManagementServer { Long hostId = cmd.getHostId(); String keyword = cmd.getKeyword(); Long networkId = cmd.getNetworkId(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -1555,7 +1554,7 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria sc = sb.create(); _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + if (keyword != null) { SearchCriteria ssc = _routerDao.createSearchCriteria(); ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -1590,7 +1589,6 @@ public class ManagementServerImpl implements ManagementServer { return _routerDao.search(sc, searchFilter); } - @Override public List searchForIPAddresses(ListPublicIpAddressesCmd cmd) { Object keyword = cmd.getKeyword(); @@ -1604,10 +1602,10 @@ public class ManagementServerImpl implements ManagementServer { Long ipId = cmd.getId(); Boolean sourceNat = cmd.getIsSourceNat(); Boolean staticNat = cmd.getIsStaticNat(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); - + Boolean isAllocated = cmd.isAllocatedOnly(); if (isAllocated == null) { isAllocated = Boolean.TRUE; @@ -1617,12 +1615,12 @@ public class ManagementServerImpl implements ManagementServer { _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(IPAddressVO.class, "address", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _publicIpAddressDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); sb.and("address", sb.entity().getAddress(), SearchCriteria.Op.EQ); sb.and("vlanDbId", sb.entity().getVlanId(), SearchCriteria.Op.EQ); @@ -1631,9 +1629,8 @@ public class ManagementServerImpl implements ManagementServer { sb.and("associatedNetworkIdEq", sb.entity().getAssociatedWithNetworkId(), SearchCriteria.Op.EQ); sb.and("isSourceNat", sb.entity().isSourceNat(), SearchCriteria.Op.EQ); sb.and("isStaticNat", sb.entity().isOneToOneNat(), SearchCriteria.Op.EQ); - - - if (forLoadBalancing != null && (Boolean)forLoadBalancing) { + + if (forLoadBalancing != null && (Boolean) forLoadBalancing) { SearchBuilder lbSearch = _loadbalancerDao.createSearchBuilder(); sb.join("lbSearch", lbSearch, sb.entity().getId(), lbSearch.entity().getSourceIpAddressId(), JoinType.INNER); sb.groupBy(sb.entity().getId()); @@ -1652,17 +1649,17 @@ public class ManagementServerImpl implements ManagementServer { sb.and("allocated", sb.entity().getAllocatedTime(), SearchCriteria.Op.NNULL); allocatedOnly = true; } - + VlanType vlanType = null; if (forVirtualNetwork != null) { vlanType = (Boolean) forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached; } else { vlanType = VlanType.VirtualNetwork; } - - //don't show SSVM/CPVM ips + + // don't show SSVM/CPVM ips if (vlanType == VlanType.VirtualNetwork && (allocatedOnly)) { - sb.and("associatedNetworkId", sb.entity().getAssociatedWithNetworkId(), SearchCriteria.Op.NNULL); + sb.and("associatedNetworkId", sb.entity().getAssociatedWithNetworkId(), SearchCriteria.Op.NNULL); } SearchCriteria sc = sb.create(); @@ -1677,15 +1674,14 @@ public class ManagementServerImpl implements ManagementServer { if (ipId != null) { sc.setParameters("id", ipId); } - + if (sourceNat != null) { sc.setParameters("isSourceNat", sourceNat); } - + if (staticNat != null) { sc.setParameters("isStaticNat", staticNat); } - if (address == null && keyword != null) { sc.setParameters("addressLIKE", "%" + keyword + "%"); @@ -1698,13 +1694,13 @@ public class ManagementServerImpl implements ManagementServer { if (vlan != null) { sc.setParameters("vlanDbId", vlan); } - + if (physicalNetworkId != null) { sc.setParameters("physicalNetworkId", physicalNetworkId); } - + if (associatedNetworkId != null) { - sc.setParameters("associatedNetworkIdEq", associatedNetworkId); + sc.setParameters("associatedNetworkIdEq", associatedNetworkId); } return _publicIpAddressDao.search(sc, searchFilter); @@ -1838,53 +1834,53 @@ public class ManagementServerImpl implements ManagementServer { // check permissions Account caller = UserContext.current().getCaller(); _accountMgr.checkAccess(caller, domain); - - //domain name is unique in the cloud + + // domain name is unique in the cloud if (domainName != null) { SearchCriteria sc = _domainDao.createSearchCriteria(); sc.addAnd("name", SearchCriteria.Op.EQ, domainName); List domains = _domainDao.search(sc, null); - + boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId); - + if (!domains.isEmpty() && !sameDomain) { throw new InvalidParameterValueException("Failed to update domain id=" + domainId + "; domain with name " + domainName + " already exists in the system"); } } - //validate network domain - if (networkDomain != null && !networkDomain.isEmpty()){ + // validate network domain + if (networkDomain != null && !networkDomain.isEmpty()) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " - + "and the hyphen ('-'); can't start or end with \"-\""); + + "and the hyphen ('-'); can't start or end with \"-\""); } } Transaction txn = Transaction.currentTxn(); - + txn.start(); - + if (domainName != null) { String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName); updateDomainChildren(domain, updatedDomainPath); domain.setName(domainName); domain.setPath(updatedDomainPath); } - + if (networkDomain != null) { - if (networkDomain.isEmpty()) { - domain.setNetworkDomain(null); - } else { + if (networkDomain.isEmpty()) { + domain.setNetworkDomain(null); + } else { domain.setNetworkDomain(networkDomain); - } + } } _domainDao.update(domainId, domain); - + txn.commit(); return _domainDao.findById(domainId); - + } private String getUpdatedDomainPath(String oldPath, String newName) { @@ -1937,154 +1933,155 @@ public class ManagementServerImpl implements ManagementServer { return _alertDao.search(sc, searchFilter); } - + @Override public List listTopConsumedResources(ListCapacityCmd cmd) { - + Integer capacityType = cmd.getType(); Long zoneId = cmd.getZoneId(); Long podId = cmd.getPodId(); Long clusterId = cmd.getClusterId(); - - if (clusterId != null){ + + if (clusterId != null) { throw new InvalidParameterValueException("Currently clusterId param is not suppoerted"); } zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); List summedCapacities = new ArrayList(); - - if (zoneId == null && podId == null){//Group by Zone, capacity type + + if (zoneId == null && podId == null) {// Group by Zone, capacity type List summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, cmd.getPageSizeVal()); - if(summedCapacitiesAtZone != null){ + if (summedCapacitiesAtZone != null) { summedCapacities.addAll(summedCapacitiesAtZone); } } - if (podId == null){//Group by Pod, capacity type + if (podId == null) {// Group by Pod, capacity type List summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, cmd.getPageSizeVal()); - if(summedCapacitiesAtPod != null){ + if (summedCapacitiesAtPod != null) { summedCapacities.addAll(summedCapacitiesAtPod); - } + } List summedCapacitiesForSecStorage = getSecStorageUsed(zoneId, capacityType); - if (summedCapacitiesForSecStorage != null){ + if (summedCapacitiesForSecStorage != null) { summedCapacities.addAll(summedCapacitiesForSecStorage); } } - - //Group by Cluster, capacity type + + // Group by Cluster, capacity type List summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, cmd.getPageSizeVal()); - if(summedCapacitiesAtCluster != null){ + if (summedCapacitiesAtCluster != null) { summedCapacities.addAll(summedCapacitiesAtCluster); - } - - //Sort Capacities + } + + // Sort Capacities Collections.sort(summedCapacities, new Comparator() { @Override public int compare(SummedCapacity arg0, SummedCapacity arg1) { if (arg0.getPercentUsed() < arg1.getPercentUsed()) { return 1; - } else if (arg0.getPercentUsed()== arg1.getPercentUsed()) { + } else if (arg0.getPercentUsed() == arg1.getPercentUsed()) { return 0; } return -1; } }); - + List capacities = new ArrayList(); - - + Integer pageSize = null; - try { - pageSize = Integer.valueOf(cmd.getPageSizeVal().toString()); - } catch(IllegalArgumentException e) { - throw new InvalidParameterValueException("pageSize " + cmd.getPageSizeVal() + " is out of Integer range is not supported for this call"); + try { + pageSize = Integer.valueOf(cmd.getPageSizeVal().toString()); + } catch (IllegalArgumentException e) { + throw new InvalidParameterValueException("pageSize " + cmd.getPageSizeVal() + " is out of Integer range is not supported for this call"); } summedCapacities = summedCapacities.subList(0, summedCapacities.size() < cmd.getPageSizeVal() ? summedCapacities.size() : pageSize); - for (SummedCapacity summedCapacity : summedCapacities){ - CapacityVO capacity = new CapacityVO(summedCapacity.getDataCenterId(), summedCapacity.getPodId() , summedCapacity.getClusterId(), - summedCapacity.getCapacityType(), summedCapacity.getPercentUsed()); + for (SummedCapacity summedCapacity : summedCapacities) { + CapacityVO capacity = new CapacityVO(summedCapacity.getDataCenterId(), summedCapacity.getPodId(), summedCapacity.getClusterId(), + summedCapacity.getCapacityType(), summedCapacity.getPercentUsed()); capacity.setUsedCapacity(summedCapacity.getUsedCapacity()); capacity.setTotalCapacity(summedCapacity.getTotalCapacity()); - capacities.add(capacity); - } + capacities.add(capacity); + } return capacities; } - - List getSecStorageUsed(Long zoneId, Integer capacityType){ - if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE){ - List list = new ArrayList(); - if (zoneId != null){ + + List getSecStorageUsed(Long zoneId, Integer capacityType) { + if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE) { + List list = new ArrayList(); + if (zoneId != null) { DataCenterVO zone = ApiDBUtils.findZoneById(zoneId); - if(zone == null || zone.getAllocationState() == AllocationState.Disabled){ - return null; + if (zone == null || zone.getAllocationState() == AllocationState.Disabled) { + return null; } CapacityVO capacity = _storageMgr.getSecondaryStorageUsedStats(null, zoneId); - if (capacity.getTotalCapacity()!= 0){ - capacity.setUsedPercentage( capacity.getUsedCapacity() / capacity.getTotalCapacity() ); - }else { + if (capacity.getTotalCapacity() != 0) { + capacity.setUsedPercentage(capacity.getUsedCapacity() / capacity.getTotalCapacity()); + } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), capacity.getClusterId()); - list.add(summedCapacity) ; - }else { + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), + capacity.getPodId(), capacity.getClusterId()); + list.add(summedCapacity); + } else { List dcList = _dcDao.listEnabledZones(); - for(DataCenterVO dc : dcList){ - CapacityVO capacity = _storageMgr.getSecondaryStorageUsedStats(null, dc.getId()); - if (capacity.getTotalCapacity()!= 0){ - capacity.setUsedPercentage( capacity.getUsedCapacity() / capacity.getTotalCapacity() ); - }else { + for (DataCenterVO dc : dcList) { + CapacityVO capacity = _storageMgr.getSecondaryStorageUsedStats(null, dc.getId()); + if (capacity.getTotalCapacity() != 0) { + capacity.setUsedPercentage(capacity.getUsedCapacity() / capacity.getTotalCapacity()); + } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), capacity.getClusterId()); + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), + capacity.getPodId(), capacity.getClusterId()); list.add(summedCapacity); - }//End of for + }// End of for } return list; } return null; } - + @Override public List listCapacities(ListCapacityCmd cmd) { - Integer capacityType = cmd.getType(); + Integer capacityType = cmd.getType(); Long zoneId = cmd.getZoneId(); Long podId = cmd.getPodId(); Long clusterId = cmd.getClusterId(); Boolean fetchLatest = cmd.getFetchLatest(); zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); - if (fetchLatest != null && fetchLatest){ - _alertMgr.recalculateCapacity(); + if (fetchLatest != null && fetchLatest) { + _alertMgr.recalculateCapacity(); } List summedCapacities = _capacityDao.findCapacityBy(capacityType, zoneId, podId, clusterId); List capacities = new ArrayList(); - for (SummedCapacity summedCapacity : summedCapacities){ - CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, - summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(), - summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType()); - - if ( summedCapacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU){ - capacity.setTotalCapacity((long)(summedCapacity.getTotalCapacity() * ApiDBUtils.getCpuOverprovisioningFactor())); - } - capacities.add(capacity); + for (SummedCapacity summedCapacity : summedCapacities) { + CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, + summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(), + summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType()); + + if (summedCapacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { + capacity.setTotalCapacity((long) (summedCapacity.getTotalCapacity() * ApiDBUtils.getCpuOverprovisioningFactor())); + } + capacities.add(capacity); } // op_host_Capacity contains only allocated stats and the real time stats are stored "in memory". // Show Sec. Storage only when the api is invoked for the zone layer. List dcList = new ArrayList(); - if (zoneId==null && podId==null && clusterId==null){ + if (zoneId == null && podId == null && clusterId == null) { dcList = ApiDBUtils.listZones(); - }else if (zoneId != null){ + } else if (zoneId != null) { dcList.add(ApiDBUtils.findZoneById(zoneId)); - }else{ + } else { if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) { capacities.add(_storageMgr.getStoragePoolUsedStats(null, clusterId, podId, zoneId)); } } - - for(DataCenterVO zone : dcList){ + + for (DataCenterVO zone : dcList) { zoneId = zone.getId(); if ((capacityType == null || capacityType == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE) && podId == null && clusterId == null) { capacities.add(_storageMgr.getSecondaryStorageUsedStats(null, zoneId)); @@ -2108,9 +2105,9 @@ public class ManagementServerImpl implements ManagementServer { return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } - private List searchDiskOfferingsInternal(Account account, Object name, Object id, Object keyword, Filter searchFilter) { - // it was decided to return all offerings for the user's domain, and everything above till root (for normal user or + // it was decided to return all offerings for the user's domain, and everything above till root (for normal user +// or // domain admin) // list all offerings belonging to this domain, and all of its parents // check the parent, if not null, add offerings for that parent to list @@ -2178,11 +2175,12 @@ public class ManagementServerImpl implements ManagementServer { // The list method for offerings is being modified in accordance with discussion with Will/Kevin // For now, we will be listing the following based on the usertype // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way till + // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way +// till // root - Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); - isAscending = (isAscending == null ? true : isAscending); + Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); + isAscending = (isAscending == null ? true : isAscending); Filter searchFilter = new Filter(DiskOfferingVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); @@ -2247,7 +2245,8 @@ public class ManagementServerImpl implements ManagementServer { // FIXME: disk offerings should search back up the hierarchy for available disk offerings... /* * if (domainId != null) { sc.setParameters("domainId", domainId); // //DomainVO domain = - * _domainDao.findById((Long)domainId); // // I want to join on user_vm.domain_id = domain.id where domain.path like + * _domainDao.findById((Long)domainId); // // I want to join on user_vm.domain_id = domain.id where domain.path + * like * 'foo%' //sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); // } */ @@ -2362,80 +2361,79 @@ public class ManagementServerImpl implements ManagementServer { return _poolDao.search(sc, searchFilter); } - @Override public List searchForAsyncJobs(ListAsyncJobsCmd cmd) { - - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(AsyncJobVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _jobDao.createSearchBuilder(); - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); - SearchBuilder accountSearch = null; - boolean accountJoinIsDone = false; - if (permittedAccounts.isEmpty() && domainId != null) { - accountSearch = _accountDao.createSearchBuilder(); - // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("domainId", domainSearch.entity().getId(), SearchCriteria.Op.EQ); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - accountJoinIsDone = true; - accountSearch.join("domainSearch", domainSearch, accountSearch.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (listProjectResourcesCriteria != null) { - if (accountSearch == null) { - accountSearch = _accountDao.createSearchBuilder(); - } - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); - } - - if (!accountJoinIsDone) { - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - } - - Object keyword = cmd.getKeyword(); - Object startDate = cmd.getStartDate(); + Account caller = UserContext.current().getCaller(); - SearchCriteria sc = sb.create(); - if (listProjectResourcesCriteria != null) { - sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); - } - - if (!permittedAccounts.isEmpty()) { - sc.setParameters("accountIdIN", permittedAccounts.toArray()); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setJoinParameters("domainSearch", "domainId", domainId); - } - } - - if (keyword != null) { - sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - } + List permittedAccounts = new ArrayList(); - if (startDate != null) { - sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate); - } + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - return _jobDao.search(sc, searchFilter); - } + Filter searchFilter = new Filter(AsyncJobVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _jobDao.createSearchBuilder(); + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); + SearchBuilder accountSearch = null; + boolean accountJoinIsDone = false; + if (permittedAccounts.isEmpty() && domainId != null) { + accountSearch = _accountDao.createSearchBuilder(); + // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true + SearchBuilder domainSearch = _domainDao.createSearchBuilder(); + domainSearch.and("domainId", domainSearch.entity().getId(), SearchCriteria.Op.EQ); + domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); + sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + accountJoinIsDone = true; + accountSearch.join("domainSearch", domainSearch, accountSearch.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } + + if (listProjectResourcesCriteria != null) { + if (accountSearch == null) { + accountSearch = _accountDao.createSearchBuilder(); + } + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); + } + + if (!accountJoinIsDone) { + sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); + } + } + + Object keyword = cmd.getKeyword(); + Object startDate = cmd.getStartDate(); + + SearchCriteria sc = sb.create(); + if (listProjectResourcesCriteria != null) { + sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); + } + + if (!permittedAccounts.isEmpty()) { + sc.setParameters("accountIdIN", permittedAccounts.toArray()); + } else if (domainId != null) { + DomainVO domain = _domainDao.findById(domainId); + if (isRecursive) { + sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); + } else { + sc.setJoinParameters("domainSearch", "domainId", domainId); + } + } + + if (keyword != null) { + sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + } + + if (startDate != null) { + sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate); + } + + return _jobDao.search(sc, searchFilter); + } @ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true) public SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) { @@ -2636,7 +2634,7 @@ public class ManagementServerImpl implements ManagementServer { if ((user == null) || (user.getRemoved() != null)) { throw new InvalidParameterValueException("Unable to find active user by id " + userId); } - + // check permissions _accountMgr.checkAccess(caller, null, true, _accountMgr.getAccount(user.getAccountId())); @@ -2674,7 +2672,7 @@ public class ManagementServerImpl implements ManagementServer { if (networks != null && !networks.isEmpty()) { securityGroupsEnabled = true; String elbEnabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key()); - elasticLoadBalancerEnabled = elbEnabled==null?false:Boolean.parseBoolean(elbEnabled); + elasticLoadBalancerEnabled = elbEnabled == null ? false : Boolean.parseBoolean(elbEnabled); if (elasticLoadBalancerEnabled) { String networkType = _configDao.getValue(Config.ElasticLoadBalancerNetwork.key()); if (networkType != null) @@ -2711,13 +2709,13 @@ public class ManagementServerImpl implements ManagementServer { if (!_accountMgr.isRootAdmin(account.getType()) && ApiDBUtils.isExtractionDisabled()) { throw new PermissionDeniedException("Extraction has been disabled by admin"); } - + VolumeVO volume = _volumeDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException("Unable to find volume with id " + volumeId); } - - //perform permission check + + // perform permission check _accountMgr.checkAccess(account, null, true, volume); if (_dcDao.findById(zoneId) == null) { @@ -2731,16 +2729,18 @@ public class ManagementServerImpl implements ManagementServer { s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state."); throw new PermissionDeniedException("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state."); } - - if (volume.getVolumeType() != Volume.Type.DATADISK){ //Datadisk dont have any template dependence. - - VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - if (template != null){ //For ISO based volumes template = null and we allow extraction of all ISO based volumes - boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; - if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global admins are always allowed to extract - throw new PermissionDeniedException("The volume:" + volumeId + " is not allowed to be extracted"); - } - } + + if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont have any template dependence. + + VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); + if (template != null) { // For ISO based volumes template = null and we allow extraction of all ISO based +// volumes + boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; + if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global +// admins are always allowed to extract + throw new PermissionDeniedException("The volume:" + volumeId + " is not allowed to be extracted"); + } + } } Upload.Mode extractMode; @@ -2749,7 +2749,7 @@ public class ManagementServerImpl implements ManagementServer { } else { extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD; } - + // If mode is upload perform extra checks on url and also see if there is an ongoing upload on the same. if (extractMode == Upload.Mode.FTP_UPLOAD) { URI uri = new URI(url); @@ -2801,7 +2801,7 @@ public class ManagementServerImpl implements ManagementServer { _asyncMgr.updateAsyncJobStatus(job.getId(), AsyncJobResult.STATUS_IN_PROGRESS, resultObj); } String value = _configs.get(Config.CopyVolumeWait.toString()); - int copyvolumewait = NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue())); + int copyvolumewait = NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue())); // Copy the volume from the source storage pool to secondary storage CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true, copyvolumewait); CopyVolumeAnswer cvAnswer = null; @@ -2848,23 +2848,22 @@ public class ManagementServerImpl implements ManagementServer { } } - private String getFormatForPool(StoragePoolVO pool){ - ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId()); - - if (cluster.getHypervisorType() == HypervisorType.XenServer){ - return "vhd"; - }else if (cluster.getHypervisorType() == HypervisorType.KVM){ - return "qcow2"; - }else if (cluster.getHypervisorType() == HypervisorType.VMware){ - return "ova"; - }else if (cluster.getHypervisorType() == HypervisorType.Ovm){ - return "raw"; - }else{ - return null; - } + private String getFormatForPool(StoragePoolVO pool) { + ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId()); + + if (cluster.getHypervisorType() == HypervisorType.XenServer) { + return "vhd"; + } else if (cluster.getHypervisorType() == HypervisorType.KVM) { + return "qcow2"; + } else if (cluster.getHypervisorType() == HypervisorType.VMware) { + return "ova"; + } else if (cluster.getHypervisorType() == HypervisorType.Ovm) { + return "raw"; + } else { + return null; + } } - - + @Override public InstanceGroupVO updateVmGroup(UpdateVMGroupCmd cmd) { Account caller = UserContext.current().getCaller(); @@ -2898,7 +2897,7 @@ public class ManagementServerImpl implements ManagementServer { Long id = cmd.getId(); String name = cmd.getGroupName(); String keyword = cmd.getKeyword(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -2906,12 +2905,12 @@ public class ManagementServerImpl implements ManagementServer { _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(InstanceGroupVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - + SearchBuilder sb = _vmGroupDao.createSearchBuilder(); - + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { @@ -2920,23 +2919,23 @@ public class ManagementServerImpl implements ManagementServer { domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); } - + if (listProjectResourcesCriteria != null) { - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); - } + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); + } } - + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); SearchCriteria sc = sb.create(); if (listProjectResourcesCriteria != null) { - sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT); + sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT); } - + if (!permittedAccounts.isEmpty()) { sc.setParameters("accountIdIN", permittedAccounts.toArray()); } else if (domainId != null) { @@ -2988,28 +2987,28 @@ public class ManagementServerImpl implements ManagementServer { @Override @DB public String uploadCertificate(UploadCustomCertificateCmd cmd) { - if (cmd.getPrivateKey() != null && cmd.getAlias() != null) { - throw new InvalidParameterValueException("Can't change the alias for private key certification"); - } - - if (cmd.getPrivateKey() == null) { - if (cmd.getAlias() == null) { - throw new InvalidParameterValueException("alias can't be empty, if it's a certification chain"); - } - - if (cmd.getCertIndex() == null) { - throw new InvalidParameterValueException("index can't be empty, if it's a certifciation chain"); - } - } - - if (cmd.getPrivateKey() != null &&!_ksMgr.validateCertificate(cmd.getCertificate(), cmd.getPrivateKey(), cmd.getDomainSuffix())) { + if (cmd.getPrivateKey() != null && cmd.getAlias() != null) { + throw new InvalidParameterValueException("Can't change the alias for private key certification"); + } + + if (cmd.getPrivateKey() == null) { + if (cmd.getAlias() == null) { + throw new InvalidParameterValueException("alias can't be empty, if it's a certification chain"); + } + + if (cmd.getCertIndex() == null) { + throw new InvalidParameterValueException("index can't be empty, if it's a certifciation chain"); + } + } + + if (cmd.getPrivateKey() != null && !_ksMgr.validateCertificate(cmd.getCertificate(), cmd.getPrivateKey(), cmd.getDomainSuffix())) { throw new InvalidParameterValueException("Failed to pass certificate validation check"); } if (cmd.getPrivateKey() != null) { - _ksMgr.saveCertificate(ConsoleProxyManager.CERTIFICATE_NAME, cmd.getCertificate(), cmd.getPrivateKey(), cmd.getDomainSuffix()); + _ksMgr.saveCertificate(ConsoleProxyManager.CERTIFICATE_NAME, cmd.getCertificate(), cmd.getPrivateKey(), cmd.getDomainSuffix()); } else { - _ksMgr.saveCertificate(cmd.getAlias(), cmd.getCertificate(), cmd.getCertIndex(), cmd.getDomainSuffix()); + _ksMgr.saveCertificate(cmd.getAlias(), cmd.getCertificate(), cmd.getCertIndex(), cmd.getDomainSuffix()); } _consoleProxyMgr.setManagementState(ConsoleProxyManagementState.ResetSuspending); @@ -3091,7 +3090,7 @@ public class ManagementServerImpl implements ManagementServer { String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); Long projectId = cmd.getProjectId(); - + Account owner = _accountMgr.finalizeOwner(caller, accountName, domainId, projectId); SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); @@ -3106,7 +3105,7 @@ public class ManagementServerImpl implements ManagementServer { public List listSSHKeyPairs(ListSSHKeyPairsCmd cmd) { String name = cmd.getName(); String fingerPrint = cmd.getFingerprint(); - + Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -3114,7 +3113,8 @@ public class ManagementServerImpl implements ManagementServer { _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); SearchBuilder sb = _sshKeyPairDao.createSearchBuilder(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + SearchBuilder sb = _sshKeyPairDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); Filter searchFilter = new Filter(SSHKeyPairVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -3135,9 +3135,9 @@ public class ManagementServerImpl implements ManagementServer { @Override public SSHKeyPair registerSSHKeyPair(RegisterSSHKeyPairCmd cmd) { Account caller = UserContext.current().getCaller(); - + Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId()); - + SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s != null) { throw new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' already exists."); @@ -3145,11 +3145,11 @@ public class ManagementServerImpl implements ManagementServer { String name = cmd.getName(); String publicKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(cmd.getPublicKey()); - + if (publicKey == null) { throw new InvalidParameterValueException("Public key is invalid"); } - + String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(publicKey); return createAndSaveSSHKeyPair(name, fingerprint, publicKey, null, owner); @@ -3200,19 +3200,19 @@ public class ManagementServerImpl implements ManagementServer { HostVO host = _hostDao.findById(cmd.getHostId()); if (host != null && host.getHypervisorType() == HypervisorType.XenServer) { throw new InvalidParameterValueException("You should provide cluster id for Xenserver cluster."); - }else { + } else { throw new InvalidParameterValueException("This operation is not supported for this hypervisor type"); } } else { - + ClusterVO cluster = ApiDBUtils.findClusterById(cmd.getClusterId()); - if (cluster == null || cluster.getHypervisorType() != HypervisorType.XenServer){ + if (cluster == null || cluster.getHypervisorType() != HypervisorType.XenServer) { throw new InvalidParameterValueException("This operation is not supported for this hypervisor type"); } // get all the hosts in this cluster List hosts = _resourceMgr.listAllHostsInCluster(cmd.getClusterId()); Transaction txn = Transaction.currentTxn(); - try{ + try { txn.start(); for (HostVO h : hosts) { if (s_logger.isDebugEnabled()) { @@ -3232,24 +3232,24 @@ public class ManagementServerImpl implements ManagementServer { } txn.commit(); // if hypervisor is xenserver then we update it in CitrixResourceBase - }catch (Exception e) { + } catch (Exception e) { txn.rollback(); - throw new CloudRuntimeException("Failed to update password " + e.getMessage()); + throw new CloudRuntimeException("Failed to update password " + e.getMessage()); } } - + return true; } @Override - public String[] listEventTypes(){ - Object eventObj = new EventTypes(); + public String[] listEventTypes() { + Object eventObj = new EventTypes(); Class c = EventTypes.class; Field[] fields = c.getDeclaredFields(); String[] eventTypes = new String[fields.length]; try { int i = 0; - for(Field field : fields){ + for (Field field : fields) { eventTypes[i++] = field.get(eventObj).toString(); } return eventTypes; @@ -3260,9 +3260,9 @@ public class ManagementServerImpl implements ManagementServer { } return null; } - + @Override - public List listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal){ + public List listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal) { Filter searchFilter = new Filter(HypervisorCapabilitiesVO.class, "id", true, startIndex, pageSizeVal); SearchCriteria sc = _hypervisorCapabilitiesDao.createSearchCriteria(); @@ -3279,39 +3279,38 @@ public class ManagementServerImpl implements ManagementServer { ssc.addOr("hypervisorType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); sc.addAnd("hypervisorType", SearchCriteria.Op.SC, ssc); } - + return _hypervisorCapabilitiesDao.search(sc, searchFilter); - + } - + @Override - public HypervisorCapabilities updateHypervisorCapabilities(Long id, Long maxGuestsLimit, Boolean securityGroupEnabled){ + public HypervisorCapabilities updateHypervisorCapabilities(Long id, Long maxGuestsLimit, Boolean securityGroupEnabled) { HypervisorCapabilitiesVO hpvCapabilities = _hypervisorCapabilitiesDao.findById(id, true); - - if(hpvCapabilities == null){ + + if (hpvCapabilities == null) { throw new InvalidParameterValueException("unable to find the hypervisor capabilities " + id); } - + boolean updateNeeded = (maxGuestsLimit != null || securityGroupEnabled != null); if (!updateNeeded) { return hpvCapabilities; } - - + hpvCapabilities = _hypervisorCapabilitiesDao.createForUpdate(id); - if (maxGuestsLimit != null){ + if (maxGuestsLimit != null) { hpvCapabilities.setMaxGuestsLimit(maxGuestsLimit); } - - if (securityGroupEnabled != null){ + + if (securityGroupEnabled != null) { hpvCapabilities.setSecurityGroupEnabled(securityGroupEnabled); } - if (_hypervisorCapabilitiesDao.update(id, hpvCapabilities)){ + if (_hypervisorCapabilitiesDao.update(id, hpvCapabilities)) { hpvCapabilities = _hypervisorCapabilitiesDao.findById(id); UserContext.current().setEventDetails("Hypervisor Capabilities id=" + hpvCapabilities.getId()); - return hpvCapabilities; + return hpvCapabilities; } else { return null; } diff --git a/test/src/com/cloud/test/regression/ApiCommand.java b/test/src/com/cloud/test/regression/ApiCommand.java index 9358b888af0..1b71e95bcf4 100644 --- a/test/src/com/cloud/test/regression/ApiCommand.java +++ b/test/src/com/cloud/test/regression/ApiCommand.java @@ -1,6 +1,6 @@ /** * * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved -* + * * * This software is licensed under the GNU General Public License v3 or later. * @@ -17,7 +17,7 @@ * */ -package com.cloud.test.regression; +package com.cloud.test.regression; import java.io.File; import java.io.FileInputStream; @@ -49,17 +49,18 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.cloud.test.utils.UtilsForTest; - -public class ApiCommand{ + +public class ApiCommand { public static final Logger s_logger = Logger.getLogger(ApiCommand.class.getName()); - public static enum CommandType{ + + public static enum CommandType { HTTP, MYSQL, SCRIPT; } - - public static enum ResponseType{ + + public static enum ResponseType { ERROR, EMPTY; } - + private Element xmlCommand; private String commandName; private String testCaseInfo; @@ -67,41 +68,40 @@ public class ApiCommand{ private boolean isAsync = false; private CommandType commandType; private ResponseType responseType; - - - private TreeMap urlParam; - private HashMap verifyParam = new HashMap();; - private HashMap setParam = new HashMap();; - private int responseCode; - private Element responseBody; - - private String command; - private String host; - private boolean list; - private Element listName; - private Element listId; - private boolean required = false; - private ResultSet result; - - - public ApiCommand(Element fstElmnt, HashMap param, HashMap commands){ - this.setXmlCommand(fstElmnt); - this.setCommandName(); - this.setResponseType(); - this.setUserCommand(); - this.setCommandType(); - this.setTestCaseInfo(); - this.setUrlParam(param); - this.setVerifyParam(param); - this.setHost("http://" + param.get("hostip")); - this.setCommand(param); - String async = commands.get(this.getName()); - if (async != null && async.equals("yes")) { + + private TreeMap urlParam; + private HashMap verifyParam = new HashMap();; + private HashMap setParam = new HashMap();; + private int responseCode; + private Element responseBody; + + private String command; + private String host; + private boolean list; + private Element listName; + private Element listId; + private boolean required = false; + private ResultSet result; + + public ApiCommand(Element fstElmnt, HashMap param, HashMap commands) { + this.setXmlCommand(fstElmnt); + this.setCommandName(); + this.setResponseType(); + this.setUserCommand(); + this.setCommandType(); + this.setTestCaseInfo(); + this.setUrlParam(param); + this.setVerifyParam(param); + this.setHost("http://" + param.get("hostip")); + this.setCommand(param); + String async = commands.get(this.getName()); + if (async != null && async.equals("yes")) { this.isAsync = true; - } - } - - public Element getXmlCommand() { + + } + } + + public Element getXmlCommand() { return xmlCommand; } @@ -109,43 +109,43 @@ public class ApiCommand{ this.xmlCommand = xmlCommand; } - //================FOLLOWING METHODS USE INPUT XML FILE=======================// - public void setCommandName() { - NodeList commandName = this.xmlCommand.getElementsByTagName("name"); - Element commandElmnt = (Element) commandName.item(0); - NodeList commandNm = commandElmnt.getChildNodes(); - this.commandName = (((Node) commandNm.item(0)).getNodeValue()); - } - + // ================FOLLOWING METHODS USE INPUT XML FILE=======================// + public void setCommandName() { + NodeList commandName = this.xmlCommand.getElementsByTagName("name"); + Element commandElmnt = (Element) commandName.item(0); + NodeList commandNm = commandElmnt.getChildNodes(); + this.commandName = (((Node) commandNm.item(0)).getNodeValue()); + } + public String getName() { return commandName; - } - - public void setTestCaseInfo() { - this.testCaseInfo = getElementByName("testcase"); - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public void setResponseType() { - boolean result = verifyTagValue("error", "true"); - if (result) { - this.responseType = ResponseType.ERROR; - return; - } - result = verifyTagValue("empty", "true"); - if (result) { + } + + public void setTestCaseInfo() { + this.testCaseInfo = getElementByName("testcase"); + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public void setResponseType() { + boolean result = verifyTagValue("error", "true"); + if (result) { + this.responseType = ResponseType.ERROR; + return; + } + result = verifyTagValue("empty", "true"); + if (result) { this.responseType = ResponseType.EMPTY; - } - } - - public void setResponseType(ResponseType responseType) { + } + } + + public void setResponseType(ResponseType responseType) { this.responseType = responseType; } @@ -155,11 +155,11 @@ public class ApiCommand{ public void setUserCommand() { boolean result = verifyTagValue("usercommand", "true"); - this.isUserCommand = result; - } - - public void setCommandType() { - boolean result = verifyTagValue("mysql", "true"); + this.isUserCommand = result; + } + + public void setCommandType() { + boolean result = verifyTagValue("mysql", "true"); if (result) { this.commandType = CommandType.MYSQL; return; @@ -170,686 +170,682 @@ public class ApiCommand{ return; } this.commandType = CommandType.HTTP; - } - - public CommandType getCommandType() { + } + + public CommandType getCommandType() { return commandType; - } - - public String getTestCaseInfo() { - return testCaseInfo; - } - - public Boolean getRequired() { - return required; - } - - public void setUrlParam(HashMap param) { - this.urlParam = new TreeMap(); - NodeList parameterLst= this.xmlCommand.getElementsByTagName("parameters"); - if (parameterLst != null ) { - for (int j=0; j param) { - - if (this.getCommandType() == CommandType.SCRIPT) { - String temp = "bash xen/" + this.commandName; - Set c = this.urlParam.entrySet(); - Iterator it = c.iterator(); - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - try { - temp = temp + " -" + key + " " + value; - } catch (Exception ex) { - s_logger.error("Unable to set parameter " + key + " for the command " + this.getName()); - } - } - this.command = temp; - } else if (this.getCommandType() == CommandType.MYSQL) { - String temp = this.commandName + " where "; - Set c = this.urlParam.entrySet(); - Iterator it = c.iterator(); - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - try { - temp = temp + key + "=" + value; - } catch (Exception ex) { - s_logger.error("Unable to set parameter " + key + " for the command " + this.getName()); - } - } - this.command = temp; - s_logger.info("The command is " + this.command); - - } else { - if ((param.get("apikey") == null) || (param.get("secretkey")==null) || (this.isUserCommand == false)) { - String temp = this.host + ":8096/?command="+ this.commandName; - Set c = this.urlParam.entrySet(); - Iterator it = c.iterator(); - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - try { - temp = temp + "&" + key + "=" + URLEncoder.encode(value, "UTF-8"); - } catch (Exception ex) { - s_logger.error("Unable to set parameter " + key + " for the command " + this.getName()); - } - } - this.command = temp; - } - else if (isUserCommand == true) { - String apiKey = param.get("apikey"); - String secretKey = param.get("secretkey"); - - String temp = ""; - this.urlParam.put("apikey", apiKey); - this.urlParam.put("command", this.commandName); - - //sort url hash map by key - Set c = this.urlParam.entrySet(); - Iterator it = c.iterator(); - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - try { - temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&"; - } catch (Exception ex) { - s_logger.error("Unable to set parameter " + value + " for the command " + this.getName()); - } - - } - temp = temp.substring(0, temp.length()-1 ); - String requestToSign = temp.toLowerCase(); - String signature = UtilsForTest.signRequest(requestToSign, secretKey); - String encodedSignature = ""; - try { - encodedSignature = URLEncoder.encode(signature, "UTF-8"); - } catch (Exception ex) { - s_logger.error(ex); - } - this.command = this.host + ":8080/client/api/?" + temp + "&signature=" + encodedSignature; - } - } - } - - public void setVerifyParam(HashMap param) { - NodeList returnLst= this.xmlCommand.getElementsByTagName("returnvalue"); - if (returnLst != null ) { - for (int m=0; m param) { - if ((this.responseBody == null) && (this.commandType == CommandType.HTTP)) { - s_logger.error("Response body is empty"); - return false; - } - Boolean result = true; - - if (this.getCommandType() == CommandType.MYSQL) { - Set set = this.setParam.entrySet(); - Iterator it = set.iterator(); - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - try { - String itemName = null; - while (this.result.next()) { - itemName = this.result.getString(value); - } - if (itemName != null) { - param.put(key, itemName); - } - else { - s_logger.error("Following return parameter is missing: " + value); - result = false; - } - } catch (Exception ex) { - s_logger.error("Unable to set parameter " + value, ex); - } - } - } else if (this.getCommandType() == CommandType.HTTP) { - if (this.list == false) { - Set set = this.setParam.entrySet(); - Iterator it = set.iterator(); - - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - //set parameters needed for the future use - NodeList itemName = this.responseBody.getElementsByTagName(value); - if ((itemName != null) && (itemName.getLength() != 0)) { - for (int i=0; i < itemName.getLength(); i++) { - Element itemNameElement = (Element) itemName.item(i); - if (itemNameElement.getChildNodes().getLength() <= 1) { - param.put(key, itemNameElement.getTextContent()); - break; - } - } - } - else { - s_logger.error("Following return parameter is missing: " + value); - result = false; - } - } - } else { - Set set = this.setParam.entrySet(); - Iterator it = set.iterator(); - NodeList returnLst = this.responseBody.getElementsByTagName(this.listName.getTextContent()); - Node requiredNode = returnLst.item(Integer.parseInt(this.listId.getTextContent())); + public String getTestCaseInfo() { + return testCaseInfo; + } - if (requiredNode.getNodeType() == Node.ELEMENT_NODE) { - Element fstElmnt = (Element) requiredNode; - - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - NodeList itemName = fstElmnt.getElementsByTagName(value); - if ((itemName != null) && (itemName.getLength() != 0)) { - Element itemNameElement = (Element) itemName.item(0); - if (itemNameElement.getChildNodes().getLength() <= 1) { - param.put(key, itemNameElement.getTextContent()); - } - } - else { - s_logger.error("Following return parameter is missing: " + value); - result = false; - } - } - } - } - } - return result; - } - - public String getUrl() { - return command; - } - - public boolean verifyParam() { - boolean result = true; - if (this.getCommandType() == CommandType.HTTP) { - if (this.list == false) { - Set set = verifyParam.entrySet(); - Iterator it = set.iterator(); - - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - if (value == null) { - s_logger.error("Parameter " + key + " is missing in the list of global parameters"); - return false; - } - - NodeList itemName = this.responseBody.getElementsByTagName(key); - if ((itemName.getLength() != 0) && (itemName != null)) { - Element itemNameElement = (Element) itemName.item(0); - if (itemNameElement.hasChildNodes()) { - continue; - } - if ( !(verifyParam.get(key).equals("no value")) && !(itemNameElement.getTextContent().equals(verifyParam.get(key)))){ - s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is " + verifyParam.get(key) + " while actual value is " + itemNameElement.getTextContent()); - result = false; - } - } else { - s_logger.error("Following xml element is missing in the response: " + key); - result=false; - } - } - } - //for multiple elements - else { - Set set = verifyParam.entrySet(); - Iterator it = set.iterator(); - //get list element specified by id - NodeList returnLst = this.responseBody.getElementsByTagName(this.listName.getTextContent()); - Node requiredNode = returnLst.item(Integer.parseInt(this.listId.getTextContent())); + public Boolean getRequired() { + return required; + } - if (requiredNode.getNodeType() == Node.ELEMENT_NODE) { - Element fstElmnt = (Element) requiredNode; - - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - if (value == null) { - s_logger.error("Parameter " + key + " is missing in the list of global parameters"); - return false; - } - NodeList itemName = fstElmnt.getElementsByTagName(key); - if ((itemName.getLength() != 0) && (itemName != null)) { - Element itemNameElement = (Element) itemName.item(0); - if ( !(verifyParam.get(key).equals("no value")) && !(itemNameElement.getTextContent().equals(verifyParam.get(key)))){ - s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is " + verifyParam.get(key) + " while actual value is " + itemNameElement.getTextContent()); - result = false; - } - } else { - s_logger.error("Following xml element is missing in the response: " + key); - result = false; - } - } - } - } - } else if (this.getCommandType() == CommandType.MYSQL) { - Set set = verifyParam.entrySet(); - Iterator it = set.iterator(); - - while (it.hasNext()) { - Map.Entry me = (Map.Entry)it.next(); - String key = (String) me.getKey(); - String value = (String) me.getValue(); - if (value == null) { - s_logger.error("Parameter " + key + " is missing in the list of global parameters"); - return false; - } - - String itemName = null; - try { - while(this.result.next()) { - itemName = this.result.getString(key); - } - } catch (Exception ex) { - s_logger.error("Unable to get element from result set " + key); - } - - if ( !(value.equals("no value")) && !(itemName.equals(verifyParam.get(key)))){ - s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is " + verifyParam.get(key) + " while actual value is " + itemName); - result = false; - } - } - } - return result; - } - - public static boolean verifyEvents (String fileName, String level, String host, String account) { - boolean result=false; - HashMap expectedEvents = new HashMap (); - HashMap actualEvents = new HashMap (); - String key = ""; - - File file = new File(fileName); - if (file.exists()) { - Properties pro = new Properties(); - try { - //get expected events - FileInputStream in = new FileInputStream(file); - pro.load(in); - Enumeration en = pro.propertyNames(); - while (en.hasMoreElements()) { - key = (String) en.nextElement(); - expectedEvents.put(key, Integer.parseInt(pro.getProperty(key))); - } - - //get actual events - String url = host + "/?command=listEvents&account=" + account + "&level=" + level + "&domainid=1&pagesize=100"; - s_logger.info("Getting events with the following url " + url); - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - if (responseCode == 200 ) { - InputStream is = method.getResponseBodyAsStream(); - ArrayList> eventValues = UtilsForTest.parseMulXML( - is, new String[] { "event" }); - - for (int i=0; i< eventValues.size(); i++) { - HashMap element = eventValues.get(i); - if (element.get("level").equals(level)) { - if (actualEvents.containsKey(element.get("type")) == true){ - actualEvents.put(element.get("type"), actualEvents.get(element.get("type"))+1); - } - else { - actualEvents.put(element.get("type"), 1); - } - } - } - } - method.releaseConnection(); - - //compare actual events with expected events - - //compare expected result and actual result - Iterator iterator = expectedEvents.keySet().iterator(); - Integer expected; - Integer actual; - int fail=0; - while (iterator.hasNext()) { - expected=null; - actual=null; - String type = iterator.next().toString(); - expected = expectedEvents.get(type); - actual = actualEvents.get(type); - if (actual == null ) { - s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " + expected); - fail++; - } else if (expected.compareTo(actual) != 0){ - fail++; - s_logger.info("Amount of events of " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected + ", actual number is " + actual); - } - } - if (fail == 0) { - result = true; - } - } catch (Exception ex) { - s_logger.error(ex); - } - }else { - s_logger.info("File " + fileName + " not found"); - } - return result; - } - - - public static boolean verifyEvents (HashMap expectedEvents, String level, String host, String parameters) { - boolean result=false; - HashMap actualEvents = new HashMap (); - try { - //get actual events - String url = host + "/?command=listEvents&" + parameters; - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(url); - int responseCode = client.executeMethod(method); - if (responseCode == 200 ) { - InputStream is = method.getResponseBodyAsStream(); - ArrayList> eventValues = UtilsForTest.parseMulXML( - is, new String[] { "event" }); - - for (int i=0; i< eventValues.size(); i++) { - HashMap element = eventValues.get(i); - if (element.get("level").equals(level)) { - if (actualEvents.containsKey(element.get("type")) == true){ - actualEvents.put(element.get("type"), actualEvents.get(element.get("type"))+1); - } - else { - actualEvents.put(element.get("type"), 1); - } - } - } - } - method.releaseConnection(); - }catch (Exception ex) { - s_logger.error(ex); - } - - //compare actual events with expected events - Iterator iterator = expectedEvents.keySet().iterator(); - Integer expected; - Integer actual; - int fail=0; - while (iterator.hasNext()) { - expected=null; - actual=null; - String type = iterator.next().toString(); - expected = expectedEvents.get(type); - actual = actualEvents.get(type); - if (actual == null ) { - s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " + expected); - fail++; - } - else if (expected.compareTo(actual) != 0){ - fail++; - s_logger.info("Amount of events of " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected + ", actual number is " + actual); - } - } - - if (fail == 0) { - result = true; - } - - return result; - } - - - public Element queryAsyncJobResult (String jobId) { - Element returnBody = null; - int code = 400; - String resultUrl = this.host + ":8096/?command=queryAsyncJobResult&jobid=" + jobId; - HttpClient client = new HttpClient(); - HttpMethod method = new GetMethod(resultUrl); - while (true) { - try { - code = client.executeMethod(method); - if (code == 200) { - InputStream is = method.getResponseBodyAsStream(); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(is); - doc.getDocumentElement().normalize(); - returnBody = doc.getDocumentElement(); - Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0); - String jobStatus = jobStatusTag.getTextContent(); - if(jobStatus.equals("0")) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } else { - break; - } - method.releaseConnection(); - } - else { - s_logger.error("Error during queryJobAsync. Error code is " + code); - this.responseCode = code; - return null; - } - } catch (Exception ex) { - s_logger.error(ex); - } - } - return returnBody; - } - - private String getElementByName(String elementName){ - NodeList commandName = this.xmlCommand.getElementsByTagName(elementName); + public void setUrlParam(HashMap param) { + this.urlParam = new TreeMap(); + NodeList parameterLst = this.xmlCommand.getElementsByTagName("parameters"); + if (parameterLst != null) { + for (int j = 0; j < parameterLst.getLength(); j++) { + Element parameterElement = (Element) parameterLst.item(j); + NodeList itemLst = parameterElement.getElementsByTagName("item"); + for (int k = 0; k < itemLst.getLength(); k++) { + Node item = itemLst.item(k); + if (item.getNodeType() == Node.ELEMENT_NODE) { + Element itemElement = (Element) item; + NodeList itemName = itemElement.getElementsByTagName("name"); + Element itemNameElement = (Element) itemName.item(0); + + // get value + Element itemValueElement = null; + if ((itemElement.getElementsByTagName("value") != null) && (itemElement.getElementsByTagName("value").getLength() != 0)) { + NodeList itemValue = itemElement.getElementsByTagName("value"); + itemValueElement = (Element) itemValue.item(0); + } + + Element itemParamElement = null; + // getparam + if ((itemElement.getElementsByTagName("param") != null) && (itemElement.getElementsByTagName("param").getLength() != 0)) { + NodeList itemParam = itemElement.getElementsByTagName("param"); + itemParamElement = (Element) itemParam.item(0); + } + + if ((itemElement.getAttribute("getparam").equals("true")) && (itemParamElement != null)) { + this.urlParam.put(itemNameElement.getTextContent(), param.get(itemParamElement.getTextContent())); + } + else if (itemValueElement != null) { + this.urlParam.put(itemNameElement.getTextContent(), itemValueElement.getTextContent()); + } else if (itemElement.getAttribute("random").equals("true")) { + Random ran = new Random(); + String randomString = Math.abs(ran.nextInt()) + "-randomName"; + this.urlParam.put(itemNameElement.getTextContent(), randomString); + if ((itemElement.getAttribute("setparam").equals("true")) && (itemParamElement != null)) { + param.put(itemParamElement.getTextContent(), randomString); + } + } else if (itemElement.getAttribute("randomnumber").equals("true")) { + Random ran = new Random(); + Integer randomNumber = (Integer) Math.abs(ran.nextInt(65535)); + this.urlParam.put(itemNameElement.getTextContent(), randomNumber.toString()); + if ((itemElement.getAttribute("setparam").equals("true")) && (itemParamElement != null)) { + param.put(itemParamElement.getTextContent(), randomNumber.toString()); + } + } + } + } + } + } + } + + // Set command URL + public void setCommand(HashMap param) { + + if (this.getCommandType() == CommandType.SCRIPT) { + String temp = "bash xen/" + this.commandName; + Set c = this.urlParam.entrySet(); + Iterator it = c.iterator(); + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + try { + temp = temp + " -" + key + " " + value; + } catch (Exception ex) { + s_logger.error("Unable to set parameter " + key + " for the command " + this.getName()); + } + } + this.command = temp; + } else if (this.getCommandType() == CommandType.MYSQL) { + String temp = this.commandName + " where "; + Set c = this.urlParam.entrySet(); + Iterator it = c.iterator(); + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + try { + temp = temp + key + "=" + value; + } catch (Exception ex) { + s_logger.error("Unable to set parameter " + key + " for the command " + this.getName()); + } + } + this.command = temp; + s_logger.info("The command is " + this.command); + + } else { + if ((param.get("apikey") == null) || (param.get("secretkey") == null) || (this.isUserCommand == false)) { + String temp = this.host + ":8096/?command=" + this.commandName; + Set c = this.urlParam.entrySet(); + Iterator it = c.iterator(); + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + try { + temp = temp + "&" + key + "=" + URLEncoder.encode(value, "UTF-8"); + } catch (Exception ex) { + s_logger.error("Unable to set parameter " + key + " for the command " + this.getName()); + } + } + this.command = temp; + } + else if (isUserCommand == true) { + String apiKey = param.get("apikey"); + String secretKey = param.get("secretkey"); + + String temp = ""; + this.urlParam.put("apikey", apiKey); + this.urlParam.put("command", this.commandName); + + // sort url hash map by key + Set c = this.urlParam.entrySet(); + Iterator it = c.iterator(); + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + try { + temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&"; + } catch (Exception ex) { + s_logger.error("Unable to set parameter " + value + " for the command " + this.getName()); + } + + } + temp = temp.substring(0, temp.length() - 1); + String requestToSign = temp.toLowerCase(); + String signature = UtilsForTest.signRequest(requestToSign, secretKey); + String encodedSignature = ""; + try { + encodedSignature = URLEncoder.encode(signature, "UTF-8"); + } catch (Exception ex) { + s_logger.error(ex); + } + this.command = this.host + ":8080/client/api/?" + temp + "&signature=" + encodedSignature; + } + } + } + + public void setVerifyParam(HashMap param) { + NodeList returnLst = this.xmlCommand.getElementsByTagName("returnvalue"); + if (returnLst != null) { + for (int m = 0; m < returnLst.getLength(); m++) { + Element returnElement = (Element) returnLst.item(m); + if (returnElement.getAttribute("list").equals("true")) { + this.list = true; + NodeList elementLst = returnElement.getElementsByTagName("element"); + this.listId = (Element) elementLst.item(0); + NodeList elementName = returnElement.getElementsByTagName("name"); + this.listName = (Element) elementName.item(0); + } + else { + this.list = false; + } + + NodeList itemLst1 = returnElement.getElementsByTagName("item"); + if (itemLst1 != null) { + for (int n = 0; n < itemLst1.getLength(); n++) { + Node item = itemLst1.item(n); + if (item.getNodeType() == Node.ELEMENT_NODE) { + Element itemElement = (Element) item; + // get parameter name + NodeList itemName = itemElement.getElementsByTagName("name"); + Element itemNameElement = (Element) itemName.item(0); + + // Get parameters for future use + if (itemElement.getAttribute("setparam").equals("true")) { + NodeList itemVariable = itemElement.getElementsByTagName("param"); + Element itemVariableElement = (Element) itemVariable.item(0); + setParam.put(itemVariableElement.getTextContent(), itemNameElement.getTextContent()); + this.required = true; + } else if (itemElement.getAttribute("getparam").equals("true")) { + NodeList itemVariable = itemElement.getElementsByTagName("param"); + Element itemVariableElement = (Element) itemVariable.item(0); + this.verifyParam.put(itemNameElement.getTextContent(), param.get(itemVariableElement.getTextContent())); + } else if ((itemElement.getElementsByTagName("value") != null) && (itemElement.getElementsByTagName("value").getLength() != 0)) { + NodeList itemVariable = itemElement.getElementsByTagName("value"); + Element itemVariableElement = (Element) itemVariable.item(0); + this.verifyParam.put(itemNameElement.getTextContent(), itemVariableElement.getTextContent()); + } else { + this.verifyParam.put(itemNameElement.getTextContent(), "no value"); + } + } + } + } + } + } + } + + public int getResponseCode() { + return responseCode; + } + + // Send api command to the server + public void sendCommand(HttpClient client, Connection conn) { + if (TestCaseEngine._printUrl == true) + { + s_logger.info("url is " + this.command); + } + + if (this.getCommandType() == CommandType.SCRIPT) { + try { + s_logger.info("Executing command " + this.command); + Runtime rtime = Runtime.getRuntime(); + Process child = rtime.exec(this.command); + Thread.sleep(10000); + int retCode = child.waitFor(); + if (retCode != 0) { + this.responseCode = retCode; + } else { + this.responseCode = 200; + } + + } catch (Exception ex) { + s_logger.error("Unable to execute a command " + this.command, ex); + } + } else if (this.getCommandType() == CommandType.MYSQL) { + try { + Statement stmt = conn.createStatement(); + this.result = stmt.executeQuery(this.command); + this.responseCode = 200; + } catch (Exception ex) { + this.responseCode = 400; + s_logger.error("Unable to execute mysql query " + this.command, ex); + } + } else { + HttpMethod method = new GetMethod(this.command); + try { + this.responseCode = client.executeMethod(method); + + if (this.responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(is); + doc.getDocumentElement().normalize(); + + if (!(this.isAsync)) { + this.responseBody = doc.getDocumentElement(); + } + else { + // get async job result + Element jobTag = (Element) doc.getDocumentElement().getElementsByTagName("jobid").item(0); + String jobId = jobTag.getTextContent(); + Element responseBodyAsyncEl = queryAsyncJobResult(jobId); + if (responseBodyAsyncEl == null) { + s_logger.error("Can't get a async result"); + } + else { + this.responseBody = responseBodyAsyncEl; + // get status of the job + Element jobStatusTag = (Element) responseBodyAsyncEl.getElementsByTagName("jobstatus").item(0); + String jobStatus = jobStatusTag.getTextContent(); + if (!jobStatus.equals("1")) { // Need to modify with different error codes for jobAsync +// results + // set fake response code by now + this.responseCode = 400; + } + } + } + } + + if (TestCaseEngine._printUrl == true) { + s_logger.info("Response code is " + this.responseCode); + } + } catch (Exception ex) { + s_logger.error("Command " + command + " failed with exception " + ex.getMessage()); + } finally { + method.releaseConnection(); + } + } + } + + // verify if response is empty (contains only root element) + public boolean isEmpty() { + boolean result = false; + if (!this.responseBody.hasChildNodes()) + result = true; + return result; + } + + // ================FOLLOWING METHODS USE RETURN XML FILE=======================// + + public boolean setParam(HashMap param) { + if ((this.responseBody == null) && (this.commandType == CommandType.HTTP)) { + s_logger.error("Response body is empty"); + return false; + } + Boolean result = true; + + if (this.getCommandType() == CommandType.MYSQL) { + Set set = this.setParam.entrySet(); + Iterator it = set.iterator(); + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + try { + String itemName = null; + while (this.result.next()) { + itemName = this.result.getString(value); + } + if (itemName != null) { + param.put(key, itemName); + } + else { + s_logger.error("Following return parameter is missing: " + value); + result = false; + } + } catch (Exception ex) { + s_logger.error("Unable to set parameter " + value, ex); + } + } + } else if (this.getCommandType() == CommandType.HTTP) { + if (this.list == false) { + Set set = this.setParam.entrySet(); + Iterator it = set.iterator(); + + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + // set parameters needed for the future use + NodeList itemName = this.responseBody.getElementsByTagName(value); + if ((itemName != null) && (itemName.getLength() != 0)) { + for (int i = 0; i < itemName.getLength(); i++) { + Element itemNameElement = (Element) itemName.item(i); + if (itemNameElement.getChildNodes().getLength() <= 1) { + param.put(key, itemNameElement.getTextContent()); + break; + } + } + } + else { + s_logger.error("Following return parameter is missing: " + value); + result = false; + } + } + } else { + Set set = this.setParam.entrySet(); + Iterator it = set.iterator(); + NodeList returnLst = this.responseBody.getElementsByTagName(this.listName.getTextContent()); + Node requiredNode = returnLst.item(Integer.parseInt(this.listId.getTextContent())); + + if (requiredNode.getNodeType() == Node.ELEMENT_NODE) { + Element fstElmnt = (Element) requiredNode; + + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + NodeList itemName = fstElmnt.getElementsByTagName(value); + if ((itemName != null) && (itemName.getLength() != 0)) { + Element itemNameElement = (Element) itemName.item(0); + if (itemNameElement.getChildNodes().getLength() <= 1) { + param.put(key, itemNameElement.getTextContent()); + } + } + else { + s_logger.error("Following return parameter is missing: " + value); + result = false; + } + } + } + } + } + return result; + } + + public String getUrl() { + return command; + } + + public boolean verifyParam() { + boolean result = true; + if (this.getCommandType() == CommandType.HTTP) { + if (this.list == false) { + Set set = verifyParam.entrySet(); + Iterator it = set.iterator(); + + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + if (value == null) { + s_logger.error("Parameter " + key + " is missing in the list of global parameters"); + return false; + } + + NodeList itemName = this.responseBody.getElementsByTagName(key); + if ((itemName.getLength() != 0) && (itemName != null)) { + Element itemNameElement = (Element) itemName.item(0); + if (itemNameElement.hasChildNodes()) { + continue; + } + if (!(verifyParam.get(key).equals("no value")) && !(itemNameElement.getTextContent().equals(verifyParam.get(key)))) { + s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is " + verifyParam.get(key) + " while actual value is " + itemNameElement.getTextContent()); + result = false; + } + } else { + s_logger.error("Following xml element is missing in the response: " + key); + result = false; + } + } + } + // for multiple elements + else { + Set set = verifyParam.entrySet(); + Iterator it = set.iterator(); + // get list element specified by id + NodeList returnLst = this.responseBody.getElementsByTagName(this.listName.getTextContent()); + Node requiredNode = returnLst.item(Integer.parseInt(this.listId.getTextContent())); + + if (requiredNode.getNodeType() == Node.ELEMENT_NODE) { + Element fstElmnt = (Element) requiredNode; + + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + if (value == null) { + s_logger.error("Parameter " + key + " is missing in the list of global parameters"); + return false; + } + NodeList itemName = fstElmnt.getElementsByTagName(key); + if ((itemName.getLength() != 0) && (itemName != null)) { + Element itemNameElement = (Element) itemName.item(0); + if (!(verifyParam.get(key).equals("no value")) && !(itemNameElement.getTextContent().equals(verifyParam.get(key)))) { + s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is " + verifyParam.get(key) + " while actual value is " + itemNameElement.getTextContent()); + result = false; + } + } else { + s_logger.error("Following xml element is missing in the response: " + key); + result = false; + } + } + } + } + } else if (this.getCommandType() == CommandType.MYSQL) { + Set set = verifyParam.entrySet(); + Iterator it = set.iterator(); + + while (it.hasNext()) { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + String value = (String) me.getValue(); + if (value == null) { + s_logger.error("Parameter " + key + " is missing in the list of global parameters"); + return false; + } + + String itemName = null; + try { + while (this.result.next()) { + itemName = this.result.getString(key); + } + } catch (Exception ex) { + s_logger.error("Unable to get element from result set " + key); + } + + if (!(value.equals("no value")) && !(itemName.equals(verifyParam.get(key)))) { + s_logger.error("Incorrect value for the following tag: " + key + ". Expected value is " + verifyParam.get(key) + " while actual value is " + itemName); + result = false; + } + } + } + return result; + } + + public static boolean verifyEvents(String fileName, String level, String host, String account) { + boolean result = false; + HashMap expectedEvents = new HashMap(); + HashMap actualEvents = new HashMap(); + String key = ""; + + File file = new File(fileName); + if (file.exists()) { + Properties pro = new Properties(); + try { + // get expected events + FileInputStream in = new FileInputStream(file); + pro.load(in); + Enumeration en = pro.propertyNames(); + while (en.hasMoreElements()) { + key = (String) en.nextElement(); + expectedEvents.put(key, Integer.parseInt(pro.getProperty(key))); + } + + // get actual events + String url = host + "/?command=listEvents&account=" + account + "&level=" + level + "&domainid=1&pagesize=100"; + s_logger.info("Getting events with the following url " + url); + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + ArrayList> eventValues = UtilsForTest.parseMulXML( + is, new String[] { "event" }); + + for (int i = 0; i < eventValues.size(); i++) { + HashMap element = eventValues.get(i); + if (element.get("level").equals(level)) { + if (actualEvents.containsKey(element.get("type")) == true) { + actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1); + } + else { + actualEvents.put(element.get("type"), 1); + } + } + } + } + method.releaseConnection(); + + // compare actual events with expected events + + // compare expected result and actual result + Iterator iterator = expectedEvents.keySet().iterator(); + Integer expected; + Integer actual; + int fail = 0; + while (iterator.hasNext()) { + expected = null; + actual = null; + String type = iterator.next().toString(); + expected = expectedEvents.get(type); + actual = actualEvents.get(type); + if (actual == null) { + s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " + expected); + fail++; + } else if (expected.compareTo(actual) != 0) { + fail++; + s_logger.info("Amount of events of " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected + ", actual number is " + actual); + } + } + if (fail == 0) { + result = true; + } + } catch (Exception ex) { + s_logger.error(ex); + } + } else { + s_logger.info("File " + fileName + " not found"); + } + return result; + } + + public static boolean verifyEvents(HashMap expectedEvents, String level, String host, String parameters) { + boolean result = false; + HashMap actualEvents = new HashMap(); + try { + // get actual events + String url = host + "/?command=listEvents&" + parameters; + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(url); + int responseCode = client.executeMethod(method); + if (responseCode == 200) { + InputStream is = method.getResponseBodyAsStream(); + ArrayList> eventValues = UtilsForTest.parseMulXML( + is, new String[] { "event" }); + + for (int i = 0; i < eventValues.size(); i++) { + HashMap element = eventValues.get(i); + if (element.get("level").equals(level)) { + if (actualEvents.containsKey(element.get("type")) == true) { + actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1); + } + else { + actualEvents.put(element.get("type"), 1); + } + } + } + } + method.releaseConnection(); + } catch (Exception ex) { + s_logger.error(ex); + } + + // compare actual events with expected events + Iterator iterator = expectedEvents.keySet().iterator(); + Integer expected; + Integer actual; + int fail = 0; + while (iterator.hasNext()) { + expected = null; + actual = null; + String type = iterator.next().toString(); + expected = expectedEvents.get(type); + actual = actualEvents.get(type); + if (actual == null) { + s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " + expected); + fail++; + } + else if (expected.compareTo(actual) != 0) { + fail++; + s_logger.info("Amount of events of " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected + ", actual number is " + actual); + } + } + + if (fail == 0) { + result = true; + } + + return result; + } + + public Element queryAsyncJobResult(String jobId) { + Element returnBody = null; + int code = 400; + String resultUrl = this.host + ":8096/?command=queryAsyncJobResult&jobid=" + jobId; + HttpClient client = new HttpClient(); + HttpMethod method = new GetMethod(resultUrl); + while (true) { + try { + code = client.executeMethod(method); + if (code == 200) { + InputStream is = method.getResponseBodyAsStream(); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(is); + doc.getDocumentElement().normalize(); + returnBody = doc.getDocumentElement(); + Element jobStatusTag = (Element) returnBody.getElementsByTagName("jobstatus").item(0); + String jobStatus = jobStatusTag.getTextContent(); + if (jobStatus.equals("0")) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } else { + break; + } + method.releaseConnection(); + } + else { + s_logger.error("Error during queryJobAsync. Error code is " + code); + this.responseCode = code; + return null; + } + } catch (Exception ex) { + s_logger.error(ex); + } + } + return returnBody; + } + + private String getElementByName(String elementName) { + NodeList commandName = this.xmlCommand.getElementsByTagName(elementName); if (commandName.getLength() != 0) { Element commandElmnt = (Element) commandName.item(0); NodeList commandNm = commandElmnt.getChildNodes(); return ((Node) commandNm.item(0)).getNodeValue(); - } + } else { return null; } - } - - private boolean verifyTagValue(String elementName, String expectedValue){ - NodeList tag = this.xmlCommand.getElementsByTagName(elementName); + } + + private boolean verifyTagValue(String elementName, String expectedValue) { + NodeList tag = this.xmlCommand.getElementsByTagName(elementName); if (tag.getLength() != 0) { Element commandElmnt = (Element) tag.item(0); NodeList commandNm = commandElmnt.getChildNodes(); @@ -861,5 +857,5 @@ public class ApiCommand{ } else { return false; } - } -} + } +}