Search in sources :

Example 1 with ListEventsCmd

use of org.apache.cloudstack.api.command.user.event.ListEventsCmd in project cloudstack by apache.

the class ParamProcessWorker method setFieldValue.

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setFieldValue(final Field field, final BaseCmd cmdObj, final Object paramObj, final Parameter annotation) throws IllegalArgumentException, ParseException {
    try {
        field.setAccessible(true);
        final CommandType fieldType = annotation.type();
        switch(fieldType) {
            case BOOLEAN:
                field.set(cmdObj, Boolean.valueOf(paramObj.toString()));
                break;
            case DATE:
                // and support both the date formats(Bug 9724)
                if (cmdObj instanceof ListEventsCmd || cmdObj instanceof DeleteEventsCmd || cmdObj instanceof ArchiveEventsCmd || cmdObj instanceof ArchiveAlertsCmd || cmdObj instanceof DeleteAlertsCmd || cmdObj instanceof ListUsageRecordsCmd) {
                    final boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString());
                    if (isObjInNewDateFormat) {
                        final DateFormat newFormat = newInputFormat;
                        synchronized (newFormat) {
                            field.set(cmdObj, newFormat.parse(paramObj.toString()));
                        }
                    } else {
                        final DateFormat format = inputFormat;
                        synchronized (format) {
                            Date date = format.parse(paramObj.toString());
                            if (field.getName().equals("startDate")) {
                                date = messageDate(date, 0, 0, 0);
                            } else if (field.getName().equals("endDate")) {
                                date = messageDate(date, 23, 59, 59);
                            }
                            field.set(cmdObj, date);
                        }
                    }
                } else {
                    final DateFormat format = inputFormat;
                    synchronized (format) {
                        format.setLenient(false);
                        field.set(cmdObj, format.parse(paramObj.toString()));
                    }
                }
                break;
            case FLOAT:
                // value for optional parameters ...
                if (paramObj != null && StringUtils.isNotBlank(paramObj.toString())) {
                    field.set(cmdObj, Float.valueOf(paramObj.toString()));
                }
                break;
            case DOUBLE:
                // value for optional parameters ...
                if (paramObj != null && StringUtils.isNotBlank(paramObj.toString())) {
                    field.set(cmdObj, Double.valueOf(paramObj.toString()));
                }
                break;
            case INTEGER:
                // value for optional parameters ...
                if (paramObj != null && StringUtils.isNotBlank(paramObj.toString())) {
                    field.set(cmdObj, Integer.valueOf(paramObj.toString()));
                }
                break;
            case LIST:
                final List listParam = new ArrayList();
                final StringTokenizer st = new StringTokenizer(paramObj.toString(), ",");
                while (st.hasMoreTokens()) {
                    final String token = st.nextToken();
                    final CommandType listType = annotation.collectionType();
                    switch(listType) {
                        case INTEGER:
                            listParam.add(Integer.valueOf(token));
                            break;
                        case UUID:
                            if (token.isEmpty())
                                break;
                            final Long internalId = translateUuidToInternalId(token, annotation);
                            listParam.add(internalId);
                            break;
                        case LONG:
                            {
                                listParam.add(Long.valueOf(token));
                            }
                            break;
                        case SHORT:
                            listParam.add(Short.valueOf(token));
                            break;
                        case STRING:
                            listParam.add(token);
                            break;
                    }
                }
                field.set(cmdObj, listParam);
                break;
            case UUID:
                final Long internalId = translateUuidToInternalId(paramObj.toString(), annotation);
                field.set(cmdObj, internalId);
                break;
            case LONG:
                field.set(cmdObj, Long.valueOf(paramObj.toString()));
                break;
            case SHORT:
                field.set(cmdObj, Short.valueOf(paramObj.toString()));
                break;
            case STRING:
                if ((paramObj != null)) {
                    if (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());
                    } else {
                        field.set(cmdObj, paramObj.toString());
                    }
                }
                break;
            case TZDATE:
                field.set(cmdObj, DateUtil.parseTZDateString(paramObj.toString()));
                break;
            case MAP:
            default:
                field.set(cmdObj, paramObj);
                break;
        }
    } catch (final IllegalAccessException ex) {
        s_logger.error("Error initializing command " + cmdObj.getCommandName() + ", field " + field.getName() + " is not accessible.");
        throw new CloudRuntimeException("Internal error initializing parameters for command " + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]");
    }
}
Also used : ArchiveEventsCmd(org.apache.cloudstack.api.command.user.event.ArchiveEventsCmd) ListEventsCmd(org.apache.cloudstack.api.command.user.event.ListEventsCmd) ArrayList(java.util.ArrayList) DeleteEventsCmd(org.apache.cloudstack.api.command.user.event.DeleteEventsCmd) DeleteAlertsCmd(org.apache.cloudstack.api.command.admin.resource.DeleteAlertsCmd) Date(java.util.Date) ListUsageRecordsCmd(org.apache.cloudstack.api.command.admin.usage.ListUsageRecordsCmd) StringTokenizer(java.util.StringTokenizer) CommandType(org.apache.cloudstack.api.BaseCmd.CommandType) ArchiveAlertsCmd(org.apache.cloudstack.api.command.admin.resource.ArchiveAlertsCmd) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with ListEventsCmd

use of org.apache.cloudstack.api.command.user.event.ListEventsCmd in project cloudstack by apache.

the class ApiServer method queueCommand.

private String queueCommand(final BaseCmd cmdObj, final Map<String, String> params, StringBuilder log) throws Exception {
    final CallContext ctx = CallContext.current();
    final Long callerUserId = ctx.getCallingUserId();
    final Account caller = ctx.getCallingAccount();
    // 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) {
            final BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
            dispatcher.dispatchCreateCmd(createCmd, params);
            objectId = createCmd.getEntityId();
            objectUuid = createCmd.getEntityUuid();
            params.put("id", objectId.toString());
            Class entityClass = EventTypes.getEntityClassForEvent(createCmd.getEventType());
            if (entityClass != null)
                ctx.putContextParameter(entityClass, objectUuid);
        } else {
            // Extract the uuid before params are processed and id reflects internal db id
            objectUuid = params.get(ApiConstants.ID);
            dispatchChainFactory.getStandardDispatchChain().dispatch(new DispatchTask(cmdObj, params));
        }
        final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj;
        if (callerUserId != null) {
            params.put("ctxUserId", callerUserId.toString());
        }
        if (caller != null) {
            params.put("ctxAccountId", String.valueOf(caller.getId()));
        }
        if (objectUuid != null) {
            params.put("uuid", objectUuid);
        }
        long startEventId = ctx.getStartEventId();
        asyncCmd.setStartEventId(startEventId);
        // save the scheduled event
        final Long eventId = ActionEventUtils.onScheduledActionEvent((callerUserId == null) ? (Long) User.UID_SYSTEM : callerUserId, asyncCmd.getEntityOwnerId(), asyncCmd.getEventType(), asyncCmd.getEventDescription(), asyncCmd.isDisplay(), 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));
        params.put("cmdEventType", asyncCmd.getEventType().toString());
        params.put("ctxDetails", ApiGsonHelper.getBuilder().create().toJson(ctx.getContextParameters()));
        Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId;
        // users can provide the job id they want to use, so log as it is a uuid and is unique
        String injectedJobId = asyncCmd.getInjectedJobId();
        uuidMgr.checkUuidSimple(injectedJobId, AsyncJob.class);
        AsyncJobVO job = new AsyncJobVO("", callerUserId, caller.getId(), cmdObj.getClass().getName(), ApiGsonHelper.getBuilder().create().toJson(params), instanceId, asyncCmd.getInstanceType() != null ? asyncCmd.getInstanceType().toString() : null, injectedJobId);
        job.setDispatcher(asyncDispatcher.getName());
        final long jobId = asyncMgr.submitAsyncJob(job);
        if (jobId == 0L) {
            final String errorMsg = "Unable to schedule async job for command " + job.getCmd();
            s_logger.warn(errorMsg);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg);
        }
        final String response;
        if (objectId != null) {
            final String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid;
            response = getBaseAsyncCreateResponse(jobId, (BaseAsyncCreateCmd) asyncCmd, objUuid);
        } else {
            SerializationContext.current().setUuidTranslation(true);
            response = getBaseAsyncResponse(jobId, asyncCmd);
        }
        // Always log response for async for now, I don't think any sensitive data will be in here.
        // It might be nice to send this through scrubbing similar to how
        // ApiResponseSerializer.toSerializedStringWithSecureLogs works. For now, this gets jobid's
        // in the api logs.
        log.append(response);
        return response;
    } else {
        dispatcher.dispatch(cmdObj, params, false);
        // 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) && !(cmdObj instanceof ListDiskOfferingsCmd) && !(cmdObj instanceof ListServiceOfferingsCmd) && !(cmdObj instanceof ListZonesCmd)) {
            buildAsyncListResponse((BaseListCmd) cmdObj, caller);
        }
        SerializationContext.current().setUuidTranslation(true);
        return ApiResponseSerializer.toSerializedStringWithSecureLogs((ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType(), log);
    }
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) ListHostsCmd(org.apache.cloudstack.api.command.admin.host.ListHostsCmd) AsyncJobVO(org.apache.cloudstack.framework.jobs.impl.AsyncJobVO) ListZonesCmd(org.apache.cloudstack.api.command.user.zone.ListZonesCmd) ServerApiException(org.apache.cloudstack.api.ServerApiException) ListProjectInvitationsCmd(org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd) ListProjectAccountsCmd(org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd) ListAccountsCmd(org.apache.cloudstack.api.command.user.account.ListAccountsCmd) DispatchTask(com.cloud.api.dispatch.DispatchTask) ListUsersCmd(org.apache.cloudstack.api.command.admin.user.ListUsersCmd) BaseListCmd(org.apache.cloudstack.api.BaseListCmd) ListSecurityGroupsCmd(org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd) ListEventsCmd(org.apache.cloudstack.api.command.user.event.ListEventsCmd) ListVolumesCmd(org.apache.cloudstack.api.command.user.volume.ListVolumesCmd) ListDiskOfferingsCmd(org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd) BaseAsyncCreateCmd(org.apache.cloudstack.api.BaseAsyncCreateCmd) ListRoutersCmd(org.apache.cloudstack.api.command.admin.router.ListRoutersCmd) ListProjectsCmd(org.apache.cloudstack.api.command.user.project.ListProjectsCmd) CallContext(org.apache.cloudstack.context.CallContext) ListVMGroupsCmd(org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd) BaseAsyncCmd(org.apache.cloudstack.api.BaseAsyncCmd) ListVMsCmd(org.apache.cloudstack.api.command.user.vm.ListVMsCmd) ListStoragePoolsCmd(org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd) ListServiceOfferingsCmd(org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd) ListTagsCmd(org.apache.cloudstack.api.command.user.tag.ListTagsCmd)

Aggregations

ListEventsCmd (org.apache.cloudstack.api.command.user.event.ListEventsCmd)2 DispatchTask (com.cloud.api.dispatch.DispatchTask)1 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)1 Account (com.cloud.user.Account)1 UserAccount (com.cloud.user.UserAccount)1 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)1 DateFormat (java.text.DateFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 List (java.util.List)1 StringTokenizer (java.util.StringTokenizer)1 BaseAsyncCmd (org.apache.cloudstack.api.BaseAsyncCmd)1 BaseAsyncCreateCmd (org.apache.cloudstack.api.BaseAsyncCreateCmd)1 CommandType (org.apache.cloudstack.api.BaseCmd.CommandType)1 BaseListCmd (org.apache.cloudstack.api.BaseListCmd)1 ServerApiException (org.apache.cloudstack.api.ServerApiException)1 ListHostsCmd (org.apache.cloudstack.api.command.admin.host.ListHostsCmd)1 ArchiveAlertsCmd (org.apache.cloudstack.api.command.admin.resource.ArchiveAlertsCmd)1 DeleteAlertsCmd (org.apache.cloudstack.api.command.admin.resource.DeleteAlertsCmd)1