Example usage for java.lang.reflect Method getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private void writeNewAnnotation(final SourceWriter sw,
        final ConstraintDescriptor<? extends Annotation> constraint) throws UnableToCompleteException {
    final Annotation annotation = constraint.getAnnotation();
    final Class<? extends Annotation> annotationType = annotation.annotationType();

    // new MyAnnotation () {
    sw.print("new ");
    sw.print(annotationType.getCanonicalName());
    sw.println("(){");
    sw.indent();//from   w w  w .  j  a  v  a2s  . c  om
    sw.indent();

    // public Class<? extends Annotation> annotationType() { return
    // MyAnnotation.class; }
    sw.print("public Class<? extends Annotation> annotationType() {  return ");
    sw.print(annotationType.getCanonicalName());
    sw.println(".class; }");

    for (final Method method : annotationType.getMethods()) {
        // method.isAbstract would be better
        if (method.getDeclaringClass().equals(annotation.annotationType())) {
            // public returnType method() { return value ;}
            sw.print("public ");
            sw.print(method.getReturnType().getCanonicalName()); // TODO handle
                                                                 // generics
            sw.print(" ");
            sw.print(method.getName());
            sw.print("() { return ");

            try {
                final Object value = method.invoke(annotation);
                sw.print(asLiteral(value));
            } catch (final IllegalArgumentException e) {
                throw error(this.logger, e);
            } catch (final IllegalAccessException e) {
                throw error(this.logger, e);
            } catch (final InvocationTargetException e) {
                throw error(this.logger, e);
            }
            sw.println(";}");
        }
    }

    sw.outdent();
    sw.outdent();
    sw.println("}");
}

From source file:com.gatf.executor.core.AcceptanceTestContext.java

@SuppressWarnings("rawtypes")
public Class addTestCaseHooks(Method method) {
    Class claz = null;/* ww  w.j a v  a2s .c  o m*/
    if (method != null && Modifier.isStatic(method.getModifiers())) {

        Annotation preHook = method.getAnnotation(PreTestCaseExecutionHook.class);
        Annotation postHook = method.getAnnotation(PostTestCaseExecutionHook.class);

        if (preHook != null) {
            PreTestCaseExecutionHook hook = (PreTestCaseExecutionHook) preHook;

            if (method.getParameterTypes().length != 1
                    || !method.getParameterTypes()[0].equals(TestCase.class)) {
                logger.severe("PreTestCaseExecutionHook annotated methods should "
                        + "confirm to the method signature - `public static void {methodName} ("
                        + "TestCase testCase)`");
                return claz;
            }

            if (hook.value() != null && hook.value().length > 0) {
                for (String testCaseName : hook.value()) {
                    if (testCaseName != null && !testCaseName.trim().isEmpty()) {
                        prePostTestCaseExecHooks.put("pre" + testCaseName, method);
                    }
                }
            } else {
                prePostTestCaseExecHooks.put("preAll", method);
            }
            claz = method.getDeclaringClass();
        }
        if (postHook != null) {
            PostTestCaseExecutionHook hook = (PostTestCaseExecutionHook) postHook;

            if (method.getParameterTypes().length != 1
                    || !method.getParameterTypes()[0].equals(TestCaseReport.class)) {
                logger.severe("PostTestCaseExecutionHook annotated methods should "
                        + "confirm to the method signature - `public static void {methodName} ("
                        + "TestCaseReport testCaseReport)`");
                return claz;
            }

            if (hook.value() != null && hook.value().length > 0) {
                for (String testCaseName : hook.value()) {
                    if (testCaseName != null && !testCaseName.trim().isEmpty()) {
                        prePostTestCaseExecHooks.put("post" + testCaseName, method);
                    }
                }
            } else {
                prePostTestCaseExecHooks.put("postAll", method);
            }
            claz = method.getDeclaringClass();
        }
    }
    return claz;
}

From source file:ca.uhn.fhir.rest.method.SearchMethodBinding.java

public SearchMethodBinding(Class<? extends IBaseResource> theReturnResourceType, Method theMethod,
        FhirContext theContext, Object theProvider) {
    super(theReturnResourceType, theMethod, theContext, theProvider);
    Search search = theMethod.getAnnotation(Search.class);
    this.myQueryName = StringUtils.defaultIfBlank(search.queryName(), null);
    this.myCompartmentName = StringUtils.defaultIfBlank(search.compartmentName(), null);
    this.myIdParamIndex = MethodUtil.findIdParameterIndex(theMethod, getContext());
    this.myAllowUnknownParams = search.allowUnknownParams();

    Description desc = theMethod.getAnnotation(Description.class);
    if (desc != null) {
        if (isNotBlank(desc.formalDefinition())) {
            myDescription = StringUtils.defaultIfBlank(desc.formalDefinition(), null);
        } else {/*from  ww w .j ava  2 s .c  o m*/
            myDescription = StringUtils.defaultIfBlank(desc.shortDefinition(), null);
        }
    }

    /*
     * Check for parameter combinations and names that are invalid
     */
    List<IParameter> parameters = getParameters();
    // List<SearchParameter> searchParameters = new ArrayList<SearchParameter>();
    for (int i = 0; i < parameters.size(); i++) {
        IParameter next = parameters.get(i);
        if (!(next instanceof SearchParameter)) {
            continue;
        }

        SearchParameter sp = (SearchParameter) next;
        if (sp.getName().startsWith("_")) {
            if (ALLOWED_PARAMS.contains(sp.getName())) {
                String msg = getContext().getLocalizer().getMessage(
                        getClass().getName() + ".invalidSpecialParamName", theMethod.getName(),
                        theMethod.getDeclaringClass().getSimpleName(), sp.getName());
                throw new ConfigurationException(msg);
            }
        }

        // searchParameters.add(sp);
    }
    // for (int i = 0; i < searchParameters.size(); i++) {
    // SearchParameter next = searchParameters.get(i);
    // // next.
    // }

    /*
     * Only compartment searching methods may have an ID parameter
     */
    if (isBlank(myCompartmentName) && myIdParamIndex != null) {
        String msg = theContext.getLocalizer().getMessage(getClass().getName() + ".idWithoutCompartment",
                theMethod.getName(), theMethod.getDeclaringClass());
        throw new ConfigurationException(msg);
    }

}

From source file:ca.uhn.fhir.rest.method.MethodUtil.java

@SuppressWarnings("unchecked")
public static List<IParameter> getResourceParameters(final FhirContext theContext, Method theMethod,
        Object theProvider, RestOperationTypeEnum theRestfulOperationTypeEnum) {
    List<IParameter> parameters = new ArrayList<IParameter>();

    Class<?>[] parameterTypes = theMethod.getParameterTypes();
    int paramIndex = 0;
    for (Annotation[] annotations : theMethod.getParameterAnnotations()) {

        IParameter param = null;/* w w w.  j  av a  2s .  c  o m*/
        Class<?> parameterType = parameterTypes[paramIndex];
        Class<? extends java.util.Collection<?>> outerCollectionType = null;
        Class<? extends java.util.Collection<?>> innerCollectionType = null;
        if (SearchParameterMap.class.equals(parameterType)) {
            if (theProvider instanceof IDynamicSearchResourceProvider) {
                Search searchAnnotation = theMethod.getAnnotation(Search.class);
                if (searchAnnotation != null && searchAnnotation.dynamic()) {
                    param = new DynamicSearchParameter((IDynamicSearchResourceProvider) theProvider);
                }
            }
        } else if (TagList.class.isAssignableFrom(parameterType)) {
            // TagList is handled directly within the method bindings
            param = new NullParameter();
        } else {
            if (Collection.class.isAssignableFrom(parameterType)) {
                innerCollectionType = (Class<? extends java.util.Collection<?>>) parameterType;
                parameterType = ReflectionUtil.getGenericCollectionTypeOfMethodParameter(theMethod, paramIndex);
            }
            if (Collection.class.isAssignableFrom(parameterType)) {
                outerCollectionType = innerCollectionType;
                innerCollectionType = (Class<? extends java.util.Collection<?>>) parameterType;
                parameterType = ReflectionUtil.getGenericCollectionTypeOfMethodParameter(theMethod, paramIndex);
            }
            if (Collection.class.isAssignableFrom(parameterType)) {
                throw new ConfigurationException("Argument #" + paramIndex + " of Method '"
                        + theMethod.getName() + "' in type '" + theMethod.getDeclaringClass().getCanonicalName()
                        + "' is of an invalid generic type (can not be a collection of a collection of a collection)");
            }
        }

        /* 
         * Note: for the frst two here, we're using strings instead of static binding
         * so that we don't need the java.servlet JAR on the classpath in order to use
         * this class 
         */
        if (ourServletRequestTypes.contains(parameterType.getName())) {
            param = new ServletRequestParameter();
        } else if (ourServletResponseTypes.contains(parameterType.getName())) {
            param = new ServletResponseParameter();
        } else if (parameterType.equals(RequestDetails.class)) {
            param = new RequestDetailsParameter();
        } else if (parameterType.equals(IRequestOperationCallback.class)) {
            param = new RequestOperationCallbackParameter();
        } else if (parameterType.equals(SummaryEnum.class)) {
            param = new SummaryEnumParameter();
        } else if (parameterType.equals(PatchTypeEnum.class)) {
            param = new PatchTypeParameter();
        } else {
            for (int i = 0; i < annotations.length && param == null; i++) {
                Annotation nextAnnotation = annotations[i];

                if (nextAnnotation instanceof RequiredParam) {
                    SearchParameter parameter = new SearchParameter();
                    parameter.setName(((RequiredParam) nextAnnotation).name());
                    parameter.setRequired(true);
                    parameter.setDeclaredTypes(((RequiredParam) nextAnnotation).targetTypes());
                    parameter.setCompositeTypes(((RequiredParam) nextAnnotation).compositeTypes());
                    parameter.setChainlists(((RequiredParam) nextAnnotation).chainWhitelist(),
                            ((RequiredParam) nextAnnotation).chainBlacklist());
                    parameter.setType(theContext, parameterType, innerCollectionType, outerCollectionType);
                    MethodUtil.extractDescription(parameter, annotations);
                    param = parameter;
                } else if (nextAnnotation instanceof OptionalParam) {
                    SearchParameter parameter = new SearchParameter();
                    parameter.setName(((OptionalParam) nextAnnotation).name());
                    parameter.setRequired(false);
                    parameter.setDeclaredTypes(((OptionalParam) nextAnnotation).targetTypes());
                    parameter.setCompositeTypes(((OptionalParam) nextAnnotation).compositeTypes());
                    parameter.setChainlists(((OptionalParam) nextAnnotation).chainWhitelist(),
                            ((OptionalParam) nextAnnotation).chainBlacklist());
                    parameter.setType(theContext, parameterType, innerCollectionType, outerCollectionType);
                    MethodUtil.extractDescription(parameter, annotations);
                    param = parameter;
                } else if (nextAnnotation instanceof IncludeParam) {
                    Class<? extends Collection<Include>> instantiableCollectionType;
                    Class<?> specType;

                    if (parameterType == String.class) {
                        instantiableCollectionType = null;
                        specType = String.class;
                    } else if ((parameterType != Include.class) || innerCollectionType == null
                            || outerCollectionType != null) {
                        throw new ConfigurationException("Method '" + theMethod.getName()
                                + "' is annotated with @" + IncludeParam.class.getSimpleName()
                                + " but has a type other than Collection<" + Include.class.getSimpleName()
                                + ">");
                    } else {
                        instantiableCollectionType = (Class<? extends Collection<Include>>) CollectionBinder
                                .getInstantiableCollectionType(innerCollectionType,
                                        "Method '" + theMethod.getName() + "'");
                        specType = parameterType;
                    }

                    param = new IncludeParameter((IncludeParam) nextAnnotation, instantiableCollectionType,
                            specType);
                } else if (nextAnnotation instanceof ResourceParam) {
                    Mode mode;
                    if (IBaseResource.class.isAssignableFrom(parameterType)) {
                        mode = Mode.RESOURCE;
                    } else if (String.class.equals(parameterType)) {
                        mode = ResourceParameter.Mode.BODY;
                    } else if (byte[].class.equals(parameterType)) {
                        mode = ResourceParameter.Mode.BODY_BYTE_ARRAY;
                    } else if (EncodingEnum.class.equals(parameterType)) {
                        mode = Mode.ENCODING;
                    } else {
                        StringBuilder b = new StringBuilder();
                        b.append("Method '");
                        b.append(theMethod.getName());
                        b.append("' is annotated with @");
                        b.append(ResourceParam.class.getSimpleName());
                        b.append(" but has a type that is not an implemtation of ");
                        b.append(IBaseResource.class.getCanonicalName());
                        b.append(" or String or byte[]");
                        throw new ConfigurationException(b.toString());
                    }
                    param = new ResourceParameter((Class<? extends IResource>) parameterType, theProvider,
                            mode);
                } else if (nextAnnotation instanceof IdParam || nextAnnotation instanceof VersionIdParam) {
                    param = new NullParameter();
                } else if (nextAnnotation instanceof ServerBase) {
                    param = new ServerBaseParamBinder();
                } else if (nextAnnotation instanceof Elements) {
                    param = new ElementsParameter();
                } else if (nextAnnotation instanceof Since) {
                    param = new SinceParameter();
                    ((SinceParameter) param).setType(theContext, parameterType, innerCollectionType,
                            outerCollectionType);
                } else if (nextAnnotation instanceof At) {
                    param = new AtParameter();
                    ((AtParameter) param).setType(theContext, parameterType, innerCollectionType,
                            outerCollectionType);
                } else if (nextAnnotation instanceof Count) {
                    param = new CountParameter();
                } else if (nextAnnotation instanceof Sort) {
                    param = new SortParameter(theContext);
                } else if (nextAnnotation instanceof TransactionParam) {
                    param = new TransactionParameter(theContext);
                } else if (nextAnnotation instanceof ConditionalUrlParam) {
                    param = new ConditionalParamBinder(theRestfulOperationTypeEnum,
                            ((ConditionalUrlParam) nextAnnotation).supportsMultiple());
                } else if (nextAnnotation instanceof OperationParam) {
                    Operation op = theMethod.getAnnotation(Operation.class);
                    param = new OperationParameter(theContext, op.name(), ((OperationParam) nextAnnotation));
                } else if (nextAnnotation instanceof Validate.Mode) {
                    if (parameterType.equals(ValidationModeEnum.class) == false) {
                        throw new ConfigurationException("Parameter annotated with @"
                                + Validate.class.getSimpleName() + "." + Validate.Mode.class.getSimpleName()
                                + " must be of type " + ValidationModeEnum.class.getName());
                    }
                    param = new OperationParameter(theContext, Constants.EXTOP_VALIDATE,
                            Constants.EXTOP_VALIDATE_MODE, 0, 1).setConverter(new IOperationParamConverter() {
                                @Override
                                public Object incomingServer(Object theObject) {
                                    if (isNotBlank(theObject.toString())) {
                                        ValidationModeEnum retVal = ValidationModeEnum
                                                .forCode(theObject.toString());
                                        if (retVal == null) {
                                            OperationParameter.throwInvalidMode(theObject.toString());
                                        }
                                        return retVal;
                                    } else {
                                        return null;
                                    }
                                }

                                @Override
                                public Object outgoingClient(Object theObject) {
                                    return ParametersUtil.createString(theContext,
                                            ((ValidationModeEnum) theObject).getCode());
                                }
                            });
                } else if (nextAnnotation instanceof Validate.Profile) {
                    if (parameterType.equals(String.class) == false) {
                        throw new ConfigurationException("Parameter annotated with @"
                                + Validate.class.getSimpleName() + "." + Validate.Profile.class.getSimpleName()
                                + " must be of type " + String.class.getName());
                    }
                    param = new OperationParameter(theContext, Constants.EXTOP_VALIDATE,
                            Constants.EXTOP_VALIDATE_PROFILE, 0, 1)
                                    .setConverter(new IOperationParamConverter() {
                                        @Override
                                        public Object incomingServer(Object theObject) {
                                            return theObject.toString();
                                        }

                                        @Override
                                        public Object outgoingClient(Object theObject) {
                                            return ParametersUtil.createString(theContext,
                                                    theObject.toString());
                                        }
                                    });
                } else {
                    continue;
                }

            }

        }

        if (param == null) {
            throw new ConfigurationException("Parameter #" + ((paramIndex + 1)) + "/" + (parameterTypes.length)
                    + " of method '" + theMethod.getName() + "' on type '"
                    + theMethod.getDeclaringClass().getCanonicalName()
                    + "' has no recognized FHIR interface parameter annotations. Don't know how to handle this parameter");
        }

        param.initializeTypes(theMethod, outerCollectionType, innerCollectionType, parameterType);
        parameters.add(param);

        paramIndex++;
    }
    return parameters;
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

/**
 * Create a proper implementation of AttributeAccessor for the given
 * attribute type./*www . j  a v  a  2s .  c  om*/
 */
private AttributeAccessor createAttributeAccessor(final Method m, final String attrName, final Class arg) {
    AttributeAccessor result = new AttributeAccessor() {
        public Object get(XdmParseContext pc, Object parent)
                throws InvocationTargetException, IllegalAccessException {
            return m.invoke(parent, null);
        }

        public boolean isInherited() {
            return !m.getDeclaringClass().equals(bean);
        }

        public Class getDeclaringClass() {
            return m.getDeclaringClass();
        }
    };

    if (XdmBitmaskedFlagsAttribute.class.isAssignableFrom(arg))
        flagsAttributeAccessors.put(attrName, result);

    return result;
}

From source file:org.apache.openjpa.meta.ClassMetaData.java

/**
 * Ensure that the user has overridden the equals and hashCode methods,
 * and has the proper constructors./*from w w  w  . j av  a2s.c om*/
 */
private void validateAppIdClassMethods(Class<?> oid) {
    try {
        oid.getConstructor((Class[]) null);
    } catch (Exception e) {
        throw new MetaDataException(_loc.get("null-cons", oid, _type)).setCause(e);
    }

    // check for equals and hashcode overrides; don't enforce it
    // for abstract application id classes, since they may not necessarily
    // declare primary key fields
    Method method;
    try {
        method = oid.getMethod("equals", new Class[] { Object.class });
    } catch (Exception e) {
        throw new GeneralException(e).setFatal(true);
    }

    boolean abs = Modifier.isAbstract(_type.getModifiers());
    if (!abs && method.getDeclaringClass() == Object.class)
        throw new MetaDataException(_loc.get("eq-method", _type));

    try {
        method = oid.getMethod("hashCode", (Class[]) null);
    } catch (Exception e) {
        throw new GeneralException(e).setFatal(true);
    }
    if (!abs && method.getDeclaringClass() == Object.class)
        throw new MetaDataException(_loc.get("hc-method", _type));
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

/**
 * Create a proper implementation of AttributeSetter for the given
 * attribute type./*from  w w w  .  j a  v a 2s  . c o m*/
 */
private AttributeSetter createAttributeSetter(final Method m, final String attrName, final Class arg) {
    if (java.lang.String[].class.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Object[] { TextUtils.getInstance().split(value, ",", true) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.String.class.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new String[] { value });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.Character.class.equals(arg) || java.lang.Character.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Character[] { new Character(value.charAt(0)) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.Byte.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Byte[] { new Byte(value) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.Short.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Short[] { new Short(value) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.Integer.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Integer[] { new Integer(value) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.Long.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Long[] { new Long(value) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.Float.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Float[] { new Float(value) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.lang.Double.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Double[] { new Double(value) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    }
    // boolean gets an extra treatment, because we have a nice method
    else if (java.lang.Boolean.class.equals(arg) || java.lang.Boolean.TYPE.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                m.invoke(parent, new Boolean[] { new Boolean(TextUtils.getInstance().toBoolean(value)) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    }
    // Class doesn't have a String constructor but a decent factory method
    else if (java.lang.Class.class.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException, DataModelException {
                try {
                    m.invoke(parent, new Class[] { Class.forName(value) });
                } catch (ClassNotFoundException ce) {
                    if (pc != null) {
                        DataModelException dme = new DataModelException(pc, ce);
                        pc.addError(dme);
                        if (pc.isThrowErrorException())
                            throw dme;
                    } else
                        log.error(ce);
                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (java.io.File.class.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                // resolve relative paths through DataModel
                m.invoke(parent, new File[] { pc != null ? pc.resolveFile(value) : new File(value) });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (RedirectValueSource.class.isAssignableFrom(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                TextUtils textUtils = TextUtils.getInstance();
                ValueSource vs = ValueSources.getInstance().getValueSourceOrStatic(value);
                if (vs == null) {
                    // better to throw an error here since if there are objects which are based on null/non-null
                    // value of the value source, it is easier to debug
                    pc.addError("Unable to find ValueSource '" + value + "' to wrap in RedirectValueSource at "
                            + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber()
                            + ". Valid value sources are: "
                            + textUtils.join(ValueSources.getInstance().getAllValueSourceIdentifiers(), ", "));
                }
                try {
                    RedirectValueSource redirectValueSource = (RedirectValueSource) arg.newInstance();
                    redirectValueSource.setValueSource(vs);
                    m.invoke(parent, new RedirectValueSource[] { redirectValueSource });
                } catch (InstantiationException e) {
                    pc.addError("Unable to create RedirectValueSource for '" + value + "' at "
                            + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber()
                            + ". Valid value sources are: "
                            + textUtils.join(ValueSources.getInstance().getAllValueSourceIdentifiers(), ", "));
                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (ValueSource.class.equals(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException {
                TextUtils textUtils = TextUtils.getInstance();
                ValueSource vs = ValueSources.getInstance().getValueSourceOrStatic(value);
                if (vs == null) {
                    // better to throw an error here since if there are objects which are based on null/non-null
                    // value of the value source, it is easier to debug
                    if (pc != null)
                        pc.addError("Unable to create ValueSource for '" + value + "' at "
                                + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber()
                                + ". Valid value sources are: " + textUtils
                                        .join(ValueSources.getInstance().getAllValueSourceIdentifiers(), ", "));
                    else
                        log.error("Unable to create ValueSource for '" + value + ". Valid value sources are: "
                                + textUtils.join(ValueSources.getInstance().getAllValueSourceIdentifiers(),
                                        ", "));
                }
                m.invoke(parent, new ValueSource[] { vs });
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (Command.class.isAssignableFrom(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException, DataModelException {
                try {
                    m.invoke(parent, new Command[] { Commands.getInstance().getCommand(value) });
                } catch (CommandNotFoundException e) {
                    if (pc != null) {
                        pc.addError("Unable to create Command for '" + value + "' at "
                                + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber()
                                + ".");
                        if (pc.isThrowErrorException())
                            throw new DataModelException(pc, e);
                    } else
                        log.error("Unable to create Command for '" + value + "'", e);
                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (XdmEnumeratedAttribute.class.isAssignableFrom(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException, DataModelException {
                try {
                    XdmEnumeratedAttribute ea = (XdmEnumeratedAttribute) arg.newInstance();
                    ea.setValue(pc, parent, attrName, value);
                    m.invoke(parent, new XdmEnumeratedAttribute[] { ea });
                } catch (InstantiationException ie) {
                    pc.addError(ie);
                    if (pc.isThrowErrorException())
                        throw new DataModelException(pc, ie);
                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (XdmBitmaskedFlagsAttribute.class.isAssignableFrom(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException, DataModelException {
                try {
                    XdmBitmaskedFlagsAttribute bfa;
                    NestedCreator creator = (NestedCreator) nestedCreators.get(attrName);
                    if (creator != null)
                        bfa = (XdmBitmaskedFlagsAttribute) creator.create(parent);
                    else
                        bfa = (XdmBitmaskedFlagsAttribute) arg.newInstance();
                    bfa.setValue(pc, parent, attrName, value);
                    m.invoke(parent, new XdmBitmaskedFlagsAttribute[] { bfa });
                } catch (InstantiationException ie) {
                    pc.addError(ie);
                    if (pc.isThrowErrorException())
                        throw new DataModelException(pc, ie);
                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (Locale.class.isAssignableFrom(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException, DataModelException {
                String[] items = TextUtils.getInstance().split(value, ",", true);
                switch (items.length) {
                case 1:
                    m.invoke(parent, new Locale[] { new Locale(items[0], "") });
                    break;

                case 2:
                    m.invoke(parent, new Locale[] { new Locale(items[1], items[2]) });
                    break;

                case 3:
                    m.invoke(parent, new Locale[] { new Locale(items[1], items[2], items[3]) });
                    break;

                case 4:
                    if (pc != null)
                        throw new DataModelException(pc, "Too many items in Locale constructor.");
                    else
                        log.error("Too many items in Locale constructor: " + value);
                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (ResourceBundle.class.isAssignableFrom(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException, DataModelException {
                String[] items = TextUtils.getInstance().split(value, ",", true);
                switch (items.length) {
                case 1:
                    m.invoke(parent, new ResourceBundle[] { ResourceBundle.getBundle(items[0]) });
                    break;

                case 2:
                    m.invoke(parent, new ResourceBundle[] {
                            ResourceBundle.getBundle(items[0], new Locale(items[1], Locale.US.getCountry())) });
                    break;

                case 3:
                    m.invoke(parent, new ResourceBundle[] {
                            ResourceBundle.getBundle(items[0], new Locale(items[1], items[2])) });
                    break;

                case 4:
                    m.invoke(parent, new ResourceBundle[] {
                            ResourceBundle.getBundle(items[0], new Locale(items[1], items[2], items[3])) });

                default:
                    if (pc != null)
                        throw new DataModelException(pc, "Too many items in ResourceBundle constructor.");
                    else
                        log.error("Too many items in Locale constructor: " + value);

                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else if (Properties.class.isAssignableFrom(arg)) {
        return new AttributeSetter() {
            public void set(XdmParseContext pc, Object parent, String value)
                    throws InvocationTargetException, IllegalAccessException, DataModelException {
                // when specifying properties the following are valid
                // <xxx properties="abc.properties">  <!-- load this property file, throw exception if not found -->
                // <xxx properties="abc.properties:optional">  <!-- load this property file, no exception if not found -->
                // <xxx properties="/a/b/abc.properties,/x/y/def.properties"> <!-- load the first property file found, throw exception if none found -->
                // <xxx properties="/a/b/abc.properties,/x/y/def.properties:optional"> <!-- load the first property file found, no exception if none found -->

                final TextUtils textUtils = TextUtils.getInstance();
                final String[] options = textUtils.split(value, ":", true);
                final String[] fileNames = textUtils.split(value, ",", true);
                final Properties properties;
                switch (options.length) {
                case 1:
                    properties = PropertiesLoader.loadProperties(fileNames, true, false);
                    m.invoke(parent, new Properties[] { properties });
                    break;

                case 2:
                    properties = PropertiesLoader.loadProperties(fileNames,
                            options[1].equals("optional") ? false : true, false);
                    if (properties != null)
                        m.invoke(parent, new Properties[] { properties });
                    break;

                default:
                    if (pc != null)
                        throw new DataModelException(pc,
                                "Don't know how to get properties from PropertiesLoader: " + value);
                    else
                        log.error("Don't know how to get properties from PropertiesLoader:" + value);
                }
            }

            public boolean isInherited() {
                return !m.getDeclaringClass().equals(bean);
            }

            public Class getDeclaringClass() {
                return m.getDeclaringClass();
            }
        };
    } else {
        // worst case. look for a public String constructor and use it
        try {
            final Constructor c = arg.getConstructor(new Class[] { java.lang.String.class });
            return new AttributeSetter() {
                public void set(XdmParseContext pc, Object parent, String value)
                        throws InvocationTargetException, IllegalAccessException, DataModelException {
                    try {
                        Object attribute = c.newInstance(new String[] { value });
                        m.invoke(parent, new Object[] { attribute });
                    } catch (InstantiationException ie) {
                        if (pc != null) {
                            pc.addError(ie);
                            if (pc.isThrowErrorException())
                                throw new DataModelException(pc, ie);
                        } else
                            log.error(ie);
                    }
                }

                public boolean isInherited() {
                    return !m.getDeclaringClass().equals(bean);
                }

                public Class getDeclaringClass() {
                    return m.getDeclaringClass();
                }
            };
        } catch (NoSuchMethodException nme) {
        }
    }

    return null;
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private String mapObjToOutput(Object obj, int maxDepth, Stack<Object> serStack, boolean useGwtArray,
        boolean translateValue) {
    if (serStack.size() == 0) {
        log.log(Level.FINER, "Serializing START {0}", obj);
    }/* www . j a v  a 2s . com*/

    // Avoid recursion
    if (serStack.size() == maxDepth && !(obj instanceof Date || obj instanceof Number || obj instanceof Boolean
            || obj instanceof CharSequence || obj instanceof Enum)) {
        String objId = getIdFromObj(obj);
        return objId == null ? Q + Q : objId;
    }
    if (serStack.contains(obj)) {
        return getIdFromObj(obj);
        // return Q+"ref: "+obj.getClass().getName()+"@"+obj.hashCode()+Q;
    }
    serStack.push(obj);

    String startArray = useGwtArray ? "$wnd.Array.create([" : "[";
    String endArray = useGwtArray ? "])" : "]";

    StringBuilder recordData = new StringBuilder();
    if (obj == null) {
        recordData.append("null");
    } else if (obj instanceof Map) {
        recordData.append("{");
        Map objMap = (Map) obj;
        String delim = "";
        for (Object objKey : objMap.keySet()) {
            recordData.append(delim).append(objKey).append(":")
                    .append(mapObjToOutput(objMap.get(objKey), maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append("}");
    } else if (obj instanceof Collection) {
        recordData.append(startArray);
        Collection objSet = (Collection) obj;
        String delim = "";
        for (Object objVal : objSet) {
            recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append(endArray);
    } else if (obj instanceof List) {
        recordData.append(startArray);
        List objList = (List) obj;
        String delim = "";
        for (Object objVal : objList) {
            recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append(endArray);
    } else if (obj instanceof Object[]) {
        recordData.append(startArray);
        Object[] objArr = (Object[]) obj;
        String delim = "";
        for (Object objVal : objArr) {
            recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append(endArray);
    } else if (obj instanceof Date) {
        Date objDate = (Date) obj;
        // recordData.append(Q+dateTimeFormat.format(objDate)+Q);
        recordData.append("new Date(" + objDate.getTime() + ")");
    } else if (obj instanceof Boolean) {
        recordData.append(obj);
    } else if (obj instanceof Number) {
        recordData.append(obj);
    } else if (obj instanceof CharSequence) {
        String strObj = obj.toString();
        if (strObj.startsWith(Main.JAVASCRIPT_PREFIX) && useGwtArray) {
            recordData.append(" ").append(strObj.substring(Main.JAVASCRIPT_PREFIX.length()));
        } else if (strObj.startsWith("function") && useGwtArray) {
            recordData.append(" ").append(strObj);
        } else {
            strObj = translateValue ? translate(strObj) : strObj;
            String escapeString = strObj.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"")
                    .replaceAll("\\r", "\\\\r").replaceAll("\\n", "\\\\n");
            recordData.append(Q + escapeString + Q);
        }
    } else if (obj instanceof Enum) {
        String val = ((Enum) obj).name();
        if (useGwtArray) {
            try {
                Method getValMethod = obj.getClass().getMethod("getValue", (Class[]) null);
                val = (String) getValMethod.invoke(obj, (Object[]) null);
            } catch (Exception e) {
                // no method getValue
            }
        }
        recordData.append(Q + val + Q);
    } else {
        String className = obj.getClass().getName();
        ServiceDescription serviceForClass = findServiceByClassName(className);
        log.log(Level.FINER, "Serializing class {0}", className);
        if (serStack.size() > 2 && serviceForClass != null) {
            recordData.append(getIdFromObj(obj));
        } else {
            // Use reflection
            recordData.append("{");
            String delim = "";
            String jsonPostfix = null;
            Method[] methods = obj.getClass().getMethods();
            for (Method m : methods) {
                boolean translateThisValue = false;
                String mName;
                if (m.getName().startsWith(GET_TRANSLATE)) {
                    translateThisValue = true;
                    mName = m.getName().substring(GET_TRANSLATE_LENGTH);
                } else if (m.getName().startsWith("is")) {
                    mName = m.getName().substring(2);
                } else {
                    mName = m.getName().substring(3);
                }

                if (mName.length() > 1 && Character.isLowerCase(mName.charAt(1))) {
                    mName = mName.substring(0, 1).toLowerCase() + mName.substring(1);
                }

                if (m.getName().startsWith("getJsonPostfix") && m.getParameterTypes().length == 0
                        && String.class.equals(m.getReturnType())) {
                    try {
                        jsonPostfix = (String) m.invoke(obj, new Object[] {});
                    } catch (Throwable e) {
                        log.log(Level.FINE, "Mapping error", e);
                    }
                } else if (!m.getDeclaringClass().getName().startsWith("org.hibernate")
                        && m.getDeclaringClass() != Object.class && m.getDeclaringClass() != Class.class
                        && (m.getName().startsWith("get") || m.getName().startsWith("is"))
                        && m.getParameterTypes().length == 0 && m.getReturnType() != null
                        && !isHiddenField(m.getDeclaringClass().getName(), mName)) {
                    log.log(Level.FINEST, "Reflection invoking name={0} declaringClass={1} on {2}[{3}]",
                            new Object[] { m.getName(), m.getDeclaringClass(), obj, obj.getClass() });
                    try {
                        Object result = m.invoke(obj, new Object[] {});
                        if (result != null) {
                            mName = mName.startsWith("xxx") ? mName.substring(3) : mName;
                            String resultClassName = AopUtils.getTargetClass(result).getName();
                            String idVal = getIdFromObj(result);
                            String valStr;
                            if (findServiceByClassName(resultClassName) != null && idVal != null) {
                                recordData.append(delim).append(mName).append(":").append(idVal);
                                String refField = ds2Ref.get(resultClassName);
                                if (refField != null) {
                                    Object realVal = getValFromObj(refField, result);
                                    valStr = realVal == null ? Q + Q : Q + realVal + Q;
                                } else {
                                    valStr = Q + "UNKNOWN" + Q;
                                }
                                mName = mName + "_VAL";
                                delim = ", ";
                            } else {
                                valStr = mapObjToOutput(result, maxDepth, serStack, useGwtArray,
                                        translateThisValue);
                            }
                            recordData.append(delim).append(mName).append(":").append(valStr);
                            delim = ", ";
                        }
                    } catch (Throwable e) {
                        log.log(Level.FINE, "Mapping error", e);
                    }
                }
            }

            if (jsonPostfix != null) {
                recordData.append(delim).append(jsonPostfix).append("}");
            } else {
                recordData.append("}");
            }
        }
    }
    serStack.pop();
    return recordData.toString();
}

From source file:javadz.beanutils.PropertyUtilsBean.java

/** This just catches and wraps IllegalArgumentException. */
private Object invokeMethod(Method method, Object bean, Object[] values)
        throws IllegalAccessException, InvocationTargetException {
    if (bean == null) {
        throw new IllegalArgumentException(
                "No bean specified " + "- this should have been checked before reaching this method");
    }// w  w  w. j  a v  a 2 s.c o  m

    try {

        return method.invoke(bean, values);

    } catch (NullPointerException cause) {
        // JDK 1.3 and JDK 1.4 throw NullPointerException if an argument is
        // null for a primitive value (JDK 1.5+ throw IllegalArgumentException)
        String valueString = "";
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    valueString += ", ";
                }
                if (values[i] == null) {
                    valueString += "<null>";
                } else {
                    valueString += (values[i]).getClass().getName();
                }
            }
        }
        String expectedString = "";
        Class[] parTypes = method.getParameterTypes();
        if (parTypes != null) {
            for (int i = 0; i < parTypes.length; i++) {
                if (i > 0) {
                    expectedString += ", ";
                }
                expectedString += parTypes[i].getName();
            }
        }
        IllegalArgumentException e = new IllegalArgumentException(
                "Cannot invoke " + method.getDeclaringClass().getName() + "." + method.getName()
                        + " on bean class '" + bean.getClass() + "' - " + cause.getMessage()
                        // as per https://issues.apache.org/jira/browse/BEANUTILS-224
                        + " - had objects of type \"" + valueString + "\" but expected signature \""
                        + expectedString + "\"");
        if (!BeanUtils.initCause(e, cause)) {
            log.error("Method invocation failed", cause);
        }
        throw e;
    } catch (IllegalArgumentException cause) {
        String valueString = "";
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    valueString += ", ";
                }
                if (values[i] == null) {
                    valueString += "<null>";
                } else {
                    valueString += (values[i]).getClass().getName();
                }
            }
        }
        String expectedString = "";
        Class[] parTypes = method.getParameterTypes();
        if (parTypes != null) {
            for (int i = 0; i < parTypes.length; i++) {
                if (i > 0) {
                    expectedString += ", ";
                }
                expectedString += parTypes[i].getName();
            }
        }
        IllegalArgumentException e = new IllegalArgumentException(
                "Cannot invoke " + method.getDeclaringClass().getName() + "." + method.getName()
                        + " on bean class '" + bean.getClass() + "' - " + cause.getMessage()
                        // as per https://issues.apache.org/jira/browse/BEANUTILS-224
                        + " - had objects of type \"" + valueString + "\" but expected signature \""
                        + expectedString + "\"");
        if (!BeanUtils.initCause(e, cause)) {
            log.error("Method invocation failed", cause);
        }
        throw e;

    }
}