Code format fixes

This commit is contained in:
Alena Prokharchyk 2012-02-10 15:10:02 -08:00
parent 4c05adaac0
commit 294d3a2fda
19 changed files with 1499 additions and 1472 deletions

View File

@ -35,35 +35,35 @@ 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() {
@ -111,13 +111,12 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd {
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);
@ -129,8 +128,8 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd {
}
@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());
@ -148,4 +147,5 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd {
public String getEventDescription() {
return "creating project";
}
}

View File

@ -31,21 +31,21 @@ 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;
}
@ -55,18 +55,18 @@ public class DeleteProjectInvitationCmd extends BaseAsyncCmd {
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) {
@ -84,6 +84,7 @@ public class DeleteProjectInvitationCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
return "Project invitatino id " + id + " is being removed";
return "Project invitatino id " + id + " is being removed";
}
}

View File

@ -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;
}
@ -76,13 +77,14 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd {
return s_name;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public void execute(){
List<? extends ProjectInvitation> invites = _projectService.listProjectInvitations(id, projectId, this.getAccountName(), this.getDomainId(), state, activeOnly, this.getStartIndex(), this.getPageSizeVal(), this.isRecursive(), this.listAll());
public void execute() {
List<? extends ProjectInvitation> invites = _projectService.listProjectInvitations(id, projectId, this.getAccountName(), this.getDomainId(), state, activeOnly, this.getStartIndex(), this.getPageSizeVal(),
this.isRecursive(), this.listAll());
ListResponse<ProjectInvitationResponse> response = new ListResponse<ProjectInvitationResponse>();
List<ProjectInvitationResponse> projectInvitationResponses = new ArrayList<ProjectInvitationResponse>();
for (ProjectInvitation invite : invites) {
@ -94,4 +96,5 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd {
this.setResponseObject(response);
}
}

View File

@ -40,31 +40,31 @@ 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.")
@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 /////////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ////////////// 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;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
public Long getId() {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public String getCommandName() {
@ -72,7 +72,7 @@ public class StartVMCmd extends BaseAsyncCmd {
}
public static String getResultObjectName() {
return "virtualmachine";
return "virtualmachine";
}
@Override
@ -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());
}
}
}

View File

@ -35,35 +35,34 @@ 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() {
@ -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,17 +91,17 @@ 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() {
@ -109,14 +109,14 @@ public class StopVMCmd extends BaseAsyncCmd {
}
@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) {

View File

@ -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;
}
@ -80,20 +79,19 @@ public class UpdateProjectInvitationCmd extends BaseAsyncCmd {
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());
@ -110,6 +108,6 @@ public class UpdateProjectInvitationCmd extends BaseAsyncCmd {
@Override
public String getEventDescription() {
return "Updating project invitation for projectId " + projectId;
return "Updating project invitation for projectId " + projectId;
}
}

View File

@ -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<UserResponse> users;
public void setProjectId(Long projectId) {

View File

@ -175,11 +175,11 @@ public class ApiDispatcher {
Map<String, Object> 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");
@ -212,7 +212,8 @@ public class ApiDispatcher {
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()));
}
}else{
} else {
DateFormat format = BaseCmd.INPUT_FORMAT;
synchronized (format) {
Date date = format.parse(paramObj.toString());
if (field.getName().equals("startDate")){
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);
case LONG: {
Long val = null;
if (identityMapper != null)
val = s_instance._identityDao.getIdentityId(identityMapper, token);
else
val = Long.valueOf(token);
listParam.add(val);
}
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:
@ -363,7 +367,7 @@ public class ApiDispatcher {
public static void plugService(BaseCmd cmd) {
if(!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())){
if (!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())) {
return;
}
Class<?> clazz = cmd.getClass();

View File

@ -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;

View File

@ -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
@ -114,11 +114,11 @@ public class ProjectInvitationVO implements ProjectInvitation, Identity {
@Override
public String getUuid() {
return this.uuid;
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
this.uuid = uuid;
}
@Override

View File

@ -1,4 +1,3 @@
package com.cloud.projects;
import java.util.List;
@ -14,7 +13,8 @@ public interface ProjectManager extends ProjectService {
List<Long> listPermittedProjectAccounts(long accountId);
boolean projectInviteRequired();
boolean projectInviteRequired();
boolean allowUserToCreateProject();
boolean allowUserToCreateProject();
}

View File

@ -23,9 +23,11 @@ import com.cloud.projects.ProjectAccount;
import com.cloud.projects.ProjectAccountVO;
import com.cloud.utils.db.GenericDao;
public interface ProjectAccountDao extends GenericDao<ProjectAccountVO, Long>{
public interface ProjectAccountDao extends GenericDao<ProjectAccountVO, Long> {
ProjectAccountVO getProjectOwner(long projectId);
List<ProjectAccountVO> listByProjectId(long projectId);
ProjectAccountVO findByProjectIdAccountId(long projectId, long accountId);
boolean canAccessProjectAccount(long accountId, long projectAccountId);

View File

@ -30,7 +30,7 @@ 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<ProjectAccountVO, Long> implements ProjectAccountDao {
protected final SearchBuilder<ProjectAccountVO> AllFieldsSearch;
final GenericSearchBuilder<ProjectAccountVO, Long> AdminSearch;
@ -133,9 +133,10 @@ public class ProjectAccountDaoImpl extends GenericDaoBase<ProjectAccountVO, Long
@Override
public Long countByAccountIdAndRole(long accountId, ProjectAccount.Role role) {
SearchCriteria<Long> sc = CountByRoleSearch.create();
SearchCriteria<Long> sc = CountByRoleSearch.create();
sc.setParameters("accountId", accountId);
sc.setParameters("role", role);
return customSearch(sc, null).get(0);
}
}

View File

@ -23,7 +23,7 @@ import com.cloud.projects.Project;
import com.cloud.projects.ProjectVO;
import com.cloud.utils.db.GenericDao;
public interface ProjectDao extends GenericDao<ProjectVO, Long>{
public interface ProjectDao extends GenericDao<ProjectVO, Long> {
ProjectVO findByNameAndDomain(String name, long domainId);
@ -32,4 +32,5 @@ public interface ProjectDao extends GenericDao<ProjectVO, Long>{
ProjectVO findByProjectAccountId(long projectAccountId);
List<ProjectVO> listByState(Project.State state);
}

View File

@ -16,7 +16,7 @@ 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<ProjectVO, Long> implements ProjectDao {
private static final Logger s_logger = Logger.getLogger(ProjectDaoImpl.class);
protected final SearchBuilder<ProjectVO> AllFieldsSearch;
@ -46,7 +46,8 @@ public class ProjectDaoImpl extends GenericDaoBase<ProjectVO, Long> implements P
return findOneBy(sc);
}
@Override @DB
@Override
@DB
public boolean remove(Long projectId) {
boolean result = false;
Transaction txn = Transaction.currentTxn();
@ -74,7 +75,7 @@ public class ProjectDaoImpl extends GenericDaoBase<ProjectVO, Long> implements P
}
@Override
public ProjectVO findByProjectAccountId(long projectAccountId) {
public ProjectVO findByProjectAccountId(long projectAccountId) {
SearchCriteria<ProjectVO> sc = AllFieldsSearch.create();
sc.setParameters("projectAccountId", projectAccountId);
@ -87,4 +88,5 @@ public class ProjectDaoImpl extends GenericDaoBase<ProjectVO, Long> implements P
sc.setParameters("state", state);
return listBy(sc);
}
}

View File

@ -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<ProjectInvitationVO, Long>{
public interface ProjectInvitationDao extends GenericDao<ProjectInvitationVO, Long> {
ProjectInvitationVO findByAccountIdProjectId(long accountId, long projectId, State... inviteState);
List<ProjectInvitationVO> 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);
ProjectInvitationVO findPendingById(long id);
List<ProjectInvitationVO> listInvitationsToExpire(long timeOut);
}

View File

@ -14,7 +14,7 @@ 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<ProjectInvitationVO, Long> implements ProjectInvitationDao {
private static final Logger s_logger = Logger.getLogger(ProjectInvitationDaoImpl.class);
protected final SearchBuilder<ProjectInvitationVO> AllFieldsSearch;
@ -41,14 +41,13 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase<ProjectInvitationVO
InactiveSearch.done();
}
@Override
public ProjectInvitationVO findByAccountIdProjectId(long accountId, long projectId, State... inviteState) {
SearchCriteria<ProjectInvitationVO> 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);
@ -82,8 +81,8 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase<ProjectInvitationVO
}
@Override
public List<ProjectInvitationVO> listInvitationsToExpire (long timeOut) {
SearchCriteria<ProjectInvitationVO> sc = InactiveSearch.create();
public List<ProjectInvitationVO> listInvitationsToExpire(long timeOut) {
SearchCriteria<ProjectInvitationVO> sc = InactiveSearch.create();
sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - timeOut));
sc.setParameters("state", State.Pending);
return listBy(sc);
@ -115,7 +114,7 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase<ProjectInvitationVO
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);
@ -127,7 +126,7 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase<ProjectInvitationVO
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);
@ -150,4 +149,5 @@ public class ProjectInvitationDaoImpl extends GenericDaoBase<ProjectInvitationVO
int numberRemoved = remove(sc);
s_logger.debug("Removed " + numberRemoved + " invitations for project id=" + projectId);
}
}

View File

@ -298,7 +298,8 @@ public class ManagementServerImpl implements ManagementServer {
private final LoadBalancerDao _loadbalancerDao;
private final HypervisorCapabilitiesDao _hypervisorCapabilitiesDao;
private final Adapters<HostAllocator> _hostAllocators;
@Inject ProjectManager _projectMgr;
@Inject
ProjectManager _projectMgr;
private final ResourceManager _resourceMgr;
@Inject
SnapshotManager _snapshotMgr;
@ -369,7 +370,6 @@ public class ManagementServerImpl implements ManagementServer {
_hypervisorCapabilitiesDao = locator.getDao(HypervisorCapabilitiesDao.class);
_hostAllocators = locator.getAdapters(HostAllocator.class);
if (_hostAllocators == null || !_hostAllocators.isSet()) {
s_logger.error("Unable to find HostAllocators");
@ -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<ServiceOfferingVO> sc = _offeringsDao.createSearchCriteria();
@ -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");
}
@ -695,7 +696,7 @@ public class ManagementServerImpl implements ManagementServer {
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<ServiceOfferingVO> 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
@ -764,7 +766,7 @@ 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
@ -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<Host> suitableHosts = new ArrayList<Host>();
Enumeration<HostAllocator> 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);
}
@ -1066,7 +1068,7 @@ public class ManagementServerImpl implements ManagementServer {
}
}
//set project information
// set project information
if (projectId != null) {
Project project = _projectMgr.getProject(projectId);
if (project == null) {
@ -1194,7 +1196,7 @@ public class ManagementServerImpl implements ManagementServer {
List<Account> permittedAccounts = new ArrayList<Account>();
for (Long accountId : permittedAccountIds) {
permittedAccounts.add(_accountMgr.getAccount(accountId));
permittedAccounts.add(_accountMgr.getAccount(accountId));
}
HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
@ -1216,7 +1218,7 @@ public class ManagementServerImpl implements ManagementServer {
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
List<Account> permittedAccounts = new ArrayList<Account>();
for (Long accountId : permittedAccountIds) {
permittedAccounts.add(_accountMgr.getAccount(accountId));
permittedAccounts.add(_accountMgr.getAccount(accountId));
}
boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
@ -1253,8 +1255,8 @@ public class ManagementServerImpl implements ManagementServer {
}
List<HypervisorType> hypers = null;
if(!isIso) {
hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
if (!isIso) {
hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
}
Set<Pair<Long, Long>> templateZonePairSet = new HashSet<Pair<Long, Long>>();
if (_swiftMgr.isSwiftEnabled()) {
@ -1295,7 +1297,6 @@ public class ManagementServerImpl implements ManagementServer {
return templateZonePairSet;
}
@Override
public VMTemplateVO updateTemplate(UpdateIsoCmd cmd) {
return updateTemplateOrIso(cmd);
@ -1347,7 +1348,7 @@ public class ManagementServerImpl implements ManagementServer {
}
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<EventVO> searchForEvents(ListEventsCmd cmd) {
Account caller = UserContext.current().getCaller();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
Long id = cmd.getId();
@ -1408,7 +1408,7 @@ public class ManagementServerImpl implements ManagementServer {
Filter searchFilter = new Filter(EventVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<EventVO> 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
@ -1418,14 +1418,14 @@ public class ManagementServerImpl implements ManagementServer {
}
if (listProjectResourcesCriteria != null) {
SearchBuilder<AccountVO> 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<AccountVO> 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);
@ -1435,13 +1435,13 @@ 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<EventVO> 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()) {
@ -1494,7 +1494,7 @@ public class ManagementServerImpl implements ManagementServer {
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<EventVO> 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<DomainRouterVO> searchForRouters(ListRoutersCmd cmd) {
Long id = cmd.getId();
Long id = cmd.getId();
String name = cmd.getRouterName();
String state = cmd.getState();
Long zone = cmd.getZoneId();
@ -1590,7 +1589,6 @@ public class ManagementServerImpl implements ManagementServer {
return _routerDao.search(sc, searchFilter);
}
@Override
public List<IPAddressVO> searchForIPAddresses(ListPublicIpAddressesCmd cmd) {
Object keyword = cmd.getKeyword();
@ -1632,8 +1630,7 @@ public class ManagementServerImpl implements ManagementServer {
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<LoadBalancerVO> lbSearch = _loadbalancerDao.createSearchBuilder();
sb.join("lbSearch", lbSearch, sb.entity().getId(), lbSearch.entity().getSourceIpAddressId(), JoinType.INNER);
sb.groupBy(sb.entity().getId());
@ -1660,9 +1657,9 @@ public class ManagementServerImpl implements ManagementServer {
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<IPAddressVO> sc = sb.create();
@ -1686,7 +1683,6 @@ public class ManagementServerImpl implements ManagementServer {
sc.setParameters("isStaticNat", staticNat);
}
if (address == null && keyword != null) {
sc.setParameters("addressLIKE", "%" + keyword + "%");
}
@ -1704,7 +1700,7 @@ public class ManagementServerImpl implements ManagementServer {
}
if (associatedNetworkId != null) {
sc.setParameters("associatedNetworkIdEq", associatedNetworkId);
sc.setParameters("associatedNetworkIdEq", associatedNetworkId);
}
return _publicIpAddressDao.search(sc, searchFilter);
@ -1839,7 +1835,7 @@ public class ManagementServerImpl implements ManagementServer {
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<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
@ -1852,12 +1848,12 @@ public class ManagementServerImpl implements ManagementServer {
}
}
//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 \"-\"");
}
}
@ -1873,11 +1869,11 @@ public class ManagementServerImpl implements ManagementServer {
}
if (networkDomain != null) {
if (networkDomain.isEmpty()) {
domain.setNetworkDomain(null);
} else {
if (networkDomain.isEmpty()) {
domain.setNetworkDomain(null);
} else {
domain.setNetworkDomain(networkDomain);
}
}
}
_domainDao.update(domainId, domain);
@ -1946,42 +1942,42 @@ public class ManagementServerImpl implements ManagementServer {
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<SummedCapacity> summedCapacities = new ArrayList<SummedCapacity>();
if (zoneId == null && podId == null){//Group by Zone, capacity type
if (zoneId == null && podId == null) {// Group by Zone, capacity type
List<SummedCapacity> 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<SummedCapacity> summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, cmd.getPageSizeVal());
if(summedCapacitiesAtPod != null){
if (summedCapacitiesAtPod != null) {
summedCapacities.addAll(summedCapacitiesAtPod);
}
List<SummedCapacity> summedCapacitiesForSecStorage = getSecStorageUsed(zoneId, capacityType);
if (summedCapacitiesForSecStorage != null){
if (summedCapacitiesForSecStorage != null) {
summedCapacities.addAll(summedCapacitiesForSecStorage);
}
}
//Group by Cluster, capacity type
// Group by Cluster, capacity type
List<SummedCapacity> 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<SummedCapacity>() {
@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;
@ -1990,18 +1986,17 @@ public class ManagementServerImpl implements ManagementServer {
List<CapacityVO> capacities = new ArrayList<CapacityVO>();
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");
} 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);
@ -2009,34 +2004,36 @@ public class ManagementServerImpl implements ManagementServer {
return capacities;
}
List<SummedCapacity> getSecStorageUsed(Long zoneId, Integer capacityType){
if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE){
List<SummedCapacity> getSecStorageUsed(Long zoneId, Integer capacityType) {
if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_SECONDARY_STORAGE) {
List<SummedCapacity> list = new ArrayList<SummedCapacity>();
if (zoneId != null){
if (zoneId != null) {
DataCenterVO zone = ApiDBUtils.findZoneById(zoneId);
if(zone == null || zone.getAllocationState() == AllocationState.Disabled){
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<DataCenterVO> dcList = _dcDao.listEnabledZones();
for(DataCenterVO dc : dcList){
for (DataCenterVO dc : dcList) {
CapacityVO capacity = _storageMgr.getSecondaryStorageUsedStats(null, dc.getId());
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());
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;
}
@ -2046,45 +2043,45 @@ public class ManagementServerImpl implements ManagementServer {
@Override
public List<CapacityVO> 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<SummedCapacity> summedCapacities = _capacityDao.findCapacityBy(capacityType, zoneId, podId, clusterId);
List<CapacityVO> capacities = new ArrayList<CapacityVO>();
for (SummedCapacity summedCapacity : summedCapacities){
CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId,
summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(),
summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType());
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);
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<DataCenterVO> dcList = new ArrayList<DataCenterVO>();
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<DiskOfferingVO> 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<DiskOfferingVO> 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<AsyncJobVO> searchForAsyncJobs(ListAsyncJobsCmd cmd) {
Account caller = UserContext.current().getCaller();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
List<Long> permittedAccounts = new ArrayList<Long>();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(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();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(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<AsyncJobVO> sb = _jobDao.createSearchBuilder();
sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
SearchBuilder<AccountVO> 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<DomainVO> 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);
}
Filter searchFilter = new Filter(AsyncJobVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<AsyncJobVO> sb = _jobDao.createSearchBuilder();
sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
SearchBuilder<AccountVO> 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<DomainVO> 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 (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);
}
}
if (!accountJoinIsDone) {
sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
}
Object keyword = cmd.getKeyword();
Object startDate = cmd.getStartDate();
Object keyword = cmd.getKeyword();
Object startDate = cmd.getStartDate();
SearchCriteria<AsyncJobVO> sc = sb.create();
if (listProjectResourcesCriteria != null) {
sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT);
}
SearchCriteria<AsyncJobVO> 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 (!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 (keyword != null) {
sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%");
}
if (startDate != null) {
sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate);
}
if (startDate != null) {
sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate);
}
return _jobDao.search(sc, searchFilter);
}
return _jobDao.search(sc, searchFilter);
}
@ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true)
public SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) {
@ -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)
@ -2717,7 +2715,7 @@ public class ManagementServerImpl implements ManagementServer {
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) {
@ -2732,15 +2730,17 @@ public class ManagementServerImpl implements ManagementServer {
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.
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");
}
}
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;
@ -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());
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;
}
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();
@ -2922,11 +2921,11 @@ public class ManagementServerImpl implements ManagementServer {
}
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);
@ -2934,7 +2933,7 @@ public class ManagementServerImpl implements ManagementServer {
SearchCriteria<InstanceGroupVO> sc = sb.create();
if (listProjectResourcesCriteria != null) {
sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT);
sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT);
}
if (!permittedAccounts.isEmpty()) {
@ -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 && 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.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.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 && !_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);
@ -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<SSHKeyPairVO> sb = _sshKeyPairDao.createSearchBuilder();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
SearchBuilder<SSHKeyPairVO> sb = _sshKeyPairDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
Filter searchFilter = new Filter(SSHKeyPairVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
@ -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<HostVO> hosts = _resourceMgr.listAllHostsInCluster(cmd.getClusterId());
Transaction txn = Transaction.currentTxn();
try{
try {
txn.start();
for (HostVO h : hosts) {
if (s_logger.isDebugEnabled()) {
@ -3232,7 +3232,7 @@ 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());
}
@ -3242,14 +3242,14 @@ public class ManagementServerImpl implements ManagementServer {
}
@Override
public String[] listEventTypes(){
public String[] listEventTypes() {
Object eventObj = new EventTypes();
Class<EventTypes> 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;
@ -3262,7 +3262,7 @@ public class ManagementServerImpl implements ManagementServer {
}
@Override
public List<HypervisorCapabilitiesVO> listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal){
public List<HypervisorCapabilitiesVO> listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal) {
Filter searchFilter = new Filter(HypervisorCapabilitiesVO.class, "id", true, startIndex, pageSizeVal);
SearchCriteria<HypervisorCapabilitiesVO> sc = _hypervisorCapabilitiesDao.createSearchCriteria();
@ -3285,10 +3285,10 @@ public class ManagementServerImpl implements ManagementServer {
}
@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);
}
@ -3297,18 +3297,17 @@ public class ManagementServerImpl implements ManagementServer {
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;

File diff suppressed because it is too large Load Diff