Search in sources :

Example 91 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project Payara by payara.

the class WebServiceRefHandler method processAWsRef.

protected HandlerProcessingResult processAWsRef(AnnotationInfo annInfo, WebServiceRef annotation) throws AnnotationProcessorException {
    AnnotatedElementHandler annCtx = annInfo.getProcessingContext().getHandler();
    AnnotatedElement annElem = annInfo.getAnnotatedElement();
    Class annotatedType = null;
    Class declaringClass = null;
    InjectionTarget target = null;
    String defaultServiceRefName = null;
    if (annInfo.getElementType().equals(ElementType.FIELD)) {
        // this is a field injection
        Field annotatedField = (Field) annElem;
        // check this is a valid field
        if (annCtx instanceof AppClientContext) {
            if (!Modifier.isStatic(annotatedField.getModifiers())) {
                throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.injectionfieldnotstatic", "Injection fields for application clients must be declared STATIC"), annInfo);
            }
        }
        annotatedType = annotatedField.getType();
        declaringClass = annotatedField.getDeclaringClass();
        defaultServiceRefName = declaringClass.getName() + "/" + annotatedField.getName();
        target = new InjectionTarget();
        target.setFieldName(annotatedField.getName());
        target.setClassName(annotatedField.getDeclaringClass().getName());
    } else if (annInfo.getElementType().equals(ElementType.METHOD)) {
        // this is a method injection
        Method annotatedMethod = (Method) annElem;
        validateInjectionMethod(annotatedMethod, annInfo);
        if (annCtx instanceof AppClientContext) {
            if (!Modifier.isStatic(annotatedMethod.getModifiers())) {
                throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.injectionmethodnotstatic", "Injection methods for application clients must be declared STATIC"), annInfo);
            }
        }
        annotatedType = annotatedMethod.getParameterTypes()[0];
        declaringClass = annotatedMethod.getDeclaringClass();
        // Derive javabean property name.
        String propertyName = getInjectionMethodPropertyName(annotatedMethod, annInfo);
        // prefixing with fully qualified type name
        defaultServiceRefName = declaringClass.getName() + "/" + propertyName;
        target = new InjectionTarget();
        target.setMethodName(annotatedMethod.getName());
        target.setClassName(annotatedMethod.getDeclaringClass().getName());
    } else if (annInfo.getElementType().equals(ElementType.TYPE)) {
        // name must be specified.
        if (!ok(annotation.name())) {
            throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.nonametypelevel", "TYPE-Level annotation  must specify name member."), annInfo);
        }
        // this is a dependency declaration, we need the service interface
        // to be specified
        annotatedType = annotation.type();
        if (annotatedType == null || annotatedType == Object.class) {
            throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.typenotfound", "TYPE-level annotation symbol must specify type member."), annInfo);
        }
        declaringClass = (Class) annElem;
    } else {
        throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.invalidtype", "annotation not allowed on this element."), annInfo);
    }
    MTOM mtom = null;
    Addressing addressing = null;
    RespectBinding respectBinding = null;
    // Other annotations like SchemaValidation etc to be passed on to
    // ServiceReferenceDescriptor
    Map<Class<? extends Annotation>, Annotation> otherAnnotations = new HashMap<Class<? extends Annotation>, Annotation>();
    for (Annotation a : annElem.getAnnotations()) {
        if (!(a.annotationType().isAnnotationPresent(WebServiceFeatureAnnotation.class)))
            continue;
        if (a instanceof MTOM) {
            mtom = (MTOM) a;
        } else if (a instanceof Addressing) {
            addressing = (Addressing) a;
        } else if (a instanceof RespectBinding) {
            respectBinding = (RespectBinding) a;
        } else {
            if (!otherAnnotations.containsKey(a.getClass())) {
                otherAnnotations.put(a.getClass(), a);
            }
        }
    }
    String serviceRefName = !ok(annotation.name()) ? defaultServiceRefName : annotation.name();
    ServiceReferenceContainer[] containers = null;
    if (annCtx instanceof ServiceReferenceContainerContext) {
        containers = ((ServiceReferenceContainerContext) annCtx).getServiceRefContainers();
    }
    if (containers == null || containers.length == 0) {
        annInfo.getProcessingContext().getErrorHandler().fine(new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.invalidannotationforthisclass", "Illegal annotation symbol for this class will be ignored"), annInfo));
        return HandlerProcessingResultImpl.getDefaultResult(getAnnotationType(), ResultType.PROCESSED);
    }
    // now process the annotation for all the containers.
    for (ServiceReferenceContainer container : containers) {
        ServiceReferenceDescriptor aRef = null;
        try {
            aRef = container.getServiceReferenceByName(serviceRefName);
        }// ignore
         catch (Throwable t) {
        }
        if (aRef == null) {
            // time to create it...
            aRef = new ServiceReferenceDescriptor();
            aRef.setName(serviceRefName);
            container.addServiceReferenceDescriptor(aRef);
        }
        // merge other annotations
        Map<Class<? extends Annotation>, Annotation> oa = aRef.getOtherAnnotations();
        if (oa == null)
            aRef.setOtherAnnotations(otherAnnotations);
        else {
            for (Map.Entry<Class<? extends Annotation>, Annotation> entry : otherAnnotations.entrySet()) {
                if (!oa.containsKey(entry.getKey()))
                    oa.put(entry.getKey(), entry.getValue());
            }
        }
        // merge wsdlLocation
        if (!ok(aRef.getWsdlFileUri()) && ok(annotation.wsdlLocation()))
            aRef.setWsdlFileUri(annotation.wsdlLocation());
        if (!aRef.hasMtomEnabled() && mtom != null) {
            aRef.setMtomEnabled(mtom.enabled());
            aRef.setMtomThreshold(mtom.threshold());
        }
        // check Addressing annotation
        if (aRef.getAddressing() == null && addressing != null) {
            aRef.setAddressing(new com.sun.enterprise.deployment.Addressing(addressing.enabled(), addressing.required(), addressing.responses().toString()));
        }
        // check RespectBinding annotation
        if (aRef.getRespectBinding() == null && respectBinding != null) {
            aRef.setRespectBinding(new com.sun.enterprise.deployment.RespectBinding(respectBinding.enabled()));
        }
        // Store mapped name that is specified
        if (!ok(aRef.getMappedName()) && ok(annotation.mappedName()))
            aRef.setMappedName(annotation.mappedName());
        // Store lookup name that is specified
        if (!aRef.hasLookupName() && ok(getLookupValue(annotation, annInfo)))
            aRef.setLookupName(getLookupValue(annotation, annInfo));
        aRef.setInjectResourceType("javax.jws.WebServiceRef");
        if (target != null)
            aRef.addInjectionTarget(target);
        // Read the WebServiceClient annotation for the service name space
        // uri and wsdl (if required)
        WebServiceClient wsclientAnn;
        // of these default values.
        if (!Object.class.equals(annotation.value()) && (!javax.xml.ws.Service.class.equals(annotation.value()))) {
            // port.
            if (aRef.getServiceInterface() == null) {
                aRef.setServiceInterface(annotation.value().getName());
            }
            if (aRef.getPortInfoBySEI(annotatedType.getName()) == null) {
                ServiceRefPortInfo portInfo = new ServiceRefPortInfo();
                portInfo.setServiceEndpointInterface(annotatedType.getName());
                aRef.addPortInfo(portInfo);
            }
            // set the port type requested for injection
            if (aRef.getInjectionTargetType() == null) {
                aRef.setInjectionTargetType(annotatedType.getName());
            }
            wsclientAnn = (WebServiceClient) annotation.value().getAnnotation(WebServiceClient.class);
        } else {
            // no value provided in the annotation
            wsclientAnn = (WebServiceClient) annotatedType.getAnnotation(WebServiceClient.class);
        }
        if (wsclientAnn == null) {
            throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.classnotannotated", "Class must be annotated with a {1} annotation\n symbol : {1}\n location: {0}", new Object[] { annotatedType.toString(), WebServiceClient.class.toString() }));
        }
        // annotation, get it from WebServiceClient annotation
        if (aRef.getWsdlFileUri() == null) {
            aRef.setWsdlFileUri(wsclientAnn.wsdlLocation());
        }
        // Set service name space URI and service local part
        if (aRef.getServiceName() == null) {
            aRef.setServiceNamespaceUri(wsclientAnn.targetNamespace());
            aRef.setServiceLocalPart(wsclientAnn.name());
        }
        if (aRef.getServiceInterface() == null) {
            aRef.setServiceInterface(annotatedType.getName());
        }
    }
    // have @HandlerChain but the SEI has one specified through JAXWS customization
    if (annElem.getAnnotation(javax.jws.HandlerChain.class) == null) {
        return (new HandlerChainHandler()).processHandlerChainAnnotation(annInfo, annCtx, annotatedType, declaringClass, false);
    }
    return HandlerProcessingResultImpl.getDefaultResult(getAnnotationType(), ResultType.PROCESSED);
}
Also used : HashMap(java.util.HashMap) AnnotatedElement(java.lang.reflect.AnnotatedElement) ServiceReferenceContainer(com.sun.enterprise.deployment.types.ServiceReferenceContainer) Addressing(javax.xml.ws.soap.Addressing) AppClientContext(com.sun.enterprise.deployment.annotation.context.AppClientContext) Field(java.lang.reflect.Field) ServiceReferenceContainerContext(com.sun.enterprise.deployment.annotation.context.ServiceReferenceContainerContext) com.sun.enterprise.deployment(com.sun.enterprise.deployment) MTOM(javax.xml.ws.soap.MTOM) Service(org.jvnet.hk2.annotations.Service) RespectBinding(javax.xml.ws.RespectBinding) Method(java.lang.reflect.Method) WebServiceFeatureAnnotation(javax.xml.ws.spi.WebServiceFeatureAnnotation) Annotation(java.lang.annotation.Annotation) HashMap(java.util.HashMap) Map(java.util.Map)

Example 92 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project acceptance-test-harness by jenkinsci.

the class JenkinsAcceptanceTestRule method apply.

@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
    final Description description = Description.createTestDescription(target.getClass(), method.getName(), method.getAnnotations());
    return new Statement() {

        @Inject
        JenkinsController controller;

        @Inject
        Injector injector;

        @Override
        public void evaluate() throws Throwable {
            World world = World.get();
            Injector injector = world.getInjector();
            world.startTestScope(description.getDisplayName());
            injector.injectMembers(this);
            try {
                decorateWithRules(base).evaluate();
            } catch (AssumptionViolatedException e) {
                System.out.printf("Skipping %s%n", description.getDisplayName());
                e.printStackTrace();
                throw e;
            } finally {
                world.endTestScope();
            }
        }

        /**
         * Detect the outermost exception of given type.
         */
        private Throwable causedBy(Throwable caught, Class<? extends Throwable> type) {
            for (Throwable cur = caught; cur != null; cur = cur.getCause()) {
                if (type.isInstance(cur))
                    return cur;
            }
            return null;
        }

        /**
         * Look for annotations on a test and honor {@link RuleAnnotation}s in them.
         */
        private Statement decorateWithRules(Statement body) {
            TreeMap<Integer, Set<TestRule>> rules = new TreeMap<Integer, Set<TestRule>>(new Comparator<Integer>() {

                @Override
                public int compare(Integer o1, Integer o2) {
                    // Reversed since we apply the TestRule inside out:
                    return Integer.compare(o2, o1);
                }
            });
            collectRuleAnnotations(method, target, rules);
            collectGlobalRules(rules);
            // Make sure Jenkins is started between -1 and 0
            if (rules.get(0) == null) {
                rules.put(0, new LinkedHashSet<TestRule>());
            }
            rules.get(0).add(jenkinsBoot(rules));
            for (Set<TestRule> rulesGroup : rules.values()) {
                for (TestRule rule : rulesGroup) {
                    try {
                        body = rule.apply(body, description);
                    } catch (Exception e) {
                        throw new RuleFailedException(e, rule);
                    }
                }
            }
            return body;
        }

        private void collectGlobalRules(TreeMap<Integer, Set<TestRule>> rules) {
            Iterable<Class> impls;
            try {
                impls = Index.list(GlobalRule.class, getClass().getClassLoader(), Class.class);
            } catch (IOException e) {
                throw new Error("Unable to collect global annotations", e);
            }
            for (Class<?> rule : impls) {
                if (!TestRule.class.isAssignableFrom(rule)) {
                    throw new Error("GlobalRule is applicable for TestRules only");
                }
                addRule(rules, rule.getAnnotation(GlobalRule.class).priority(), (Class<? extends TestRule>) rule);
            }
        }

        private void collectRuleAnnotations(final FrameworkMethod method, final Object target, TreeMap<Integer, Set<TestRule>> rules) {
            Set<Class<? extends Annotation>> annotations = new HashSet<>();
            collectAnnotationTypes(method.getMethod(), annotations);
            collectAnnotationTypes(target.getClass(), annotations);
            for (Class<? extends Annotation> a : annotations) {
                RuleAnnotation r = a.getAnnotation(RuleAnnotation.class);
                if (r != null) {
                    addRule(rules, r.priority(), r.value());
                }
            }
        }

        private void collectAnnotationTypes(AnnotatedElement e, Collection<Class<? extends Annotation>> types) {
            for (Annotation a : e.getAnnotations()) {
                types.add(a.annotationType());
            }
        }

        private void addRule(TreeMap<Integer, Set<TestRule>> rules, int prio, Class<? extends TestRule> impl) {
            if (rules.get(prio) == null) {
                rules.put(prio, new LinkedHashSet<TestRule>());
            }
            rules.get(prio).add(injector.getInstance(impl));
        }

        private TestRule jenkinsBoot(final TreeMap<Integer, Set<TestRule>> rules) {
            return new TestRule() {

                @Override
                public Statement apply(final Statement base, Description description) {
                    return new Statement() {

                        @Override
                        public void evaluate() throws Throwable {
                            controller.start();
                            // Now it is safe to inject Jenkins
                            injector.injectMembers(target);
                            for (Set<TestRule> rg : rules.values()) {
                                for (TestRule rule : rg) {
                                    injector.injectMembers(rule);
                                }
                            }
                            base.evaluate();
                        }
                    };
                }
            };
        }
    };
}
Also used : Description(org.junit.runner.Description) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) AssumptionViolatedException(org.junit.internal.AssumptionViolatedException) AnnotatedElement(java.lang.reflect.AnnotatedElement) World(org.jenkinsci.test.acceptance.guice.World) JenkinsController(org.jenkinsci.test.acceptance.controller.JenkinsController) Injector(com.google.inject.Injector) FrameworkMethod(org.junit.runners.model.FrameworkMethod) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Statement(org.junit.runners.model.Statement) IOException(java.io.IOException) TreeMap(java.util.TreeMap) IOException(java.io.IOException) AssumptionViolatedException(org.junit.internal.AssumptionViolatedException) NoSuchElementException(org.openqa.selenium.NoSuchElementException) Annotation(java.lang.annotation.Annotation) TestRule(org.junit.rules.TestRule) Collection(java.util.Collection)

Example 93 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project hibernate-orm by hibernate.

the class Ejb3XmlTestCase method getReader.

protected JPAOverriddenAnnotationReader getReader(Class<?> entityClass, String fieldName, String ormResourceName) throws Exception {
    AnnotatedElement el = getAnnotatedElement(entityClass, fieldName);
    XMLContext xmlContext = getContext(ormResourceName);
    return new JPAOverriddenAnnotationReader(el, xmlContext, BootstrapContextImpl.INSTANCE);
}
Also used : XMLContext(org.hibernate.cfg.annotations.reflection.XMLContext) AnnotatedElement(java.lang.reflect.AnnotatedElement) JPAOverriddenAnnotationReader(org.hibernate.cfg.annotations.reflection.JPAOverriddenAnnotationReader)

Example 94 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project android_packages_apps_Gallery2 by LineageOS.

the class EntrySchema method parseColumnInfo.

private void parseColumnInfo(Class<? extends Object> clazz, ArrayList<ColumnInfo> columns) {
    // Gather metadata from each annotated field.
    // including non-public fields
    Field[] fields = clazz.getDeclaredFields();
    for (int i = 0; i != fields.length; ++i) {
        // Get column metadata from the annotation.
        Field field = fields[i];
        Entry.Column info = ((AnnotatedElement) field).getAnnotation(Entry.Column.class);
        if (info == null)
            continue;
        // Determine the field type.
        int type;
        Class<?> fieldType = field.getType();
        if (fieldType == String.class) {
            type = TYPE_STRING;
        } else if (fieldType == boolean.class) {
            type = TYPE_BOOLEAN;
        } else if (fieldType == short.class) {
            type = TYPE_SHORT;
        } else if (fieldType == int.class) {
            type = TYPE_INT;
        } else if (fieldType == long.class) {
            type = TYPE_LONG;
        } else if (fieldType == float.class) {
            type = TYPE_FLOAT;
        } else if (fieldType == double.class) {
            type = TYPE_DOUBLE;
        } else if (fieldType == byte[].class) {
            type = TYPE_BLOB;
        } else {
            throw new IllegalArgumentException("Unsupported field type for column: " + fieldType.getName());
        }
        // Add the column to the array.
        int index = columns.size();
        columns.add(new ColumnInfo(info.value(), type, info.indexed(), info.unique(), info.fullText(), info.defaultValue(), field, index));
    }
}
Also used : Field(java.lang.reflect.Field) AnnotatedElement(java.lang.reflect.AnnotatedElement)

Example 95 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project mule by mulesoft.

the class ParameterAllowedStereotypesDeclarionEnricher method getStereotypes.

private List<StereotypeModel> getStereotypes(AnnotatedElement element) {
    ConfigReferences references = element.getAnnotation(ConfigReferences.class);
    if (references != null) {
        return stream(references.value()).map(ref -> newStereotype(ref.name(), ref.namespace()).withParent(CONFIG).build()).collect(toList());
    }
    ConfigReference ref = element.getAnnotation(ConfigReference.class);
    if (ref != null) {
        return singletonList(newStereotype(ref.name(), ref.namespace()).withParent(CONFIG).build());
    }
    if (element.getAnnotation(FlowReference.class) != null) {
        return singletonList(FLOW);
    }
    if (element.getAnnotation(ObjectStoreReference.class) != null) {
        return singletonList(OBJECT_STORE);
    }
    return emptyList();
}
Also used : ConfigReferences(org.mule.runtime.extension.api.annotation.ConfigReferences) OBJECT_STORE(org.mule.runtime.extension.api.stereotype.MuleStereotypes.OBJECT_STORE) ParameterDeclaration(org.mule.runtime.api.meta.model.declaration.fluent.ParameterDeclaration) StereotypeModel(org.mule.runtime.api.meta.model.stereotype.StereotypeModel) Collections.emptyList(java.util.Collections.emptyList) ExtensionLoadingContext(org.mule.runtime.extension.api.loader.ExtensionLoadingContext) FlowReference(org.mule.runtime.extension.api.annotation.param.reference.FlowReference) ImplementingParameterModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.ImplementingParameterModelProperty) Collections.singletonList(java.util.Collections.singletonList) DeclaringMemberModelProperty(org.mule.runtime.module.extension.internal.loader.java.property.DeclaringMemberModelProperty) CONFIG(org.mule.runtime.extension.api.stereotype.MuleStereotypes.CONFIG) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) StereotypeModelBuilder.newStereotype(org.mule.runtime.api.meta.model.stereotype.StereotypeModelBuilder.newStereotype) ConfigReference(org.mule.runtime.extension.api.annotation.param.reference.ConfigReference) ObjectStoreReference(org.mule.runtime.extension.api.annotation.param.reference.ObjectStoreReference) ParameterGroupDeclaration(org.mule.runtime.api.meta.model.declaration.fluent.ParameterGroupDeclaration) Arrays.stream(java.util.Arrays.stream) FLOW(org.mule.runtime.extension.api.stereotype.MuleStereotypes.FLOW) IdempotentDeclarationWalker(org.mule.runtime.extension.api.declaration.fluent.util.IdempotentDeclarationWalker) AnnotatedElement(java.lang.reflect.AnnotatedElement) ObjectStoreReference(org.mule.runtime.extension.api.annotation.param.reference.ObjectStoreReference) ConfigReferences(org.mule.runtime.extension.api.annotation.ConfigReferences) ConfigReference(org.mule.runtime.extension.api.annotation.param.reference.ConfigReference) FlowReference(org.mule.runtime.extension.api.annotation.param.reference.FlowReference)

Aggregations

AnnotatedElement (java.lang.reflect.AnnotatedElement)106 Method (java.lang.reflect.Method)23 Annotation (java.lang.annotation.Annotation)17 Field (java.lang.reflect.Field)17 ArrayList (java.util.ArrayList)12 Test (org.junit.Test)11 HashMap (java.util.HashMap)9 Test (org.junit.jupiter.api.Test)8 Member (java.lang.reflect.Member)7 LinkedHashSet (java.util.LinkedHashSet)7 List (java.util.List)7 Constructor (java.lang.reflect.Constructor)6 Type (java.lang.reflect.Type)6 Map (java.util.Map)6 HashSet (java.util.HashSet)5 By (org.openqa.selenium.By)5 Statement (org.junit.runners.model.Statement)4 FindBy (org.openqa.selenium.support.FindBy)4 EntityType (com.querydsl.codegen.EntityType)3 Collection (java.util.Collection)3