public String processCommand(String command) { BaseCmd commandCmd = null; int cmd_result = BaseCmd.COMMAND_OK; String result = COMMAND_OK_STR; for (int i = 0; i <= m_command_list.size(); i++) { commandCmd = m_command_list.get(Integer.valueOf(i)); if (commandCmd == null) { continue; } cmd_result = commandCmd.checkCommand(command); if (cmd_result == BaseCmd.COMMAND_UNSUPPORTED) { continue; } else if (cmd_result == BaseCmd.COMMAND_SUGGESTION) { result = commandCmd.getCmdName(); return result; } else { Log.d(TAG, "processing command: " + command); cmd_result = commandCmd.process(); break; } } return result; }
@Override public void validateSpecificParameters(final Map<String, String> params) { super.validateSpecificParameters(params); final Object pageSizeObj = params.get(ApiConstants.PAGE_SIZE); Long pageSize = null; if (pageSizeObj != null) { pageSize = Long.valueOf((String) pageSizeObj); } if (params.get(ApiConstants.PAGE) == null && pageSize != null && !pageSize.equals(BaseListCmd.s_pageSizeUnlimited)) { final ServerApiException ex = new ServerApiException( ApiErrorCode.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName())); throw ex; } else if (pageSize == null && (params.get(ApiConstants.PAGE) != null)) { throw new ServerApiException( ApiErrorCode.PARAM_ERROR, "\"pagesize\" parameter is required when \"page\" is specified"); } }
public void init() { BaseCmd.setComponents(new ApiResponseHelper()); BaseListCmd.configure(); _systemAccount = _accountMgr.getSystemAccount(); _systemUser = _accountMgr.getSystemUser(); _dispatcher = ApiDispatcher.getInstance(); Integer apiPort = null; // api port, null by default ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); SearchCriteria<ConfigurationVO> sc = configDao.createSearchCriteria(); sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port"); List<ConfigurationVO> values = configDao.search(sc, null); if ((values != null) && (values.size() > 0)) { ConfigurationVO apiPortConfig = values.get(0); if (apiPortConfig.getValue() != null) { apiPort = Integer.parseInt(apiPortConfig.getValue()); } } Set<Class<?>> cmdClasses = ReflectUtil.getClassesWithAnnotation( APICommand.class, new String[] {"org.apache.cloudstack.api", "com.cloud.api"}); for (Class<?> cmdClass : cmdClasses) { String apiName = cmdClass.getAnnotation(APICommand.class).name(); if (_apiNameCmdClassMap.containsKey(apiName)) { s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName); continue; } _apiNameCmdClassMap.put(apiName, cmdClass); } encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())); String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key()); if (jsonType != null) { jsonContentType = jsonType; } if (apiPort != null) { ListenerThread listenerThread = new ListenerThread(this, apiPort); listenerThread.start(); } }
public TkVoiceCmd(TkNotificationSpeaker speaker) { BaseCmd cmd = null; m_command_list = new SparseArray<BaseCmd>(); cmd = new StopCmd(speaker); m_command_list.put(cmd.getCmdId(), cmd); cmd = new RepeatCmd(speaker); m_command_list.put(cmd.getCmdId(), cmd); cmd = new StopCmd(speaker); m_command_list.put(cmd.getCmdId(), cmd); cmd = new NextCmd(speaker); m_command_list.put(cmd.getCmdId(), cmd); cmd = new BackCmd(speaker); m_command_list.put(cmd.getCmdId(), cmd); }
private String queueCommand(BaseCmd cmdObj, Map<String, String> params) throws Exception { UserContext ctx = UserContext.current(); Long callerUserId = ctx.getCallerUserId(); Account caller = ctx.getCaller(); // Queue command based on Cmd super class: // BaseCmd: cmd is dispatched to ApiDispatcher, executed, serialized and returned. // BaseAsyncCreateCmd: cmd params are processed and create() is called, then same workflow as // BaseAsyncCmd. // BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized // and returned. if (cmdObj instanceof BaseAsyncCmd) { Long objectId = null; String objectUuid = null; if (cmdObj instanceof BaseAsyncCreateCmd) { BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj; _dispatcher.dispatchCreateCmd(createCmd, params); objectId = createCmd.getEntityId(); objectUuid = createCmd.getEntityUuid(); params.put("id", objectId.toString()); } else { ApiDispatcher.processParameters(cmdObj, params); } BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj; if (callerUserId != null) { params.put("ctxUserId", callerUserId.toString()); } if (caller != null) { params.put("ctxAccountId", String.valueOf(caller.getId())); } long startEventId = ctx.getStartEventId(); asyncCmd.setStartEventId(startEventId); // save the scheduled event Long eventId = EventUtils.saveScheduledEvent( (callerUserId == null) ? User.UID_SYSTEM : callerUserId, asyncCmd.getEntityOwnerId(), asyncCmd.getEventType(), asyncCmd.getEventDescription(), startEventId); if (startEventId == 0) { // There was no create event before, set current event id as start eventId startEventId = eventId; } params.put("ctxStartEventId", String.valueOf(startEventId)); ctx.setAccountId(asyncCmd.getEntityOwnerId()); Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId; AsyncJobVO job = new AsyncJobVO( callerUserId, caller.getId(), cmdObj.getClass().getName(), ApiGsonHelper.getBuilder().create().toJson(params), instanceId, asyncCmd.getInstanceType()); long jobId = _asyncMgr.submitAsyncJob(job); if (jobId == 0L) { String errorMsg = "Unable to schedule async job for command " + job.getCmd(); s_logger.warn(errorMsg); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg); } if (objectId != null) { String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid; return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objUuid); } SerializationContext.current().setUuidTranslation(true); return ApiResponseSerializer.toSerializedString( asyncCmd.getResponse(jobId), asyncCmd.getResponseType()); } else { _dispatcher.dispatch(cmdObj, params); // if the command is of the listXXXCommand, we will need to also return the // the job id and status if possible // For those listXXXCommand which we have already created DB views, this step is not needed // since async job is joined in their db views. if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListRoutersCmd) && !(cmdObj instanceof ListSecurityGroupsCmd) && !(cmdObj instanceof ListTagsCmd) && !(cmdObj instanceof ListEventsCmd) && !(cmdObj instanceof ListVMGroupsCmd) && !(cmdObj instanceof ListProjectsCmd) && !(cmdObj instanceof ListProjectAccountsCmd) && !(cmdObj instanceof ListProjectInvitationsCmd) && !(cmdObj instanceof ListHostsCmd) && !(cmdObj instanceof ListVolumesCmd) && !(cmdObj instanceof ListUsersCmd) && !(cmdObj instanceof ListAccountsCmd) && !(cmdObj instanceof ListStoragePoolsCmd)) { buildAsyncListResponse((BaseListCmd) cmdObj, caller); } SerializationContext.current().setUuidTranslation(true); return ApiResponseSerializer.toSerializedString( (ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType()); } }
@SuppressWarnings("rawtypes") public String handleRequest( Map params, boolean decode, String responseType, StringBuffer auditTrailSb) throws ServerApiException { String response = null; String[] command = null; try { command = (String[]) params.get("command"); if (command == null) { s_logger.error("invalid request, no command sent"); if (s_logger.isTraceEnabled()) { s_logger.trace("dumping request parameters"); for (Object key : params.keySet()) { String keyStr = (String) key; String[] value = (String[]) params.get(key); s_logger.trace( " key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0])); } } throw new ServerApiException( ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent"); } else { Map<String, String> paramMap = new HashMap<String, String>(); Set keys = params.keySet(); Iterator keysIter = keys.iterator(); while (keysIter.hasNext()) { String key = (String) keysIter.next(); if ("command".equalsIgnoreCase(key)) { continue; } String[] value = (String[]) params.get(key); String decodedValue = null; if (decode) { try { decodedValue = URLDecoder.decode(value[0], "UTF-8"); } catch (UnsupportedEncodingException usex) { s_logger.warn(key + " could not be decoded, value = " + value[0]); throw new ServerApiException( ApiErrorCode.PARAM_ERROR, key + " could not be decoded, received value " + value[0]); } catch (IllegalArgumentException iae) { s_logger.warn(key + " could not be decoded, value = " + value[0]); throw new ServerApiException( ApiErrorCode.PARAM_ERROR, key + " could not be decoded, received value " + value[0] + " which contains illegal characters eg.%"); } } else { decodedValue = value[0]; } paramMap.put(key, decodedValue); } Class<?> cmdClass = getCmdClass(command[0]); if (cmdClass != null) { BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance(); cmdObj.setFullUrlParams(paramMap); cmdObj.setResponseType(responseType); // This is where the command is either serialized, or directly dispatched response = queueCommand(cmdObj, paramMap); buildAuditTrail(auditTrailSb, command[0], response); } else { if (!command[0].equalsIgnoreCase("login") && !command[0].equalsIgnoreCase("logout")) { String errorString = "Unknown API command: " + ((command == null) ? "null" : command[0]); s_logger.warn(errorString); auditTrailSb.append(" " + errorString); throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString); } } } } catch (InvalidParameterValueException ex) { s_logger.info(ex.getMessage()); throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex); } catch (IllegalArgumentException ex) { s_logger.info(ex.getMessage()); throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex); } catch (PermissionDeniedException ex) { ArrayList<String> idList = ex.getIdProxyList(); if (idList != null) { s_logger.info( "PermissionDenied: " + ex.getMessage() + " on uuids: [" + StringUtils.listToCsvTags(idList) + "]"); } else { s_logger.info("PermissionDenied: " + ex.getMessage()); } throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex); } catch (AccountLimitException ex) { s_logger.info(ex.getMessage()); throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex); } catch (InsufficientCapacityException ex) { s_logger.info(ex.getMessage()); String errorMsg = ex.getMessage(); if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN) { // hide internal details to non-admin user for security reason errorMsg = BaseCmd.USER_ERROR_MESSAGE; } throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex); } catch (ResourceAllocationException ex) { s_logger.info(ex.getMessage()); String errorMsg = ex.getMessage(); if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN) { // hide internal details to non-admin user for security reason errorMsg = BaseCmd.USER_ERROR_MESSAGE; } throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, errorMsg, ex); } catch (ResourceUnavailableException ex) { s_logger.info(ex.getMessage()); String errorMsg = ex.getMessage(); if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN) { // hide internal details to non-admin user for security reason errorMsg = BaseCmd.USER_ERROR_MESSAGE; } throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex); } catch (AsyncCommandQueued ex) { s_logger.error( "unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex); throw new ServerApiException( ApiErrorCode.INTERNAL_ERROR, "Internal server error, unable to execute request."); } catch (ServerApiException ex) { s_logger.info(ex.getDescription()); throw ex; } catch (Exception ex) { s_logger.error( "unhandled exception executing api command: " + ((command == null) ? "null" : command[0]), ex); String errorMsg = ex.getMessage(); if (UserContext.current().getCaller().getType() != Account.ACCOUNT_TYPE_ADMIN) { // hide internal details to non-admin user for security reason errorMsg = BaseCmd.USER_ERROR_MESSAGE; } throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex); } return response; }