Example usage for java.lang.reflect Method isAccessible

List of usage examples for java.lang.reflect Method isAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Method isAccessible.

Prototype

@Deprecated(since = "9")
public boolean isAccessible() 

Source Link

Document

Get the value of the accessible flag for this reflected object.

Usage

From source file:org.grails.orm.hibernate.proxy.GroovyAwareJavassistLazyInitializer.java

public Object invoke(final Object proxy, final Method thisMethod, final Method proceed, final Object[] args)
        throws Throwable {
    // while constructor is running
    if (thisMethod.getName().equals("getHibernateLazyInitializer")) {
        return this;
    }/*from   w  w  w .jav a 2  s.c  o  m*/

    Object result = groovyObjectMethodHandler.handleInvocation(proxy, thisMethod, args);
    if (groovyObjectMethodHandler.wasHandled(result)) {
        return result;
    }

    if (constructed) {
        try {
            result = invoke(thisMethod, args, proxy);
        } catch (Throwable t) {
            throw new Exception(t.getCause());
        }
        if (result == INVOKE_IMPLEMENTATION) {
            Object target = getImplementation();
            final Object returnValue;
            try {
                if (ReflectHelper.isPublic(persistentClass, thisMethod)) {
                    if (!thisMethod.getDeclaringClass().isInstance(target)) {
                        throw new ClassCastException(target.getClass().getName());
                    }
                    returnValue = thisMethod.invoke(target, args);
                } else {
                    if (!thisMethod.isAccessible()) {
                        thisMethod.setAccessible(true);
                    }
                    returnValue = thisMethod.invoke(target, args);
                }
                return returnValue == target ? proxy : returnValue;
            } catch (InvocationTargetException ite) {
                throw ite.getTargetException();
            }
        }
        return result;
    }

    return proceed.invoke(proxy, args);
}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

private void invokePostConstruct(Object object) throws InvocationTargetException, IllegalAccessException {
    Class<?> clazz = object.getClass();
    List<Method> postConstructMethods = new ArrayList<Method>();
    while (clazz != null) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(PostConstruct.class)) {
                addMethodIfNotOverriden(postConstructMethods, method);
            }//from www  .j ava  2s . c o m
        }
        clazz = clazz.getSuperclass();
    }
    Collections.reverse(postConstructMethods);
    for (Method method : postConstructMethods) {
        boolean accessible = method.isAccessible();
        try {
            if (!accessible) {
                method.setAccessible(true);
            }
            method.invoke(object);
        } finally {
            if (!accessible) {
                method.setAccessible(false);
            }
        }
    }
}

From source file:org.wso2.carbon.bridge.EquinoxFrameworkLauncher.java

private void registerRestartHandler(Class starterClazz) throws NoSuchMethodException, ClassNotFoundException,
        IllegalAccessException, InvocationTargetException {
    Method registerFrameworkShutdownHandler;
    try {// w  ww  .j  a v a2  s  .  com
        registerFrameworkShutdownHandler = starterClazz.getDeclaredMethod("internalAddFrameworkShutdownHandler",
                Runnable.class);
    } catch (NoSuchMethodException e) {
        // Ok. However we will not support restart events. Log this as info
        context.log(starterClazz.getName()
                + " does not support setting a shutdown handler. Restart handling is disabled.");
        return;
    }
    if (!registerFrameworkShutdownHandler.isAccessible()) {
        registerFrameworkShutdownHandler.setAccessible(true);
    }
    Runnable restartHandler = createRestartHandler();
    registerFrameworkShutdownHandler.invoke(null, restartHandler);
}

From source file:org.springframework.beans.BeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;/*from  www .  j  a v  a  2  s .c o m*/
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // TODO: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.resolvedDescriptor;
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException {
    net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue(
            "", null);
    AfxBeanUtils.copySamePropertyValue(pv2, pv);
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;//from w  w  w .j a  va 2 s . c  o m
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // #TO#DO#: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.getResolvedDescriptor();
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().setResolvedDescriptor(pd);
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.getConversionNecessary())) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:velo.ejb.impl.ConfBean.java

@Deprecated
protected Method findIdMethod(Class clazz) {
    for (Class currClazz = clazz; !currClazz.equals(Object.class); currClazz = currClazz.getSuperclass()) {
        // Iterate over the fields and find the Id field
        for (Method m : currClazz.getDeclaredMethods()) {
            if (!(m.isAccessible()))
                m.setAccessible(true);//  w  w  w  .j  a  va2  s  .c om
            if (m.isAnnotationPresent(Id.class)) {
                return m;
            }
        }
    }
    return null;
}

From source file:net.minder.config.impl.DefaultConfigurationInjector.java

private void injectMethodValue(Method method, Object target, ConfigurationAdapter adapter,
        ConfigurationBinding binding) throws ConfigurationException {
    Configure methodTag = method.getAnnotation(Configure.class);
    if (methodTag != null) {
        Alias aliasTag = method.getAnnotation(Alias.class);
        String methodName = getConfigName(method, aliasTag);
        Class[] argTypes = method.getParameterTypes();
        Object[] args = new Object[argTypes.length];
        Annotation[][] argTags = method.getParameterAnnotations();
        for (int i = 0; i < argTypes.length; i++) {
            String argName = getConfigName(methodName, argTags[i]);
            String bndName = getBindName(target, argName, binding);
            Object argValue = retrieveValue(target, bndName, argName, argTypes[i], adapter, binding);
            if (argValue == null) {
                Default defTag = findAnnotation(argTags[i], Default.class);
                if (defTag != null) {
                    String strValue = defTag.value();
                    argValue = convertValue(target, argName, strValue, argTypes[i]);
                } else {
                    throw new ConfigurationException(
                            String.format("Failed to find configuration for %s of %s via %s", bndName, argName,
                                    target.getClass().getName(), adapter.getClass().getName()));
                }/*www .  jav a2 s .  c o m*/
            }
            args[i] = argValue;
        }
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        try {
            method.invoke(target, args);
        } catch (Exception e) {
            throw new ConfigurationException(String.format("Failed to inject method configuration via %s of %s",
                    methodName, target.getClass().getName()), e);
        }
    }
}

From source file:org.apache.hadoop.gateway.config.impl.DefaultConfigurationInjector.java

private void injectMethodValue(Method method, Object target, ConfigurationAdapter adapter,
        ConfigurationBinding binding) throws ConfigurationException {
    Configure methodTag = method.getAnnotation(Configure.class);
    if (methodTag != null) {
        Alias aliasTag = method.getAnnotation(Alias.class);
        String methodName = getConfigName(method, aliasTag);
        Class[] argTypes = method.getParameterTypes();
        Object[] args = new Object[argTypes.length];
        Annotation[][] argTags = method.getParameterAnnotations();
        for (int i = 0; i < argTypes.length; i++) {
            String argName = getConfigName(methodName, argTags[i]);
            String bndName = getBindName(target, argName, binding);
            Object argValue = retrieveValue(target, bndName, argName, argTypes[i], adapter, binding);
            if (argValue == null) {
                Default defTag = findAnnotation(argTags[i], Default.class);
                if (defTag != null) {
                    String strValue = defTag.value();
                    argValue = convertValue(target, argName, strValue, argTypes[i]);
                } else {
                    throw new ConfigurationException(
                            String.format("Failed to find configuration for %s as %s of %s via %s", bndName,
                                    argName, target.getClass().getName(), adapter.getClass().getName()));
                }/* w  w w.j  a v a  2s.c om*/
            }
            args[i] = argValue;
        }
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        try {
            method.invoke(target, args);
        } catch (Exception e) {
            throw new ConfigurationException(String.format("Failed to inject method configuration via %s of %s",
                    methodName, target.getClass().getName()), e);
        }
    }
}

From source file:org.mayocat.localization.internal.DefaultEntityLocalizationService.java

@Override
public <T extends Localized> T localize(T entity, Locale locale) {
    if (locale == null || entity.getLocalizedVersions() == null
            || !entity.getLocalizedVersions().containsKey(locale)) {
        return entity;
    }// w ww.  j  av  a 2 s  .  c  om

    T copiedEntity = SerializationUtils.clone(entity);

    if (copiedEntity == null) {
        return entity;
    }

    // Special I/O case for loaded attachment : set back the input stream manually
    if (copiedEntity instanceof LoadedAttachment) {
        ((LoadedAttachment) copiedEntity)
                .setData(new AttachmentData(((LoadedAttachment) entity).getData().getStream()));
    }

    // Handle entity fields :
    // - loops over methods, checking for setters, then for each one of them
    // - infer a field name from found setter
    // - check if that field has a "LocalizedField" annotation, if not ignore
    // - if it does, try to find this field in the locale's map of translations
    // - if found and not null or empty string use the setter to set this as the localized field value

    for (Method method : copiedEntity.getClass().getDeclaredMethods()) {
        if (method.getName().startsWith("set") && Character.isUpperCase(method.getName().charAt(3))) {
            // Found a setter.
            if (method.getName().length() <= 4) {
                continue;
            }
            String fieldName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);

            Field field = null;
            try {
                field = copiedEntity.getClass().getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                this.logger.debug("Cannot find field for setter {}", method.getName());
            }

            // Check if either field or method has a "LocalizedField" annotation
            if (field != null && (field.isAnnotationPresent(LocalizedField.class)
                    || method.isAnnotationPresent(LocalizedField.class))) {
                Object value = null;
                if (copiedEntity.getLocalizedVersions().get(locale).containsKey(fieldName)) {

                    value = copiedEntity.getLocalizedVersions().get(locale).get(fieldName);

                    if (String.class.isAssignableFrom(value.getClass())
                            && Strings.isNullOrEmpty((String) value)) {
                        // Ignore empty strings, consider them as nulls
                        continue;
                    }

                    boolean setterAccessible = method.isAccessible();
                    method.setAccessible(true);
                    try {
                        method.invoke(copiedEntity, value);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        logger.error("Cannot set property {}", field.getName());
                    }

                    method.setAccessible(setterAccessible);
                }
            }
        }
    }

    // Handle entity addons :
    // - check if entity has addons and those addons are loaded, and the localized version contains something
    // for addons
    // - if yes, then loop over all the entity addons, and for each :
    // - try to find the equivalent addon in the map of translation
    // - if found, and its value is not null or empty string, replace the addon value by the localized one

    if (hasLoadedAddons(copiedEntity)
            && copiedEntity.getLocalizedVersions().get(locale).containsKey("addons")) {
        Map<String, AddonGroup> entityAddons = ((HasAddons) copiedEntity).getAddons().get();
        final Map<String, Object> localizedAddons = (Map<String, Object>) copiedEntity.getLocalizedVersions()
                .get(locale).get("addons");

        for (AddonGroup addon : entityAddons.values()) {
            if (localizedAddons.containsKey(addon.getGroup())) {
                Map<String, Object> localizedGroup = (Map<String, Object>) localizedAddons
                        .get(addon.getGroup());

                if (Map.class.isAssignableFrom(addon.getValue().getClass())) {

                    // Non-sequence addons

                    Map<String, Object> value = (Map<String, Object>) addon.getValue();
                    Map<String, Object> localizedGroupValue = (Map<String, Object>) localizedGroup.get("value");

                    for (String field : value.keySet()) {
                        Object localizedValue = localizedGroupValue.get(field);

                        if (localizedValue == null || (String.class.isAssignableFrom(localizedValue.getClass())
                                && Strings.isNullOrEmpty((String) localizedValue))) {
                            // Ignore empty strings, consider them as nulls
                            continue;
                        }

                        ((Map<String, Object>) addon.getValue()).put(field, localizedValue);
                    }
                } else if (List.class.isAssignableFrom(addon.getValue().getClass())) {

                    // Sequence addons

                    List<Map<String, Object>> values = (List<Map<String, Object>>) addon.getValue();
                    try {
                        List<Map<String, Object>> localizedGroupValue = (List<Map<String, Object>>) localizedGroup
                                .get("value");
                        Integer i = 0;
                        for (Map<String, Object> value : values) {
                            Map<String, Object> localizedGroupValueItem = localizedGroupValue.get(i);

                            for (String field : value.keySet()) {
                                Object localizedValue = localizedGroupValueItem.get(field);

                                if (localizedValue == null
                                        || (String.class.isAssignableFrom(localizedValue.getClass())
                                                && Strings.isNullOrEmpty((String) localizedValue))) {
                                    // Ignore empty strings, consider them as nulls
                                    continue;
                                }

                                ((List<Map<String, Object>>) addon.getValue()).get(i).put(field,
                                        localizedValue);
                            }
                            i++;
                        }
                    } catch (ClassCastException e) {
                        // Ignore...
                    }
                }
            }
        }
    }

    return copiedEntity;
}

From source file:plugin.google.maps.GoogleMaps.java

@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (isDebug) {
        if (args != null && args.length() > 0) {
            Log.d(TAG, "(debug)action=" + action + " args[0]=" + args.getString(0));
        } else {//from   ww  w .  jav a  2s  .  co  m
            Log.d(TAG, "(debug)action=" + action);
        }
    }

    Runnable runnable = new Runnable() {
        public void run() {
            if (("getMap".equals(action) == false && "isAvailable".equals(action) == false)
                    && GoogleMaps.this.map == null) {
                Log.w(TAG, "Can not execute '" + action + "' because the map is not created.");
                return;
            }
            if ("exec".equals(action)) {

                try {
                    String classMethod = args.getString(0);
                    String[] params = classMethod.split("\\.", 0);

                    if ("Map.setOptions".equals(classMethod)) {

                        JSONObject jsonParams = args.getJSONObject(1);
                        if (jsonParams.has("backgroundColor")) {
                            JSONArray rgba = jsonParams.getJSONArray("backgroundColor");
                            int backgroundColor = Color.WHITE;
                            if (rgba != null && rgba.length() == 4) {
                                try {
                                    backgroundColor = PluginUtil.parsePluginColor(rgba);
                                    mPluginLayout.setBackgroundColor(backgroundColor);
                                } catch (JSONException e) {
                                }
                            }
                        }

                    }

                    // Load the class plugin
                    GoogleMaps.this.loadPlugin(params[0]);

                    PluginEntry entry = GoogleMaps.this.plugins.get(params[0]);
                    if (params.length == 2 && entry != null) {
                        entry.plugin.execute("execute", args, callbackContext);
                    } else {
                        callbackContext.error("'" + action + "' parameter is invalid length.");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    callbackContext.error("Java Error\n" + e.getCause().getMessage());
                }
            } else {
                try {
                    Method method = GoogleMaps.this.getClass().getDeclaredMethod(action, JSONArray.class,
                            CallbackContext.class);
                    if (method.isAccessible() == false) {
                        method.setAccessible(true);
                    }
                    method.invoke(GoogleMaps.this, args, callbackContext);
                } catch (Exception e) {
                    e.printStackTrace();
                    callbackContext.error("'" + action + "' is not defined in GoogleMaps plugin.");
                }
            }
        }
    };
    cordova.getActivity().runOnUiThread(runnable);

    return true;
}