Example usage for java.lang.reflect Method getModifiers

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

Introduction

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

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:net.minecraftforge.fml.common.FMLModContainer.java

@SuppressWarnings("unchecked")
private Method gatherAnnotations(Class<?> clazz) throws Exception {
    Method factoryMethod = null;//from   w w  w  . j  a  v a2  s.c o m
    for (Method m : clazz.getDeclaredMethods()) {
        for (Annotation a : m.getAnnotations()) {
            if (a.annotationType().equals(Mod.EventHandler.class)) {
                if (m.getParameterTypes().length == 1
                        && FMLEvent.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    m.setAccessible(true);
                    eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0], m);
                } else {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called",
                            getModId(), a.annotationType().getSimpleName());
                }
            } else if (a.annotationType().equals(Mod.InstanceFactory.class)) {
                if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0
                        && factoryMethod == null) {
                    m.setAccessible(true);
                    factoryMethod = m;
                } else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                } else if (factoryMethod != null) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                }
            }
        }
    }
    return factoryMethod;
}

From source file:org.apache.axis.description.JavaServiceDesc.java

/**
 * Synchronize an existing OperationDesc to a java.lang.Method.
 *
 * This method is used when the deployer has specified operation metadata
 * and we want to match that up with a real java Method so that the
 * Operation-level dispatch carries us all the way to the implementation.
 * Search the declared methods on the implementation class to find one
 * with an argument list which matches our parameter list.
 *//*from ww w . ja  va2s. c o  m*/
private void syncOperationToClass(OperationDesc oper, Class implClass) {
    // ------------------------------------------------
    // Developer Note:
    //
    // The goal of the sync code is to associate
    // the OperationDesc/ParamterDesc with the
    // target Method.  There are a number of ways to get to this
    // point depending on what information
    // is available.  Here are the main scenarios:
    //
    // A) Deployment with wsdd (non-skeleton):
    //   * OperationDesc/ParameterDesc loaded from deploy.wsdd
    //   * Loaded ParameterDesc does not have javaType,
    //     so it is discovered using the TypeMappingRegistry
    //     (also loaded via deploy.wsdd) and the
    //     typeQName specified by the ParameterDesc.
    //   * Sync occurs using the discovered
    //     javaTypes and the javaTypes of the Method
    //     parameters
    //
    // B) Deployment with no wsdd OperationDesc info (non-skeleton):
    //   * Implementation Class introspected to build
    //     OperationDesc/ParameterDesc.
    //   * ParameterDesc is known via introspection.
    //   * ParameterDesc are discovered using javaType
    //     and TypeMappingRegistry.
    //   * Sync occurs using the introspected
    //     javaTypes and the javaTypes of the Method
    //     parameters
    //
    // C) Deployment with wsdd (skeleton):
    //   * OperationDesc/ParameterDesc loaded from the Skeleton
    //   * In this scenario the ParameterDescs' already
    //     have javaTypes (see E below).
    //   * Sync occurs using the ParameterDesc
    //     javaTypes and the javaTypes of the Method
    //     parameters.
    //
    // D) Commandline Java2WSDL loading non-Skeleton Class/Interface
    //   * Class/Interface introspected to build
    //     OperationDesc/ParameterDesc.
    //   * The javaTypes of the ParameterDesc are set using introspection.
    //   * typeQNames are determined for built-in types using
    //     from the default TypeMappingRegistry.  Other
    //     typeQNames are guessed from the javaType.  Note
    //     that there is no loaded TypeMappingRegistry.
    //   * Sync occurs using the ParameterDesc
    //     javaTypes and the javaTypes of the Method
    //     parameters.
    //
    // E) Commandline Java2WSDL loading Skeleton Class
    //   * OperationDesc/ParameterDesc loaded from Skeleton
    //   * Each ParameterDesc has an appropriate typeQName
    //   * Each ParameterDesc also has a javaType, which is
    //     essential for sync'ing up with the
    //     method since there is no loaded TypeMappingRegistry.
    //   * Syncronization occurs using the ParameterDesc
    //     javaTypes and the javaTypes of the Method
    //     parameters.
    //
    // So in each scenario, the ultimate sync'ing occurs
    // using the javaTypes of the ParameterDescs and the
    // javaTypes of the Method parameters.
    //
    // ------------------------------------------------

    // If we're already mapped to a Java method, no need to do anything.
    if (oper.getMethod() != null)
        return;

    // Find the method.  We do this once for each Operation.

    Method[] methods = getMethods(implClass);
    // A place to keep track of possible matches
    Method possibleMatch = null;

    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (Modifier.isPublic(method.getModifiers()) && method.getName().equals(oper.getName())
                && method2OperationMap.get(method) == null) {

            if (style == Style.MESSAGE) {
                int messageOperType = checkMessageMethod(method);
                if (messageOperType == OperationDesc.MSG_METHOD_NONCONFORMING)
                    continue;
                if (messageOperType == -1) {
                    throw new InternalException(
                            "Couldn't match method to any of the allowable message-style patterns!");
                }
                oper.setMessageOperationStyle(messageOperType);

                // Don't bother checking params if we're message style
                possibleMatch = method;
                break;
            }

            // Check params
            Class[] paramTypes = method.getParameterTypes();
            if (paramTypes.length != oper.getNumParams())
                continue;

            int j;
            boolean conversionNecessary = false;
            for (j = 0; j < paramTypes.length; j++) {
                Class type = paramTypes[j];
                Class actualType = type;
                if (Holder.class.isAssignableFrom(type)) {
                    actualType = JavaUtils.getHolderValueType(type);
                }
                ParameterDesc param = oper.getParameter(j);
                QName typeQName = param.getTypeQName();
                if (typeQName == null) {
                    // No typeQName is available.  Set it using
                    // information from the actual type.
                    // (Scenarios B and D)
                    // There is no need to try and match with
                    // the Method parameter javaType because
                    // the ParameterDesc is being constructed
                    // by introspecting the Method.
                    typeQName = getTypeMapping().getTypeQName(actualType);
                    param.setTypeQName(typeQName);
                } else {
                    // A type qname is available.
                    // Ensure that the ParameterDesc javaType
                    // is convertable to the Method parameter type
                    //
                    // Use the available javaType (Scenarios C and E)
                    // or get one from the TMR (Scenario A).
                    Class paramClass = param.getJavaType();
                    if (paramClass != null && JavaUtils.getHolderValueType(paramClass) != null) {
                        paramClass = JavaUtils.getHolderValueType(paramClass);
                    }
                    if (paramClass == null) {
                        paramClass = getTypeMapping().getClassForQName(param.getTypeQName(), type);
                    }

                    if (paramClass != null) {
                        // This is a match if the paramClass is somehow
                        // convertable to the "real" parameter type.  If not,
                        // break out of this loop.
                        if (!JavaUtils.isConvertable(paramClass, actualType)) {
                            break;
                        }

                        if (!actualType.isAssignableFrom(paramClass)) {
                            // This doesn't fit without conversion
                            conversionNecessary = true;
                        }
                    }
                }
                // In all scenarios the ParameterDesc javaType is set to
                // match the javaType in the corresponding parameter.
                // This is essential.
                param.setJavaType(type);
            }

            if (j != paramTypes.length) {
                // failed.
                continue;
            }

            // This is our latest possibility
            possibleMatch = method;

            // If this is exactly it, stop now.  Otherwise keep looking
            // just in case we find a better match.
            if (!conversionNecessary) {
                break;
            }

        }
    }

    // At this point, we may or may not have a possible match.
    // FIXME : Should we prefer an exact match from a base class over
    //         a with-conversion match from the target class?  If so,
    //         we'll need to change the logic below.
    if (possibleMatch != null) {
        Class returnClass = possibleMatch.getReturnType();
        oper.setReturnClass(returnClass);

        QName returnType = oper.getReturnType();
        if (returnType == null) {
            oper.setReturnType(getTypeMapping().getTypeQName(returnClass));
        }

        // Do the faults
        createFaultMetadata(possibleMatch, oper);

        oper.setMethod(possibleMatch);
        method2OperationMap.put(possibleMatch, oper);
        return;
    }

    // Didn't find a match.  Try the superclass, if appropriate
    Class superClass = implClass.getSuperclass();
    if (superClass != null && !superClass.getName().startsWith("java.")
            && !superClass.getName().startsWith("javax.")
            && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
        syncOperationToClass(oper, superClass);
    }

    // Exception if sync fails to find method for operation
    if (oper.getMethod() == null) {
        InternalException ie = new InternalException(
                Messages.getMessage("serviceDescOperSync00", oper.getName(), implClass.getName()));
        throw ie;
    }
}

From source file:com.weibo.api.motan.config.AbstractConfig.java

/**
 * config ?Map// w  ww.j  a  v a  2  s  .co m
 * 
 * @param parameters
 */
@SuppressWarnings("unchecked")
protected void appendConfigParams(Map<String, String> parameters, String prefix) {
    Method[] methods = this.getClass().getMethods();
    for (Method method : methods) {
        try {
            String name = method.getName();
            if (isConfigMethod(method)) {
                int idx = name.startsWith("get") ? 3 : 2;
                String prop = name.substring(idx, idx + 1).toLowerCase() + name.substring(idx + 1);
                String key = prop;
                ConfigDesc configDesc = method.getAnnotation(ConfigDesc.class);
                if (configDesc != null && !StringUtils.isBlank(configDesc.key())) {
                    key = configDesc.key();
                }

                Object value = method.invoke(this);
                if (value == null || StringUtils.isBlank(String.valueOf(value))) {
                    if (configDesc != null && configDesc.required()) {
                        throw new MotanFrameworkException(
                                String.format("%s.%s should not be null or empty",
                                        this.getClass().getSimpleName(), key),
                                MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
                    }
                    continue;
                }
                if (prefix != null && prefix.length() > 0) {
                    key = prefix + "." + key;
                }
                parameters.put(key, String.valueOf(value).trim());
            } else if ("getParameters".equals(name) && Modifier.isPublic(method.getModifiers())
                    && method.getParameterTypes().length == 0 && method.getReturnType() == Map.class) {
                Map<String, String> map = (Map<String, String>) method.invoke(this);
                if (map != null && map.size() > 0) {
                    String pre = prefix != null && prefix.length() > 0 ? prefix + "." : "";
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        parameters.put(pre + entry.getKey(), entry.getValue());
                    }
                }
            }
        } catch (Exception e) {
            throw new MotanFrameworkException(String.format("Error when append params for config: %s.%s",
                    this.getClass().getSimpleName(), method.getName()), e,
                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
        }
    }
}

From source file:com.jskaleel.xml.JSONObject.java

private void populateMap(Object bean) {
    Class klass = bean.getClass();

    // If klass is a System class then set includeSuperClass to false.

    boolean includeSuperClass = klass.getClassLoader() != null;

    Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
        try {/*from  w w w. j  a  va2s .  co m*/
            Method method = methods[i];
            if (Modifier.isPublic(method.getModifiers())) {
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")) {
                    if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
                        key = "";
                    } else {
                        key = name.substring(3);
                    }
                } else if (name.startsWith("is")) {
                    key = name.substring(2);
                }
                if (key.length() > 0 && Character.isUpperCase(key.charAt(0))
                        && method.getParameterTypes().length == 0) {
                    if (key.length() == 1) {
                        key = key.toLowerCase();
                    } else if (!Character.isUpperCase(key.charAt(1))) {
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                    }

                    Object result = method.invoke(bean, (Object[]) null);
                    if (result != null) {
                        this.map.put(key, wrap(result));
                    }
                }
            }
        } catch (Exception ignore) {
        }
    }
}

From source file:com.github.helenusdriver.driver.impl.ClassInfoImpl.java

/**
 * Finds an initial objects factory method for the POJO if configured.
 *
 * @author paouelle/* w  w  w .java  2  s  .c  o m*/
 *
 * @return the initial objects factory method or <code>null</code> if none
 *         configured
 * @throws IllegalArgumentException if the initial objects method is not
 *         properly defined
 */
private Method findInitial() {
    final InitialObjects io = clazz.getAnnotation(InitialObjects.class);

    if (io != null) {
        final String mname = io.staticMethod();

        try {
            final Method m = (suffixesByType.isEmpty() ? clazz.getMethod(mname)
                    : clazz.getMethod(mname, Map.class));

            // validate the method is static
            if (!Modifier.isStatic(m.getModifiers())) {
                throw new IllegalArgumentException("initial objects method '" + mname
                        + "' is not static in class: " + clazz.getSimpleName());
            }
            // validate the return type is compatible with this class and is an array
            final Class<?> type = m.getReturnType();

            if (!type.isArray()) {
                throw new IllegalArgumentException("initial objects method '" + mname
                        + "' doesn't return an array in class: " + clazz.getSimpleName());
            }
            final Class<?> ctype = type.getComponentType();

            if (!ctype.isAssignableFrom(clazz)) {
                throw new IllegalArgumentException("incompatible returned class '" + ctype.getName()
                        + "' for initial objects method '" + mname + "' in class: " + clazz.getSimpleName());
            }
            // validate that if suffixes are defined, the method expects a Map<String, String>
            // to provide the values for the suffixes when initializing objects
            final Class<?>[] cparms = m.getParameterTypes();

            if (suffixesByType.isEmpty()) {
                // should always be 0 as we used no classes in getMethod()
                if (cparms.length != 0) {
                    throw new IllegalArgumentException("expecting no parameters for initial objects method '"
                            + mname + "' in class: " + clazz.getSimpleName());
                }
            } else {
                // should always be 1 as we used only 1 class in getMethod()
                if (cparms.length != 1) {
                    throw new IllegalArgumentException(
                            "expecting one Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
                // should always be a map as we used a Map to find the method
                if (!Map.class.isAssignableFrom(cparms[0])) {
                    throw new IllegalArgumentException("expecting parameter for initial objects method '"
                            + mname + "' to be of type Map<String, String> in class: " + clazz.getSimpleName());
                }
                final Type[] tparms = m.getGenericParameterTypes();

                // should always be 1 as we used only 1 class in getMethod()
                if (tparms.length != 1) { // should always be 1 as it was already tested above
                    throw new IllegalArgumentException(
                            "expecting one Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
                if (tparms[0] instanceof ParameterizedType) {
                    final ParameterizedType ptype = (ParameterizedType) tparms[0];

                    // maps will always have 2 arguments
                    for (final Type atype : ptype.getActualTypeArguments()) {
                        final Class<?> aclazz = ReflectionUtils.getRawClass(atype);

                        if (String.class != aclazz) {
                            throw new IllegalArgumentException(
                                    "expecting a Map<String, String> parameter for initial objects method '"
                                            + mname + "' in class: " + clazz.getSimpleName());
                        }
                    }
                } else {
                    throw new IllegalArgumentException(
                            "expecting a Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
            }
            return m;
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(
                    "missing initial objects method '" + mname + "' in class: " + clazz.getSimpleName(), e);
        }
    }
    return null;
}

From source file:com.ng.mats.psa.mt.paga.data.JSONObject.java

private void populateMap(Object bean) {
    Class<?> klass = bean.getClass();

    // If klass is a System class then set includeSuperClass to false.

    boolean includeSuperClass = klass.getClassLoader() != null;

    Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
        try {/*from w w  w.  j  a v  a2 s . c  o m*/
            Method method = methods[i];
            if (Modifier.isPublic(method.getModifiers())) {
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")) {
                    if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
                        key = "";
                    } else {
                        key = name.substring(3);
                    }
                } else if (name.startsWith("is")) {
                    key = name.substring(2);
                }
                if (key.length() > 0 && Character.isUpperCase(key.charAt(0))
                        && method.getParameterTypes().length == 0) {
                    if (key.length() == 1) {
                        key = key.toLowerCase();
                    } else if (!Character.isUpperCase(key.charAt(1))) {
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                    }

                    Object result = method.invoke(bean, (Object[]) null);
                    if (result != null) {
                        this.map.put(key, wrap(result));
                    }
                }
            }
        } catch (Exception ignore) {
        }
    }
}

From source file:com.google.dexmaker.ProxyBuilder.java

private void getMethodsToProxy(Set<MethodSetEntry> sink, Set<MethodSetEntry> seenFinalMethods, Class<?> c) {
    for (Method method : c.getDeclaredMethods()) {
        for (Class<? extends Annotation> annotation : Constants.annotation) {
            if (method.getAnnotation(annotation) != null) {
                MethodSetEntry entry = new MethodSetEntry(method);
                if (seenFinalMethods.contains(entry)) {
                    continue;
                }//w w  w.j a v a2  s  . co m
                if (sink.add(entry)) {
                    MethodEntity entity = new MethodEntity();
                    entity.clazz = c;
                    entity.name = method.getName();
                    entity.params = method.getParameterTypes();
                    entity.method = method;
                    methods.add(entity);
                }
            }
        }

        if (!Constants.method.contains(method.getName())) {
            // ??
            continue;
        }
        if ((method.getModifiers() & Modifier.FINAL) != 0) {
            // Skip final methods, we can't override them. We
            // also need to remember them, in case the same
            // method exists in a parent class.
            seenFinalMethods.add(new MethodSetEntry(method));
            continue;
        }

        if ((method.getModifiers() & STATIC) != 0) {
            // Skip static methods, overriding them has no effect.
            continue;
        }
        if ((method.getModifiers() & PRIVATE) != 0) {
            // Skip static methods, overriding them has no effect.
            continue;
        }
        //         if ((method.getModifiers() & Modifier.PROTECTED) != 0) {
        //            // Skip static methods, overriding them has no effect.
        //            continue;
        //         }
        if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) {
            // Skip finalize method, it's likely important that it execute as normal.
            continue;
        }
        MethodSetEntry entry = new MethodSetEntry(method);
        if (seenFinalMethods.contains(entry)) {
            // This method is final in a child class.
            // We can't override it.
            continue;
        }
        if (sink.add(entry)) {
            MethodEntity entity = new MethodEntity();
            entity.clazz = c;
            entity.name = method.getName();
            entity.params = method.getParameterTypes();
            entity.method = method;
            methods.add(entity);
        }
    }

    for (Class<?> i : c.getInterfaces()) {
        getMethodsToProxy(sink, seenFinalMethods, i);
    }
}

From source file:org.guzz.builder.JPA2AnnotationsBuilder.java

protected static void parseClassForAttributes(GuzzContextImpl gf, POJOBasedObjectMapping map, Business business,
        DBGroup dbGroup, SimpleTable st, Class domainClass) {
    //???//  ww w .  j  a  v a2s . co m
    Class parentCls = domainClass.getSuperclass();
    if (parentCls != null && parentCls.isAnnotationPresent(MappedSuperclass.class)) {
        parseClassForAttributes(gf, map, business, dbGroup, st, parentCls);
    }

    javax.persistence.Access access = (javax.persistence.Access) domainClass
            .getAnnotation(javax.persistence.Access.class);
    AccessType accessType = null;

    if (access == null) {
        //@Id@Idfieldproperty
        boolean hasColumnAOnField = false;
        boolean hasColumnAOnProperty = false;

        //detect from @Id, field first.
        Field[] fs = domainClass.getDeclaredFields();

        for (Field f : fs) {
            if (f.isAnnotationPresent(Transient.class))
                continue;
            if (f.isAnnotationPresent(javax.persistence.Id.class)) {
                accessType = AccessType.FIELD;
                break;
            } else if (f.isAnnotationPresent(javax.persistence.Column.class)) {
                hasColumnAOnField = true;
            } else if (f.isAnnotationPresent(org.guzz.annotations.Column.class)) {
                hasColumnAOnField = true;
            }
        }

        if (accessType == null) {
            Method[] ms = domainClass.getDeclaredMethods();
            for (Method m : ms) {
                if (m.isAnnotationPresent(Transient.class))
                    continue;
                if (m.isAnnotationPresent(javax.persistence.Id.class)) {
                    accessType = AccessType.PROPERTY;
                    break;
                } else if (m.isAnnotationPresent(javax.persistence.Column.class)) {
                    hasColumnAOnProperty = true;
                } else if (m.isAnnotationPresent(org.guzz.annotations.Column.class)) {
                    hasColumnAOnProperty = true;
                }
            }
        }

        //@Id@Column@Columnfield?
        if (accessType == null) {
            if (hasColumnAOnField) {
                accessType = AccessType.FIELD;
            } else if (hasColumnAOnProperty) {
                accessType = AccessType.PROPERTY;
            } else {
                accessType = AccessType.FIELD;
            }
        }
    } else {
        accessType = access.value();
    }

    //orm by field
    if (accessType == AccessType.FIELD) {
        Field[] fs = domainClass.getDeclaredFields();

        for (Field f : fs) {
            if (f.isAnnotationPresent(Transient.class))
                continue;
            if (Modifier.isTransient(f.getModifiers()))
                continue;
            if (Modifier.isStatic(f.getModifiers()))
                continue;

            if (f.isAnnotationPresent(javax.persistence.Id.class)) {
                addIdMapping(gf, map, st, dbGroup, f.getName(), domainClass, f);
            } else {
                addPropertyMapping(gf, map, st, f.getName(), f, f.getType());
            }
        }
    } else {
        Method[] ms = domainClass.getDeclaredMethods();
        for (Method m : ms) {
            if (m.isAnnotationPresent(Transient.class))
                continue;
            if (Modifier.isTransient(m.getModifiers()))
                continue;
            if (Modifier.isStatic(m.getModifiers()))
                continue;
            if (Modifier.isPrivate(m.getModifiers()))
                continue;

            String methodName = m.getName();
            String fieldName = null;

            if (m.getParameterTypes().length != 0) {
                continue;
            } else if (Void.TYPE.equals(m.getReturnType())) {
                continue;
            }

            if (methodName.startsWith("get")) {
                fieldName = methodName.substring(3);
            } else if (methodName.startsWith("is")) {//is boolean?
                Class retType = m.getReturnType();

                if (boolean.class.isAssignableFrom(retType)) {
                    fieldName = methodName.substring(2);
                } else if (Boolean.class.isAssignableFrom(retType)) {
                    fieldName = methodName.substring(2);
                }
            }

            //not a javabean read method
            if (fieldName == null) {
                continue;
            }

            fieldName = java.beans.Introspector.decapitalize(fieldName);

            if (m.isAnnotationPresent(javax.persistence.Id.class)) {
                addIdMapping(gf, map, st, dbGroup, fieldName, domainClass, m);
            } else {
                addPropertyMapping(gf, map, st, fieldName, m, m.getReturnType());
            }
        }
    }

    //?attribute override
    AttributeOverride gao = (AttributeOverride) domainClass.getAnnotation(AttributeOverride.class);
    AttributeOverrides gaos = (AttributeOverrides) domainClass.getAnnotation(AttributeOverrides.class);
    AttributeOverride[] aos = gao == null ? new AttributeOverride[0] : new AttributeOverride[] { gao };
    if (gaos != null) {
        ArrayUtil.addToArray(aos, gaos.value());
    }

    for (AttributeOverride ao : aos) {
        String name = ao.name();
        Column col = ao.column();

        TableColumn tc = st.getColumnByPropName(name);
        Assert.assertNotNull(tc,
                "@AttributeOverride cann't override a attribute that doesn't exist. The attribute is:" + name);

        //update is remove and add
        st.removeColumn(tc);

        //change the column name in the database.
        tc.setColName(col.name());

        st.addColumn(tc);
    }
}

From source file:org.dasein.persist.PersistentCache.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype)
        throws PersistenceException {
    LookupDelegate delegate = getLookupDelegate(fieldName);

    if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) {
        throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid.");
    }//from   w ww  .  j ava2  s. c  o  m
    try {
        if (toType.equals(String.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof String)) {
                dataStoreValue = dataStoreValue.toString();
            }
        } else if (Enum.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null) {
                Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString());

                dataStoreValue = e;
            }
        } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) {
            if (dataStoreValue == null) {
                dataStoreValue = false;
            } else if (!(dataStoreValue instanceof Boolean)) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    dataStoreValue = (((Number) dataStoreValue).intValue() != 0);
                } else {
                    dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true")
                            || dataStoreValue.toString().trim().equalsIgnoreCase("y"));
                }
            }
        } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class)
                || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class)
                || toType.equals(float.class) || toType.equals(double.class)) {
            if (dataStoreValue == null) {
                if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) {
                    dataStoreValue = 0;
                } else if (toType.equals(float.class) || toType.equals(double.class)) {
                    dataStoreValue = 0.0f;
                }
            } else if (toType.equals(Number.class)) {
                if (!(dataStoreValue instanceof Number)) {
                    if (dataStoreValue instanceof String) {
                        try {
                            dataStoreValue = Double.parseDouble((String) dataStoreValue);
                        } catch (NumberFormatException e) {
                            throw new PersistenceException("Unable to map " + fieldName + " as " + toType
                                    + " using " + dataStoreValue);
                        }
                    } else if (dataStoreValue instanceof Boolean) {
                        dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                    } else {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                }
            } else if (toType.equals(Integer.class) || toType.equals(int.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Integer)) {
                        dataStoreValue = ((Number) dataStoreValue).intValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Integer.parseInt((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Long.class) || toType.equals(long.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Long)) {
                        dataStoreValue = ((Number) dataStoreValue).longValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Long.parseLong((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Byte.class) || toType.equals(byte.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Byte)) {
                        dataStoreValue = ((Number) dataStoreValue).byteValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Byte.parseByte((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Short.class) || toType.equals(short.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Short)) {
                        dataStoreValue = ((Number) dataStoreValue).shortValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Short.parseShort((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Double.class) || toType.equals(double.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Double)) {
                        dataStoreValue = ((Number) dataStoreValue).doubleValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Double.parseDouble((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Float.class) || toType.equals(float.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Float)) {
                        dataStoreValue = ((Number) dataStoreValue).floatValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Float.parseFloat((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigDecimal.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigDecimal)) {
                        if (dataStoreValue instanceof BigInteger) {
                            dataStoreValue = new BigDecimal((BigInteger) dataStoreValue);
                        } else {
                            dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigInteger.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigInteger)) {
                        if (dataStoreValue instanceof BigDecimal) {
                            dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger();
                        } else {
                            dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (dataStoreValue != null) {
                logger.error("Type of dataStoreValue=" + dataStoreValue.getClass());
                throw new PersistenceException(
                        "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
            }
        } else if (toType.equals(Locale.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) {
                String[] parts = dataStoreValue.toString().split("_");

                if (parts != null && parts.length > 1) {
                    dataStoreValue = new Locale(parts[0], parts[1]);
                } else {
                    dataStoreValue = new Locale(parts[0]);
                }
            }
        } else if (Measured.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null && ptype != null) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    Constructor<? extends Measured> constructor = null;
                    double value = ((Number) dataStoreValue).doubleValue();

                    for (Constructor<?> c : toType.getDeclaredConstructors()) {
                        Class[] args = c.getParameterTypes();

                        if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0])
                                && UnitOfMeasure.class.isAssignableFrom(args[1])) {
                            constructor = (Constructor<? extends Measured>) c;
                            break;
                        }
                    }
                    if (constructor == null) {
                        throw new PersistenceException("Unable to map with no proper constructor");
                    }
                    dataStoreValue = constructor.newInstance(value,
                            ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                } else if (!(dataStoreValue instanceof Measured)) {
                    try {
                        dataStoreValue = Double.parseDouble(dataStoreValue.toString());
                    } catch (NumberFormatException e) {
                        Method method = null;

                        for (Method m : toType.getDeclaredMethods()) {
                            if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) {
                                if (m.getParameterTypes().length == 1
                                        && m.getParameterTypes()[0].equals(String.class)) {
                                    method = m;
                                    break;
                                }
                            }
                        }
                        if (method == null) {
                            throw new PersistenceException("Don't know how to map " + dataStoreValue + " to "
                                    + toType + "<" + ptype + ">");
                        }
                        dataStoreValue = method.invoke(null, dataStoreValue.toString());
                    }
                }
                // just because we converted it to a measured object above doesn't mean
                // we have the unit of measure right
                if (dataStoreValue instanceof Measured) {
                    UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0])
                            .newInstance();

                    if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) {
                        dataStoreValue = ((Measured) dataStoreValue).convertTo(
                                (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                    }
                }
            }
        } else if (toType.equals(UUID.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) {
                dataStoreValue = UUID.fromString(dataStoreValue.toString());
            }
        } else if (toType.equals(TimeZone.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) {
                dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString());
            }
        } else if (toType.equals(Currency.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) {
                dataStoreValue = Currency.getInstance(dataStoreValue.toString());
            }
        } else if (toType.isArray()) {
            Class<?> t = toType.getComponentType();

            if (dataStoreValue == null) {
                dataStoreValue = Array.newInstance(t, 0);
            } else if (dataStoreValue instanceof JSONArray) {
                JSONArray arr = (JSONArray) dataStoreValue;

                if (long.class.isAssignableFrom(t)) {
                    long[] replacement = (long[]) Array.newInstance(long.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (int.class.isAssignableFrom(t)) {
                    int[] replacement = (int[]) Array.newInstance(int.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (float.class.isAssignableFrom(t)) {
                    float[] replacement = (float[]) Array.newInstance(float.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (double.class.isAssignableFrom(t)) {
                    double[] replacement = (double[]) Array.newInstance(double.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (boolean.class.isAssignableFrom(t)) {
                    boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else {
                    Object[] replacement = (Object[]) Array.newInstance(t, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                }
            } else if (!dataStoreValue.getClass().isArray()) {
                logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to "
                        + toType.getName());
                logger.error("Value of " + fieldName + "=" + dataStoreValue);
                throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName());
            }
        } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) {
            Annotation[] alist = toType.getDeclaredAnnotations();
            boolean autoJSON = false;

            for (Annotation a : alist) {
                if (a instanceof AutoJSON) {
                    autoJSON = true;
                }
            }
            if (autoJSON) {
                dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue);
            } else {
                try {
                    Method m = toType.getDeclaredMethod("valueOf", JSONObject.class);

                    dataStoreValue = m.invoke(null, dataStoreValue);
                } catch (NoSuchMethodException ignore) {
                    try {
                        Method m = toType.getDeclaredMethod("valueOf", String.class);

                        if (m != null) {
                            dataStoreValue = m.invoke(null, dataStoreValue.toString());
                        } else {
                            throw new PersistenceException(
                                    "No valueOf() field in " + toType + " for mapping " + fieldName);
                        }
                    } catch (NoSuchMethodException e) {
                        throw new PersistenceException("No valueOf() field in " + toType + " for mapping "
                                + fieldName + " with " + dataStoreValue + ": ("
                                + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")");
                    }
                }
            }
        }
    } catch (Exception e) {
        String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage();
        logger.error(err, e);
        throw new PersistenceException();
    }
    return dataStoreValue;
}

From source file:com.zenesis.qx.remote.ProxyMethod.java

/**
 * @param name/*  w  w  w . j a v a 2  s .c o m*/
 * @param returnType
 * @param parameters
 */
public ProxyMethod(Method method) {
    super();
    this.method = method;

    Class returnType = method.getReturnType();
    Class keyType = String.class;
    boolean prefetchResult = false;
    boolean cacheResult = false;
    isMap = Map.class.isAssignableFrom(returnType);
    com.zenesis.qx.remote.annotations.Method anno = method
            .getAnnotation(com.zenesis.qx.remote.annotations.Method.class);

    if (returnType.isArray() || Iterable.class.isAssignableFrom(returnType) || isMap) {
        // How to present on the client - only ArrayList by default is wrapped on the client
        Remote.Array array;
        if (returnType.isArray()) {
            returnType = returnType.getComponentType();
            array = Remote.Array.NATIVE;
        } else {
            returnType = Object.class;
            array = Remote.Array.WRAP;
        }

        // Component type
        if (anno != null) {
            if (anno.array() != Remote.Array.DEFAULT)
                array = anno.array();
            if (anno.arrayType() != Object.class)
                returnType = anno.arrayType();
            if (anno.keyType() != Object.class)
                keyType = anno.keyType();
        }
        this.array = array;
        this.arrayType = returnType;
    } else {
        array = null;
        this.arrayType = null;
    }

    if (anno != null) {
        if (method.getParameterTypes().length == 0) {
            prefetchResult = anno.prefetchResult();
            cacheResult = anno.cacheResult() || prefetchResult;
        }
    }

    this.keyType = keyType;
    this.prefetchResult = prefetchResult;
    this.staticMethod = (method.getModifiers() & Modifier.STATIC) != 0;
    if (staticMethod && cacheResult) {
        log.warn("Cannot cacheResult on static method " + method);
        cacheResult = false;
    }
    this.cacheResult = cacheResult;
}