Search in sources :

Example 71 with MetaClass

use of groovy.lang.MetaClass in project grails-core by grails.

the class DataBindingUtils method bindObjectToDomainInstance.

/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult or null if it wasn't successful
     */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ValidationErrors(grails.validation.ValidationErrors) FieldError(org.springframework.validation.FieldError) CollectionDataBindingSource(grails.databinding.CollectionDataBindingSource) DataBindingSource(grails.databinding.DataBindingSource) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) ObjectError(org.springframework.validation.ObjectError) MetaClass(groovy.lang.MetaClass) GrailsApplication(grails.core.GrailsApplication) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsDomainClass(grails.core.GrailsDomainClass) MetaClass(groovy.lang.MetaClass) DataBinder(grails.databinding.DataBinder) GrailsWebDataBinder(grails.web.databinding.GrailsWebDataBinder)

Example 72 with MetaClass

use of groovy.lang.MetaClass in project spock by spockframework.

the class GroovyMockFactory method create.

public Object create(IMockConfiguration configuration, Specification specification) throws CannotCreateMockException {
    final MetaClass oldMetaClass = GroovyRuntimeUtil.getMetaClass(configuration.getType());
    GroovyMockMetaClass newMetaClass = new GroovyMockMetaClass(configuration, specification, oldMetaClass);
    final Class<?> type = configuration.getType();
    if (configuration.isGlobal()) {
        if (type.isInterface()) {
            throw new CannotCreateMockException(type, ". Global mocking is only possible for classes, but not for interfaces.");
        }
        GroovyRuntimeUtil.setMetaClass(type, newMetaClass);
        specification.getSpecificationContext().getCurrentIteration().addCleanup(new Runnable() {

            public void run() {
                GroovyRuntimeUtil.setMetaClass(type, oldMetaClass);
            }
        });
        return MockInstantiator.instantiate(type, type, configuration.getConstructorArgs(), configuration.isUseObjenesis());
    }
    if (isFinalClass(type)) {
        final Object instance = MockInstantiator.instantiate(type, type, configuration.getConstructorArgs(), configuration.isUseObjenesis());
        GroovyRuntimeUtil.setMetaClass(instance, newMetaClass);
        return instance;
    }
    IProxyBasedMockInterceptor mockInterceptor = new GroovyMockInterceptor(configuration, specification, newMetaClass);
    return ProxyBasedMockFactory.INSTANCE.create(type, Collections.<Class<?>>singletonList(GroovyObject.class), configuration.getConstructorArgs(), mockInterceptor, specification.getClass().getClassLoader(), configuration.isUseObjenesis());
}
Also used : MetaClass(groovy.lang.MetaClass) CannotCreateMockException(org.spockframework.mock.CannotCreateMockException) GroovyObject(groovy.lang.GroovyObject) GroovyObject(groovy.lang.GroovyObject)

Example 73 with MetaClass

use of groovy.lang.MetaClass in project groovy by apache.

the class BindPath method addListeners.

/**
     * Add listeners to a specific object.  Updates the bould flags and update set
     *
     * @param listener This listener to attach.
     * @param newObject The object we should read our property off of.
     * @param updateSet The list of objects we have added listeners to
     */
public void addListeners(PropertyChangeListener listener, Object newObject, Set updateSet) {
    removeListeners();
    if (newObject != null) {
        // check for local synthetics
        TriggerBinding syntheticTrigger = getSyntheticTriggerBinding(newObject);
        MetaClass mc = InvokerHelper.getMetaClass(newObject);
        if (syntheticTrigger != null) {
            PropertyBinding psb = new PropertyBinding(newObject, propertyName);
            PropertyChangeProxyTargetBinding proxytb = new PropertyChangeProxyTargetBinding(newObject, propertyName, listener);
            syntheticFullBinding = syntheticTrigger.createBinding(psb, proxytb);
            syntheticFullBinding.bind();
            updateSet.add(newObject);
        } else if (!mc.respondsTo(newObject, "addPropertyChangeListener", NAME_PARAMS).isEmpty()) {
            InvokerHelper.invokeMethod(newObject, "addPropertyChangeListener", new Object[] { propertyName, listener });
            localListener = listener;
            updateSet.add(newObject);
        } else if (!mc.respondsTo(newObject, "addPropertyChangeListener", GLOBAL_PARAMS).isEmpty()) {
            InvokerHelper.invokeMethod(newObject, "addPropertyChangeListener", listener);
            globalListener = listener;
            updateSet.add(newObject);
        }
    }
    currentObject = newObject;
}
Also used : MetaClass(groovy.lang.MetaClass)

Example 74 with MetaClass

use of groovy.lang.MetaClass in project groovy by apache.

the class GPathResult method setMetaClass.

/**
     * Replaces the MetaClass of this GPathResult.
     *
     * @param metaClass the new MetaClass
     */
@Override
public void setMetaClass(final MetaClass metaClass) {
    final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) {

        @Override
        public Object getAttribute(final Object object, final String attribute) {
            return GPathResult.this.getProperty("@" + attribute);
        }

        @Override
        public void setAttribute(final Object object, final String attribute, final Object newValue) {
            GPathResult.this.setProperty("@" + attribute, newValue);
        }
    };
    super.setMetaClass(newMetaClass);
}
Also used : MetaClass(groovy.lang.MetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) GroovyObject(groovy.lang.GroovyObject) GString(groovy.lang.GString) DelegatingMetaClass(groovy.lang.DelegatingMetaClass)

Example 75 with MetaClass

use of groovy.lang.MetaClass in project groovy by apache.

the class Selector method getMetaClassImpl.

/**
     * Returns the MetaClassImpl if the given MetaClass is one of
     * MetaClassImpl, AdaptingMetaClass or ClosureMetaClass. If
     * none of these cases matches, this method returns null.
     */
private static MetaClassImpl getMetaClassImpl(MetaClass mc, boolean includeEMC) {
    Class mcc = mc.getClass();
    boolean valid = mcc == MetaClassImpl.class || mcc == AdaptingMetaClass.class || mcc == ClosureMetaClass.class || (includeEMC && mcc == ExpandoMetaClass.class);
    if (!valid) {
        if (LOG_ENABLED)
            LOG.info("meta class is neither MetaClassImpl, nor AdoptingMetaClass, nor ClosureMetaClass, normal method selection path disabled.");
        return null;
    }
    if (LOG_ENABLED)
        LOG.info("meta class is a recognized MetaClassImpl");
    return (MetaClassImpl) mc;
}
Also used : CachedSAMClass(org.codehaus.groovy.reflection.stdclasses.CachedSAMClass) AdaptingMetaClass(groovy.lang.AdaptingMetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) ClosureMetaClass(org.codehaus.groovy.runtime.metaclass.ClosureMetaClass) MetaClass(groovy.lang.MetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) MetaClassImpl(groovy.lang.MetaClassImpl) AdaptingMetaClass(groovy.lang.AdaptingMetaClass)

Aggregations

MetaClass (groovy.lang.MetaClass)141 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)62 GroovyObject (groovy.lang.GroovyObject)62 ExpandoMetaClass (groovy.lang.ExpandoMetaClass)40 MetaClassImpl (groovy.lang.MetaClassImpl)18 MetaProperty (groovy.lang.MetaProperty)12 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)11 MetaMethod (groovy.lang.MetaMethod)11 ArrayList (java.util.ArrayList)11 MixinInMetaClass (org.codehaus.groovy.reflection.MixinInMetaClass)11 AdaptingMetaClass (groovy.lang.AdaptingMetaClass)9 MetaClassRegistry (groovy.lang.MetaClassRegistry)9 Map (java.util.Map)9 GString (groovy.lang.GString)7 CachedClass (org.codehaus.groovy.reflection.CachedClass)7 ClassInfo (org.codehaus.groovy.reflection.ClassInfo)7 MissingMethodException (groovy.lang.MissingMethodException)6 MissingPropertyException (groovy.lang.MissingPropertyException)6 IOException (java.io.IOException)6 Method (java.lang.reflect.Method)6