Search in sources :

Example 1 with CommandType

use of org.apache.cloudstack.api.BaseCmd.CommandType 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 GetUsageRecordsCmd) {
                    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 && isNotBlank(paramObj.toString())) {
                    field.set(cmdObj, Float.valueOf(paramObj.toString()));
                }
                break;
            case DOUBLE:
                // value for optional parameters ...
                if (paramObj != null && isNotBlank(paramObj.toString())) {
                    field.set(cmdObj, Double.valueOf(paramObj.toString()));
                }
                break;
            case INTEGER:
                // value for optional parameters ...
                if (paramObj != null && 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) 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) GetUsageRecordsCmd(org.apache.cloudstack.api.command.admin.usage.GetUsageRecordsCmd) 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 CommandType

use of org.apache.cloudstack.api.BaseCmd.CommandType in project cloudstack by apache.

the class ParamProcessWorker method processParameters.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void processParameters(final BaseCmd cmd, final Map params) {
    final Map<Object, AccessType> entitiesToAccess = new HashMap<Object, AccessType>();
    final List<Field> cmdFields = cmd.getParamFields();
    for (final Field field : cmdFields) {
        final Parameter parameterAnnotation = field.getAnnotation(Parameter.class);
        final Object paramObj = params.get(parameterAnnotation.name());
        if (paramObj == null) {
            if (parameterAnnotation.required()) {
                throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to missing parameter " + parameterAnnotation.name());
            }
            continue;
        }
        // marshall the parameter into the correct type and set the field value
        try {
            validateField(paramObj, parameterAnnotation);
            setFieldValue(field, cmd, paramObj, parameterAnnotation);
        } catch (final IllegalArgumentException argEx) {
            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(ApiErrorCode.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 (final ParseException parseEx) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Invalid date parameter " + paramObj + " passed to command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8));
            }
            throw new ServerApiException(ApiErrorCode.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 (final InvalidParameterValueException invEx) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage());
        } catch (final CloudRuntimeException cloudEx) {
            s_logger.error("CloudRuntimeException", cloudEx);
            // and IllegalAccessException setting one of the parameters.
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8));
        }
        //check access on the resource this field points to
        try {
            final ACL checkAccess = field.getAnnotation(ACL.class);
            final CommandType fieldType = parameterAnnotation.type();
            if (checkAccess != null) {
                if (parameterAnnotation.entityType() != null && parameterAnnotation.entityType().length > 0 && parameterAnnotation.entityType()[0].getAnnotation(EntityReference.class) != null) {
                    final Class<?>[] entityList = parameterAnnotation.entityType()[0].getAnnotation(EntityReference.class).value();
                    // Id or list of id's/name's
                    switch(fieldType) {
                        case LIST:
                            final CommandType listType = parameterAnnotation.collectionType();
                            switch(listType) {
                                case LONG:
                                case UUID:
                                    final List<Long> listParam = (List<Long>) field.get(cmd);
                                    for (final Long entityId : listParam) {
                                        for (final Class entity : entityList) {
                                            final Object entityObj = _entityMgr.findById(entity, entityId);
                                            if (entityObj != null) {
                                                entitiesToAccess.put(entityObj, checkAccess.accessType());
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                /*
                                 * case STRING: List<String> listParam = new
                                 * ArrayList<String>(); listParam =
                                 * (List)field.get(cmd); for(String entityName:
                                 * listParam){ ControlledEntity entityObj =
                                 * (ControlledEntity )daoClassInstance(entityId);
                                 * entitiesToAccess.add(entityObj); } break;
                                 */
                                default:
                                    break;
                            }
                            break;
                        case LONG:
                        case UUID:
                            for (final Class entity : entityList) {
                                final Object entityObj = _entityMgr.findById(entity, (Long) field.get(cmd));
                                if (entityObj != null) {
                                    entitiesToAccess.put(entityObj, checkAccess.accessType());
                                    break;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        } catch (final IllegalArgumentException e) {
            s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
            throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
        } catch (final IllegalAccessException e) {
            s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible.");
            throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]");
        }
    }
    doAccessChecks(cmd, entitiesToAccess);
}
Also used : HashMap(java.util.HashMap) ACL(org.apache.cloudstack.api.ACL) Field(java.lang.reflect.Field) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CommandType(org.apache.cloudstack.api.BaseCmd.CommandType) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) EntityReference(org.apache.cloudstack.api.EntityReference) Parameter(org.apache.cloudstack.api.Parameter) ArrayList(java.util.ArrayList) List(java.util.List) ParseException(java.text.ParseException) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType)

Aggregations

InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)2 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 CommandType (org.apache.cloudstack.api.BaseCmd.CommandType)2 Field (java.lang.reflect.Field)1 DateFormat (java.text.DateFormat)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 StringTokenizer (java.util.StringTokenizer)1 AccessType (org.apache.cloudstack.acl.SecurityChecker.AccessType)1 ACL (org.apache.cloudstack.api.ACL)1 EntityReference (org.apache.cloudstack.api.EntityReference)1 Parameter (org.apache.cloudstack.api.Parameter)1 ServerApiException (org.apache.cloudstack.api.ServerApiException)1 ArchiveAlertsCmd (org.apache.cloudstack.api.command.admin.resource.ArchiveAlertsCmd)1 DeleteAlertsCmd (org.apache.cloudstack.api.command.admin.resource.DeleteAlertsCmd)1 GetUsageRecordsCmd (org.apache.cloudstack.api.command.admin.usage.GetUsageRecordsCmd)1