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:guru.qas.martini.jmeter.sampler.MartiniSampler.java

protected SampleResult getSubResult(Step step, Method method, Pattern pattern) {
    String label = getLabel(step);
    SampleResult result = new SampleResult();
    result.setSuccessful(true);//w  w  w  .ja  v a2s .  c om
    result.sampleStart();

    SamplerContext samplerContext = new SamplerContext(super.getThreadContext());

    try {
        ApplicationContext applicationContext = this.getApplicationContext();
        Parameter[] parameters = method.getParameters();
        Object[] arguments = new Object[parameters.length];

        if (parameters.length > 0) {
            String text = step.getText();
            Matcher matcher = pattern.matcher(text);
            checkState(matcher.find(), "unable to locate substitution parameters for pattern %s with input %s",
                    pattern.pattern(), text);

            ConversionService conversionService = applicationContext.getBean(ConversionService.class);

            int groupCount = matcher.groupCount();
            for (int i = 0; i < groupCount; i++) {
                String parameterAsString = matcher.group(i + 1);
                Parameter parameter = parameters[i];
                Class<?> parameterType = parameter.getType();
                Object converted = conversionService.convert(parameterAsString, parameterType);
                arguments[i] = converted;
            }
        }

        samplerContext.setStatus(Status.PASSED);
        Class<?> declaringClass = method.getDeclaringClass();
        Object bean = applicationContext.getBean(declaringClass);
        Object returnValue = method.invoke(bean, arguments);
        if (HttpEntity.class.isInstance(returnValue)) {
            HttpEntity entity = HttpEntity.class.cast(returnValue);
            samplerContext.setHttpEntities(Collections.singleton(entity));
        }
    } catch (Exception e) {
        samplerContext.setStatus(Status.FAILED);
        samplerContext.setException(e);
        result.setSuccessful(false);
        label = "FAIL: " + label;
    } finally {
        result.sampleEnd();
        result.setSampleLabel(label);
    }
    return result;
}

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

protected OperationMethodBinding(Class<?> theReturnResourceType,
        Class<? extends IBaseResource> theReturnTypeFromRp, Method theMethod, FhirContext theContext,
        Object theProvider, boolean theIdempotent, String theOperationName,
        Class<? extends IBaseResource> theOperationType, OperationParam[] theReturnParams,
        BundleTypeEnum theBundleType) {//w  w w . j  av  a2  s  .c  o m
    super(theReturnResourceType, theMethod, theContext, theProvider);

    myBundleType = theBundleType;
    myIdempotent = theIdempotent;
    myIdParamIndex = MethodUtil.findIdParameterIndex(theMethod, getContext());
    if (myIdParamIndex != null) {
        for (Annotation next : theMethod.getParameterAnnotations()[myIdParamIndex]) {
            if (next instanceof IdParam) {
                myCanOperateAtTypeLevel = ((IdParam) next).optional() == true;
            }
        }
    } else {
        myCanOperateAtTypeLevel = true;
    }

    Description description = theMethod.getAnnotation(Description.class);
    if (description != null) {
        myDescription = description.formalDefinition();
        if (isBlank(myDescription)) {
            myDescription = description.shortDefinition();
        }
    }
    if (isBlank(myDescription)) {
        myDescription = null;
    }

    if (isBlank(theOperationName)) {
        throw new ConfigurationException("Method '" + theMethod.getName() + "' on type "
                + theMethod.getDeclaringClass().getName() + " is annotated with @"
                + Operation.class.getSimpleName() + " but this annotation has no name defined");
    }
    if (theOperationName.startsWith("$") == false) {
        theOperationName = "$" + theOperationName;
    }
    myName = theOperationName;

    if (theContext.getVersion().getVersion().isEquivalentTo(FhirVersionEnum.DSTU1)) {
        throw new ConfigurationException("@" + Operation.class.getSimpleName()
                + " methods are not supported on servers for FHIR version "
                + theContext.getVersion().getVersion().name() + " - Found one on class "
                + theMethod.getDeclaringClass().getName());
    }

    if (theReturnTypeFromRp != null) {
        setResourceName(theContext.getResourceDefinition(theReturnTypeFromRp).getName());
    } else {
        if (Modifier.isAbstract(theOperationType.getModifiers()) == false) {
            setResourceName(theContext.getResourceDefinition(theOperationType).getName());
        } else {
            setResourceName(null);
        }
    }

    if (theMethod.getReturnType().isAssignableFrom(Bundle.class)) {
        throw new ConfigurationException("Can not return a DSTU1 bundle from an @"
                + Operation.class.getSimpleName() + " method. Found in method " + theMethod.getName()
                + " defined in type " + theMethod.getDeclaringClass().getName());
    }

    if (theMethod.getReturnType().equals(IBundleProvider.class)) {
        myReturnType = ReturnTypeEnum.BUNDLE;
    } else {
        myReturnType = ReturnTypeEnum.RESOURCE;
    }

    if (getResourceName() == null) {
        myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_SERVER;
    } else if (myIdParamIndex == null) {
        myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_TYPE;
    } else {
        myOtherOperatiopnType = RestOperationTypeEnum.EXTENDED_OPERATION_INSTANCE;
    }

    myReturnParams = new ArrayList<OperationMethodBinding.ReturnType>();
    if (theReturnParams != null) {
        for (OperationParam next : theReturnParams) {
            ReturnType type = new ReturnType();
            type.setName(next.name());
            type.setMin(next.min());
            type.setMax(next.max());
            if (type.getMax() == OperationParam.MAX_DEFAULT) {
                type.setMax(1);
            }
            if (!next.type().equals(IBase.class)) {
                if (next.type().isInterface() || Modifier.isAbstract(next.type().getModifiers())) {
                    throw new ConfigurationException(
                            "Invalid value for @OperationParam.type(): " + next.type().getName());
                }
                type.setType(theContext.getElementDefinition(next.type()).getName());
            }
            myReturnParams.add(type);
        }
    }

    if (myIdParamIndex != null) {
        myCanOperateAtInstanceLevel = true;
    }
    if (getResourceName() == null) {
        myCanOperateAtServerLevel = true;
    }

}

From source file:io.swagger.jaxrs.SynapseReader.java

public List<String> extractOperationMethods(ApiOperation apiOperation, Method method,
        Iterator<SwaggerExtension> chain) {
    ArrayList<String> a = new ArrayList<>();
    if (apiOperation != null && apiOperation.httpMethod() != null && !"".equals(apiOperation.httpMethod())) {
        a.add(apiOperation.httpMethod().toLowerCase());
        return a;
    } else if (method.getAnnotation(RequestMapping.class) != null) {
        List<String> l = Arrays.asList(method.getAnnotation(RequestMapping.class).method()).stream()
                .map((org.thingsplode.synapse.core.RequestMethod rm) -> rm.toString().toLowerCase())
                .collect(Collectors.toList());
        if (l.isEmpty()) {
            if (method.getParameterCount() > 0 && (method.getAnnotations().length == 0
                    || method.getAnnotation(RequestBody.class) != null)) {
                //if there are parameters but not annotated at all or the RequestBody annotation is used
                l.add("put");
            } else if (method.getParameterCount() == 0 && !method.getReturnType().equals(Void.TYPE)) {
                //if there are no parameters but there's a return type
                l.add("get");
            } else {
                //if there are no parameters and no return type (void method)
                l.add("post");
            }//from w  w  w .ja va2  s. co m
        }
        return l;
    } else if (SynapseEndpointServiceMarker.class.isAssignableFrom(method.getDeclaringClass())
            || method.getDeclaringClass().getAnnotation(Service.class) != null) {
        if (method.getParameterCount() > 0) {
            a.add("post");
        } else {
            a.add("get");
        }
        //todo: enable this when the service registry will support this differentiation
        //if (method.getReturnType().equals(Void.TYPE)) {
        //    a.add("post");
        //} else {
        //    a.add("get");
        //}
        return a;
    } else if ((ReflectionUtils.getOverriddenMethod(method)) != null) {
        return extractOperationMethods(apiOperation, ReflectionUtils.getOverriddenMethod(method), chain);
    } else if (chain != null && chain.hasNext()) {
        a.add(chain.next().extractOperationMethod(apiOperation, method, chain));
        return a;
    } else {
        return a;
    }
}

From source file:com.laxser.blitz.web.impl.module.ControllerRef.java

private Map<ReqMethod, String[]> collectsShotcutMappings(Method method) {
    Map<ReqMethod, String[]> restMethods = new HashMap<ReqMethod, String[]>();
    Annotation[] annotations = method.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation instanceof Delete) {
            restMethods.put(ReqMethod.DELETE, ((Delete) annotation).value());
        } else if (annotation instanceof Get) {
            restMethods.put(ReqMethod.GET, ((Get) annotation).value());
        } else if (annotation instanceof Head) {
            restMethods.put(ReqMethod.HEAD, ((Head) annotation).value());
        } else if (annotation instanceof Options) {
            restMethods.put(ReqMethod.OPTIONS, ((Options) annotation).value());
        } else if (annotation instanceof Post) {
            restMethods.put(ReqMethod.POST, ((Post) annotation).value());
        } else if (annotation instanceof Put) {
            restMethods.put(ReqMethod.PUT, ((Put) annotation).value());
        } else if (annotation instanceof Trace) {
            restMethods.put(ReqMethod.TRACE, ((Trace) annotation).value());
        } else {//from w w  w .  j av a 2  s  .co  m
        }
    }
    for (String[] paths : restMethods.values()) {
        for (int i = 0; i < paths.length; i++) {
            if (paths[i].equals("/")) {
                paths[i] = "";
            } else if (paths[i].length() > 0 && paths[i].charAt(0) != '/') {
                paths[i] = "/" + paths[i];
            }
            if (paths[i].length() > 1 && paths[i].endsWith("/")) {
                if (paths[i].endsWith("//")) {
                    throw new IllegalArgumentException(
                            "invalid path '" + paths[i] + "' for method " + method.getDeclaringClass().getName()
                                    + "#" + method.getName() + ": don't end with more than one '/'");
                }
                paths[i] = paths[i].substring(0, paths[i].length() - 1);
            }
        }
    }
    return restMethods;
}

From source file:io.cloudslang.lang.runtime.steps.ActionSteps.java

protected Object[] resolveActionArguments(Map<String, SerializableSessionObject> serializableSessionData,
        Method actionMethod, Map<String, Serializable> currentContext,
        Map<String, Object> nonSerializableExecutionData) {
    List<Object> args = new ArrayList<>();

    int index = 0;
    Class[] parameterTypes = actionMethod.getParameterTypes();
    for (Annotation[] annotations : actionMethod.getParameterAnnotations()) {
        index++;/*  w  w  w. jav  a 2  s .co  m*/
        for (Annotation annotation : annotations) {
            if (annotation instanceof Param) {
                if (parameterTypes[index - 1].equals(GlobalSessionObject.class)) {
                    handleNonSerializableSessionContextArgument(nonSerializableExecutionData, args,
                            (Param) annotation);
                } else if (parameterTypes[index - 1].equals(SerializableSessionObject.class)) {
                    handleSerializableSessionContextArgument(serializableSessionData, args, (Param) annotation);
                } else {
                    String parameterName = ((Param) annotation).value();
                    Serializable value = currentContext.get(parameterName);
                    Class parameterClass = parameterTypes[index - 1];
                    if (parameterClass.isInstance(value) || value == null) {
                        args.add(value);
                    } else {
                        StringBuilder exceptionMessageBuilder = new StringBuilder();
                        exceptionMessageBuilder.append("Parameter type mismatch for action ");
                        exceptionMessageBuilder.append(actionMethod.getName());
                        exceptionMessageBuilder.append(" of class ");
                        exceptionMessageBuilder.append(actionMethod.getDeclaringClass().getName());
                        exceptionMessageBuilder.append(". Parameter ");
                        exceptionMessageBuilder.append(parameterName);
                        exceptionMessageBuilder.append(" expects type ");
                        exceptionMessageBuilder.append(parameterClass.getName());
                        throw new RuntimeException(exceptionMessageBuilder.toString());
                    }
                }
            }
        }
        if (args.size() != index) {
            throw new RuntimeException("All action arguments should be annotated with @Param");
        }
    }
    return args.toArray(new Object[args.size()]);
}

From source file:com.sinosoft.one.mvc.web.impl.module.ControllerRef.java

private Map<ReqMethod, String[]> collectsShotcutMappings(Method method) {
    Map<ReqMethod, String[]> restMethods = new HashMap<ReqMethod, String[]>();
    Annotation[] annotations = method.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation instanceof Delete) {
            restMethods.put(ReqMethod.DELETE, ((Delete) annotation).value());
        } else if (annotation instanceof Get) {
            restMethods.put(ReqMethod.GET, ((Get) annotation).value());
        } else if (annotation instanceof Head) {
            restMethods.put(ReqMethod.HEAD, ((Head) annotation).value());
        } else if (annotation instanceof Options) {
            restMethods.put(ReqMethod.OPTIONS, ((Options) annotation).value());
        } else if (annotation instanceof Post) {
            restMethods.put(ReqMethod.POST, ((Post) annotation).value());
        } else if (annotation instanceof Put) {
            restMethods.put(ReqMethod.PUT, ((Put) annotation).value());
        } else if (annotation instanceof Trace) {
            restMethods.put(ReqMethod.TRACE, ((Trace) annotation).value());
        } else {//w w w  .jav  a 2  s  .co m
        }
    }

    for (String[] paths : restMethods.values()) {
        for (int i = 0; i < paths.length; i++) {
            if (paths[i].equals("/")) {
                paths[i] = "";
            } else if (paths[i].length() > 0 && paths[i].charAt(0) != '/') {
                paths[i] = "/" + paths[i];
            }
            if (paths[i].length() > 1 && paths[i].endsWith("/")) {
                if (paths[i].endsWith("//")) {
                    throw new IllegalArgumentException(
                            "invalid path '" + paths[i] + "' for method " + method.getDeclaringClass().getName()
                                    + "#" + method.getName() + ": don't end with more than one '/'");
                }
                paths[i] = paths[i].substring(0, paths[i].length() - 1);
            }
        }
    }
    return restMethods;
}

From source file:io.swagger.jaxrs.SynapseReader.java

List<String> getPaths(Service serviceAnnotation, Method method, String parentPath) {
    final List<String> pathList = new ArrayList<>();
    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
    if (serviceAnnotation == null && requestMapping == null && StringUtils.isEmpty(parentPath)) {
        //if not a service, request mapping annotation and the parent path is also empty
        return pathList;
    }/*from  www .  j  a va2 s.c  om*/

    StringBuilder b = new StringBuilder();
    if (parentPath != null && !"".equals(parentPath) && !"/".equals(parentPath)) {
        if (!parentPath.startsWith("/")) {
            parentPath = "/" + parentPath;
        }
        if (parentPath.endsWith("/")) {
            parentPath = parentPath.substring(0, parentPath.length() - 1);
        }

        b.append(parentPath);
    }
    if (serviceAnnotation != null) {
        b.append(serviceAnnotation.value());
    }

    if (requestMapping != null && requestMapping.value().length > 0) {
        Arrays.asList(requestMapping.value()).forEach(methodPath -> {
            String fullPath = b.toString();
            if (!"/".equalsIgnoreCase(methodPath)) {
                if (!methodPath.startsWith("/") && !b.toString().endsWith("/")) {
                    b.append("/");
                }
                if (methodPath.endsWith("/")) {
                    methodPath = methodPath.substring(0, methodPath.length() - 1);
                }
                pathList.add(fullPath + methodPath);
            }
        });
    } else if (method.getDeclaringClass().getAnnotation(Service.class) != null) {
        pathList.add(b.append("/").append(method.getName()).toString());
    }

    return pathList.stream().map(o -> !o.startsWith("/") ? "/" + o : o)
            .map(o -> ((o.endsWith("/") && o.length() > 1)) ? o.substring(0, o.length() - 1) : o)
            .collect(Collectors.toList());
}

From source file:com.asakusafw.testdriver.TestDriverTestToolsBase.java

private void initialize(Method caller) {
    assert caller != null;
    try {/*from   w w w  .  jav a2s  .  c  o m*/
        File buildPropertiesFile = new File(BUILD_PROPERTIES_FILE);
        if (buildPropertiesFile.exists()) {
            LOG.info("?????: {}", buildPropertiesFile);
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(buildPropertiesFile);
                buildProperties = new Properties();
                buildProperties.load(fis);
                System.setProperty("ASAKUSA_MODELGEN_PACKAGE",
                        buildProperties.getProperty("asakusa.modelgen.package"));
                System.setProperty("ASAKUSA_MODELGEN_OUTPUT",
                        buildProperties.getProperty("asakusa.modelgen.output"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        } else {
            LOG.info("??????????: {}",
                    BUILD_PROPERTIES_FILE);
        }
        System.setProperty("ASAKUSA_TESTTOOLS_CONF", String.format("%s/bulkloader/conf/%s-jdbc.properties",
                System.getenv("ASAKUSA_HOME"), buildProperties.getProperty("asakusa.database.target")));
        System.setProperty("ASAKUSA_TEMPLATEGEN_OUTPUT_DIR",
                buildProperties.getProperty("asakusa.testdatasheet.output"));
        String testDataDirPath = buildProperties.getProperty("asakusa.testdriver.testdata.dir");
        if (testDataDirPath == null) {
            testDataDirPath = TESTDATA_DIR_DEFAULT;
        }
        if (testDataFileList == null) {
            testDataDir = new File(testDataDirPath + File.separatorChar
                    + caller.getDeclaringClass().getSimpleName() + File.separatorChar + caller.getName());
            testUtils = new TestUtils(testDataDir);
        } else {
            testUtils = new TestUtils(testDataFileList);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:adalid.core.Project.java

/**
 *
 *//*from w w  w . j  a v  a2s .  c om*/
private void invokeAddAttributesMethods() {
    String name;
    Class<?> clazz;
    Class<?> parameterType;
    for (Method method : _addAttributesMethods) {
        clazz = method.getDeclaringClass();
        name = method.getName();
        parameterType = method.getParameterTypes()[0];
        for (Artifact artifact : _artifacts) {
            if (parameterType.isAssignableFrom(artifact.getClass())) {
                if (Entity.class.isAssignableFrom(artifact.getClass()) && artifact.depth() != 0) {
                    continue;
                }
                try {
                    logger.debug(signature(clazz.getSimpleName() + "." + name,
                            parameterType + " " + artifact.getClassPath()));
                    method.invoke(null, artifact);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                    fatal(ex);
                }
            }
        }
    }
}

From source file:com.p5solutions.core.jpa.orm.EntityUtility.java

/**
 * Builds the embeddable parameter list.
 * //w  ww  . j  a va  2 s.c  o m
 * @param <T>
 *          the generic type
 * @param parentClazz
 *          the parent clazz
 * @param bindingPath
 *          the binding path
 * @param getterMethod
 *          the getter method
 * @param setterMethod
 *          the setter method
 * @param pbs
 *          the pbs
 * @param recursionFilterList
 *          the recursion filter list
 * @return true, if successful
 */
@SuppressWarnings("unchecked")
public <T> boolean buildEmbeddable(Class<T> parentClazz, String bindingPath, Method getterMethod,
        Method setterMethod, List<ParameterBinder> pbs, List<Class<?>> recursionFilterList) {

    Embedded embedded = ReflectionUtility.findAnnotation(getterMethod, Embedded.class);

    // TODO Should we process the class if the getter is not marked with
    // @Embedded? but the class itself is marked with @Embeddedable??
    // Hibernate does it, but hibernate tries to be too COOL!
    if (embedded == null) {

        // check for embeddedable on the actual class type!!
        Class<?> returnType = getterMethod.getReturnType();
        if (ReflectionUtility.hasAnyAnnotation(returnType, Embeddable.class)) {
            String error = "For consistency sake, you must define the " + Embedded.class
                    + " annotation on the getter method " + getterMethod.getName() + " within entity type "
                    + getterMethod.getDeclaringClass();
            throw new AnnotationNotDefinedException(error);
        }

    } else {
        Class<?> embeddableClazz = getterMethod.getReturnType();

        // [Java GENERICS] - Parameterized annotation class type "..." is
        // unchecked, probably should create Annotation[] { } ?
        if (!ReflectionUtility.hasAnyAnnotation(embeddableClazz, Embeddable.class)) {
            String error = "Class type " + embeddableClazz + " not marked with @" + Embeddable.class
                    + " but used as an embedded parameter within " + parentClazz;
            logger.error(error);
            throw new RuntimeException(error);
        }

        // append the field name
        if (bindingPath.length() > 0) {
            bindingPath += ".";
        }

        String fieldName = ReflectionUtility.buildFieldName(getterMethod);
        bindingPath += fieldName;

        // recursively build the embedded objects as parameters
        build(embeddableClazz, bindingPath, parentClazz, getterMethod, setterMethod, pbs, recursionFilterList);

        return true;
    }
    return false;
}