Search in sources :

Example 6 with Parameter

use of java.lang.reflect.Parameter in project aws-xray-sdk-java by aws.

the class EntityTest method numberOfMutatingMethodsThatThrewException.

private MutatingMethodCount numberOfMutatingMethodsThatThrewException(Entity entity, Class klass) {
    int numberOfMutatingMethods = 0;
    int numberOfMutatingMethodsThatThrewException = 0;
    for (Method m : klass.getMethods()) {
        if (mutatingMethodPrefixes.stream().anyMatch((prefix) -> {
            return m.getName().startsWith(prefix);
        })) {
            numberOfMutatingMethods++;
            try {
                List<Parameter> parameters = Arrays.asList(m.getParameters());
                List<? extends Object> arguments = parameters.stream().map((parameter) -> {
                    try {
                        Class<?> argumentClass = parameter.getType();
                        if (boolean.class.equals(argumentClass)) {
                            return false;
                        } else if (double.class.equals(argumentClass)) {
                            return 0.0d;
                        } else {
                            return argumentClass.getConstructor().newInstance();
                        }
                    } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
                    }
                    return null;
                }).collect(Collectors.toList());
                m.invoke(entity, arguments.toArray());
            } catch (InvocationTargetException ite) {
                if (ite.getCause() instanceof AlreadyEmittedException) {
                    numberOfMutatingMethodsThatThrewException++;
                }
            } catch (IllegalAccessException e) {
            }
        }
    }
    return new MutatingMethodCount(numberOfMutatingMethods, numberOfMutatingMethodsThatThrewException);
}
Also used : MethodSorters(org.junit.runners.MethodSorters) Arrays(java.util.Arrays) AlreadyEmittedException(com.amazonaws.xray.exceptions.AlreadyEmittedException) Subsegment(com.amazonaws.xray.entities.Subsegment) JSONAssert(org.skyscreamer.jsonassert.JSONAssert) Segment(com.amazonaws.xray.entities.Segment) SegmentImpl(com.amazonaws.xray.entities.SegmentImpl) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JSONException(org.json.JSONException) Parameter(java.lang.reflect.Parameter) Emitter(com.amazonaws.xray.emitters.Emitter) Method(java.lang.reflect.Method) Before(org.junit.Before) SubsegmentImpl(com.amazonaws.xray.entities.SubsegmentImpl) TraceID(com.amazonaws.xray.entities.TraceID) Test(org.junit.Test) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Mockito(org.mockito.Mockito) List(java.util.List) JSONCompareMode(org.skyscreamer.jsonassert.JSONCompareMode) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Entity(com.amazonaws.xray.entities.Entity) Assert(org.junit.Assert) FixMethodOrder(org.junit.FixMethodOrder) Parameter(java.lang.reflect.Parameter) AlreadyEmittedException(com.amazonaws.xray.exceptions.AlreadyEmittedException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 7 with Parameter

use of java.lang.reflect.Parameter in project ART-TIME by Artezio.

the class LogInterceptor method process.

@AroundInvoke
public Object process(InvocationContext invocationContext) throws Exception {
    Method method = invocationContext.getMethod();
    Log annotation = method.getAnnotation(Log.class);
    Level level = Level.parse(annotation.level().name());
    Logger logger = getLogger(invocationContext);
    if (!logger.isLoggable(level)) {
        return invocationContext.proceed();
    }
    Object result;
    Object principal = getPrincipal();
    if (principal == null && annotation.principalsOnly()) {
        return invocationContext.proceed();
    }
    String prefix = MessageFormat.format("({0}) {1}", new Object[] { principal, method.getName() });
    if (!annotation.beforeExecuteMessage().isEmpty()) {
        logger.log(level, MessageFormat.format("{0} - {1}", new Object[] { prefix, annotation.beforeExecuteMessage() }));
    }
    if (annotation.logParams()) {
        Parameter[] metaParams = method.getParameters();
        Object[] parameters = invocationContext.getParameters();
        List<String> paramsAsStr = new ArrayList<>();
        for (int i = 0; i < parameters.length; i++) {
            String paramAsStr = showDetails(metaParams[i]) ? getDetailedString(parameters[i]) : String.valueOf(parameters[i]);
            paramsAsStr.add(paramAsStr);
        }
        logger.log(level, MessageFormat.format("{0}({1})", new Object[] { prefix, String.join(", ", paramsAsStr) }));
    }
    try {
        result = invocationContext.proceed();
    } catch (Exception e) {
        logger.log(Level.SEVERE, MessageFormat.format("Thrown exception {0}: {1}. Details in server stack trace.", e.getClass(), e.getMessage()));
        throw e;
    }
    if (annotation.logResult()) {
        logger.log(level, MessageFormat.format("{0} -  Result is  {1}", new Object[] { prefix, String.valueOf(result) }));
    }
    if (!annotation.afterExecuteMessage().isEmpty()) {
        logger.log(level, MessageFormat.format("{0} - {1}", new Object[] { prefix, annotation.afterExecuteMessage() }));
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) Logger(java.util.logging.Logger) Parameter(java.lang.reflect.Parameter) Level(java.util.logging.Level) AroundInvoke(javax.interceptor.AroundInvoke)

Example 8 with Parameter

use of java.lang.reflect.Parameter in project webpieces by deanhiller.

the class MetaLoader method loadInstIntoMeta.

public void loadInstIntoMeta(RouteMeta meta, Object controllerInst, String methodStr) {
    Method[] methods = controllerInst.getClass().getMethods();
    List<Method> matches = new ArrayList<>();
    for (Method m : methods) {
        if (m.getName().equals(methodStr))
            matches.add(m);
    }
    String controllerStr = controllerInst.getClass().getSimpleName();
    if (matches.size() == 0)
        throw new IllegalArgumentException("Invalid Route.  Cannot find 'public' method='" + methodStr + "' on class=" + controllerStr);
    else if (matches.size() > 1)
        throw new UnsupportedOperationException("You have more than one 'public' method named=" + methodStr + " on class=" + controllerStr + "  This is not yet supported until we support method parameters(let us know you hit this and we will immediately implement)");
    Method controllerMethod = matches.get(0);
    Parameter[] parameters = controllerMethod.getParameters();
    List<String> paramNames = new ArrayList<>();
    for (Parameter p : parameters) {
        String value;
        String name = p.getName();
        if (matchesBadName(name)) {
            Param annotation = p.getAnnotation(Param.class);
            if (annotation == null)
                throw new IllegalArgumentException("Method='" + controllerMethod + "' has to have every argument annotated with @Param(paramName) since\n" + "you are not compiling with -parameters to enable the param names to be built into the *.class files.  Most likely, you " + "changed the build.gradle we generated or switched to a different build system and did not enable this compiler option");
            value = annotation.value();
        } else {
            //use the param name in the method...
            value = name;
        }
        paramNames.add(value);
    }
    if (meta.getRoute().getRouteType() == RouteType.HTML) {
        preconditionCheck(meta, controllerMethod);
    } else if (meta.getRoute().getRouteType() == RouteType.CONTENT) {
        BodyContentBinder binder = contentPreconditionCheck(meta, controllerMethod, parameters);
        meta.setContentBinder(binder);
    }
    meta.setMethodParamNames(paramNames);
    meta.setControllerInstance(controllerInst);
    meta.setMethod(controllerMethod);
}
Also used : BodyContentBinder(org.webpieces.router.api.BodyContentBinder) ArrayList(java.util.ArrayList) Param(org.webpieces.router.api.routing.Param) Parameter(java.lang.reflect.Parameter) Method(java.lang.reflect.Method)

Example 9 with Parameter

use of java.lang.reflect.Parameter in project webpieces by deanhiller.

the class MetaLoader method contentPreconditionCheck.

private BodyContentBinder contentPreconditionCheck(RouteMeta meta, Method controllerMethod, Parameter[] parameters) {
    List<String> binderMatches = new ArrayList<>();
    AtomicReference<BodyContentBinder> lastMatch = new AtomicReference<BodyContentBinder>(null);
    for (BodyContentBinder binder : bodyBinderPlugins) {
        for (Parameter p : parameters) {
            Annotation[] annotations = p.getAnnotations();
            Class<?> entityClass = p.getType();
            recordParameterMatches(lastMatch, binderMatches, binder, annotations, entityClass);
        }
        Annotation[] annotations = controllerMethod.getAnnotations();
        recordParameterMatches(lastMatch, binderMatches, binder, annotations, null);
    }
    Class<?> returnType = controllerMethod.getReturnType();
    if (Action.class.isAssignableFrom(returnType))
        throw new IllegalArgumentException("The method for content route=" + meta.getRoute().getFullPath() + " is returning Action and this is not allowed.  method=" + controllerMethod);
    if (binderMatches.size() == 0)
        throw new IllegalArgumentException("there was not a single method parameter annotated with a Plugin" + " annotation on method=" + controllerMethod + ".  looking at your\n" + "plugins, these are the annotations available=" + allBinderAnnotations + "\n" + "You either need one parameter with one of the annotations OR\n" + "you need to annotata the method(if it is read only and no request is supplied)");
    else if (binderMatches.size() > 1)
        throw new IllegalArgumentException("there is more than one parameter with a Plugin" + " annotation on method=" + controllerMethod + ".  These\n" + "are the ones we found(please delete one)=" + binderMatches + "\n" + "Also make sure one parameter OR the method has the annotation, not both");
    return lastMatch.get();
}
Also used : BodyContentBinder(org.webpieces.router.api.BodyContentBinder) ArrayList(java.util.ArrayList) Parameter(java.lang.reflect.Parameter) AtomicReference(java.util.concurrent.atomic.AtomicReference) Annotation(java.lang.annotation.Annotation)

Example 10 with Parameter

use of java.lang.reflect.Parameter in project webpieces by deanhiller.

the class TestBasicDevStart method testArgSetup.

public static void testArgSetup(String param) throws ClassNotFoundException {
    Class<?> clazz = Class.forName(TestBasicDevStart.class.getName());
    Method[] method = clazz.getDeclaredMethods();
    Method target = null;
    for (Method m : method) {
        if ("testArgSetup".equals(m.getName()))
            target = m;
    }
    Assert.assertNotNull(target);
    Parameter[] parameters = target.getParameters();
    String name = parameters[0].getName();
    Assert.assertEquals("Compiler option is not on so we can't run this test", "param", name);
}
Also used : Parameter(java.lang.reflect.Parameter) Method(java.lang.reflect.Method)

Aggregations

Parameter (java.lang.reflect.Parameter)165 Method (java.lang.reflect.Method)74 ArrayList (java.util.ArrayList)31 Annotation (java.lang.annotation.Annotation)25 Type (java.lang.reflect.Type)21 List (java.util.List)20 Test (org.junit.Test)18 Constructor (java.lang.reflect.Constructor)16 Map (java.util.Map)11 Executable (java.lang.reflect.Executable)10 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 HashMap (java.util.HashMap)9 PathParam (javax.ws.rs.PathParam)9 FormParameter (io.swagger.models.parameters.FormParameter)7 IOException (java.io.IOException)7 Arrays (java.util.Arrays)7 SqlStatementCustomizerFactory (org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizerFactory)7 SqlStatementParameterCustomizer (org.jdbi.v3.sqlobject.customizer.SqlStatementParameterCustomizer)7 RequestPart (org.springframework.web.bind.annotation.RequestPart)7 HashSet (java.util.HashSet)6