Example #1
0
  /**
   * @param to
   * @param name
   * @return <code>true</code> if the name is equal to the fromName, or if the name represents a
   *     superclass or superinterface of the fromName, <code>false</code> otherwise
   */
  private boolean isAssignableTo(DotName name, Class<?> to) {
    if (to.getName().equals(name.toString())) {
      return true;
    }
    if (OBJECT_NAME.equals(name)) {
      return false; // there's nothing assignable from Object.class except for Object.class
    }

    ClassInfo fromClassInfo = index.getClassByName(name);
    if (fromClassInfo == null) {
      // We reached a class that is not in the index. Let's use reflection.
      final Class<?> clazz = loadClass(name.toString());
      return to.isAssignableFrom(clazz);
    }

    DotName superName = fromClassInfo.superName();

    if (superName != null && isAssignableTo(superName, to)) {
      return true;
    }

    if (fromClassInfo.interfaces() != null) {
      for (DotName interfaceName : fromClassInfo.interfaces()) {
        if (isAssignableTo(interfaceName, to)) {
          return true;
        }
      }
    }
    return false;
  }
Example #2
0
 private String getPackageName(DotName name) {
   if (name.isComponentized()) {
     return name.prefix().toString();
   } else {
     return name.local().substring(0, name.local().lastIndexOf("."));
   }
 }
  /**
   * Check the deployment annotation index for all classes with the @PersistenceContext annotation.
   * For each class with the annotation, collect all the required information to create a managed
   * bean instance, and attach it to the context.
   *
   * @param phaseContext the deployment unit context
   * @throws org.jboss.as.server.deployment.DeploymentUnitProcessingException
   */
  protected void processComponentConfig(
      final DeploymentUnit deploymentUnit,
      final DeploymentPhaseContext phaseContext,
      final CompositeIndex compositeIndex,
      final AbstractComponentDescription componentDescription)
      throws DeploymentUnitProcessingException {

    final ClassInfo classInfo =
        compositeIndex.getClassByName(
            DotName.createSimple(componentDescription.getComponentClassName()));
    if (classInfo == null) {
      return; // We can't continue without the annotation index info.
    }
    componentDescription
        .getBindings()
        .addAll(getConfigurations(deploymentUnit, classInfo, componentDescription, phaseContext));
    final Collection<InterceptorDescription> interceptorConfigurations =
        componentDescription.getAllInterceptors().values();
    for (InterceptorDescription interceptorConfiguration : interceptorConfigurations) {
      final ClassInfo interceptorClassInfo =
          compositeIndex.getClassByName(
              DotName.createSimple(interceptorConfiguration.getInterceptorClassName()));
      if (interceptorClassInfo == null) {
        continue;
      }
      interceptorConfiguration
          .getBindings()
          .addAll(
              getConfigurations(
                  deploymentUnit, interceptorClassInfo, componentDescription, phaseContext));
    }
  }
  private String getMessageListenerInterface(
      final CompositeIndex compositeIndex, final AnnotationInstance messageBeanAnnotation)
      throws DeploymentUnitProcessingException {
    final AnnotationValue value = messageBeanAnnotation.value("messageListenerInterface");
    if (value != null) return value.asClass().name().toString();
    final ClassInfo beanClass = (ClassInfo) messageBeanAnnotation.target();
    final Set<DotName> interfaces = new HashSet<DotName>(getPotentialViewInterfaces(beanClass));
    // check super class(es) of the bean
    DotName superClassDotName = beanClass.superName();
    while (interfaces.isEmpty()
        && superClassDotName != null
        && !superClassDotName.toString().equals(Object.class.getName())) {
      final ClassInfo superClass = compositeIndex.getClassByName(superClassDotName);
      if (superClass == null) {
        break;
      }
      interfaces.addAll(getPotentialViewInterfaces(superClass));
      // move to next super class
      superClassDotName = superClass.superName();
    }

    if (interfaces.size() != 1)
      throw MESSAGES.mdbDoesNotImplementNorSpecifyMessageListener(beanClass);
    return interfaces.iterator().next().toString();
  }
  private BindingDescription processMethod(
      final DeploymentUnit deploymentUnit,
      final AnnotationInstance annotation,
      final MethodInfo methodInfo,
      final AbstractComponentDescription componentDescription,
      final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {

    final String methodName = methodInfo.name();
    if (!methodName.startsWith("set") || methodInfo.args().length != 1) {
      throw new IllegalArgumentException(
          "injection target is invalid.  Only setter methods are allowed: " + methodInfo);
    }

    final String contextNameSuffix =
        methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
    final AnnotationValue declaredNameValue = annotation.value("name");
    final String declaredName = declaredNameValue != null ? declaredNameValue.asString() : null;
    final String localContextName;
    if (declaredName == null || declaredName.isEmpty()) {
      localContextName = methodInfo.declaringClass().name().toString() + "/" + contextNameSuffix;
    } else {
      localContextName = declaredName;
    }

    final DotName declaredType = methodInfo.returnType().name();
    final DotName injectionType =
        declaredType == null || declaredType.toString().equals(Object.class.getName())
            ? methodInfo.returnType().name()
            : declaredType;
    final BindingDescription bindingDescription = new BindingDescription();
    bindingDescription.setDependency(true);
    bindingDescription.setBindingName(localContextName);
    final String injectionTypeName = injectionType.toString();
    bindingDescription.setBindingType(injectionTypeName);

    ServiceName injectorName =
        getInjectorServiceName(
            deploymentUnit,
            annotation,
            componentDescription,
            phaseContext,
            methodName,
            injectionTypeName);

    bindingDescription.setReferenceSourceDescription(
        new ServiceBindingSourceDescription(injectorName));

    // setup the injection target
    final InjectionTargetDescription targetDescription = new InjectionTargetDescription();
    targetDescription.setName(methodName);
    targetDescription.setClassName(methodInfo.declaringClass().name().toString());
    targetDescription.setType(InjectionTargetDescription.Type.METHOD);
    targetDescription.setValueClassName(injectionTypeName);
    bindingDescription.getInjectionTargetDescriptions().add(targetDescription);
    return bindingDescription;
  }
Example #6
0
 @Test
 public void testEntityMetadataComplete() {
   Index index = getMockedIndex("entity-metadata-complete.xml");
   DotName authorName = DotName.createSimple(Author.class.getName());
   ClassInfo authorClassInfo = index.getClassByName(authorName);
   assertHasAnnotation(index, authorName, JPADotNames.ENTITY);
   assertHasAnnotation(index, authorName, JPADotNames.ID_CLASS);
   assertEquals(2, authorClassInfo.annotations().size());
   DotName bookName = DotName.createSimple(Book.class.getName());
   assertHasAnnotation(index, bookName, JPADotNames.ENTITY);
 }
Example #7
0
 @Test
 public void testOverrideToMappedSuperClass() {
   Index index = getMockedIndex("override-to-mappedsuperclass.xml");
   index.printAnnotations();
   DotName authorName = DotName.createSimple(Author.class.getName());
   assertHasAnnotation(index, authorName, JPADotNames.ENTITY);
   assertHasNoAnnotation(index, authorName, JPADotNames.TABLE);
   DotName bookName = DotName.createSimple(Book.class.getName());
   assertHasAnnotation(index, bookName, JPADotNames.MAPPED_SUPERCLASS);
   assertHasNoAnnotation(index, bookName, JPADotNames.TABLE);
 }
Example #8
0
 private static ClassInfo getModuleInfo(final Index index, final String moduleName) {
   // we need to escape any java keyword from the package list
   String quotedModuleName = JVMModuleUtil.quoteJavaKeywords(moduleName);
   DotName moduleClassName = DotName.createSimple(quotedModuleName + ".$module_");
   ClassInfo ret = index.getClassByName(moduleClassName);
   if (ret == null) {
     // read previous module descriptor name
     moduleClassName = DotName.createSimple(quotedModuleName + ".module_");
     ret = index.getClassByName(moduleClassName);
   }
   return ret;
 }
  private BindingDescription processField(
      final DeploymentUnit deploymentUnit,
      final AnnotationInstance annotation,
      final FieldInfo fieldInfo,
      final AbstractComponentDescription componentDescription,
      final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {

    final String fieldName = fieldInfo.name();
    final AnnotationValue declaredNameValue = annotation.value("name");
    final String declaredName = declaredNameValue != null ? declaredNameValue.asString() : null;
    final String localContextName;
    if (declaredName == null || declaredName.isEmpty()) {
      localContextName = "java:comp/env/persistence" + "/" + fieldName;
    } else {
      localContextName = declaredName;
    }

    // final AnnotationValue declaredTypeValue = annotation.value("type");
    final DotName declaredType = fieldInfo.type().name();
    final DotName injectionType =
        declaredType == null || declaredType.toString().equals(Object.class.getName())
            ? fieldInfo.type().name()
            : declaredType;

    BindingDescription bindingDescription = new BindingDescription();
    bindingDescription.setDependency(true);
    bindingDescription.setBindingName(localContextName);
    final String injectionTypeName = injectionType.toString();
    bindingDescription.setBindingType(injectionTypeName);

    ServiceName injectorName =
        getInjectorServiceName(
            deploymentUnit,
            annotation,
            componentDescription,
            phaseContext,
            fieldName,
            injectionTypeName);
    bindingDescription.setReferenceSourceDescription(
        new ServiceBindingSourceDescription(injectorName));

    // setup the injection target
    final InjectionTargetDescription targetDescription = new InjectionTargetDescription();
    targetDescription.setName(fieldName);
    targetDescription.setClassName(fieldInfo.declaringClass().name().toString());
    targetDescription.setType(InjectionTargetDescription.Type.FIELD);
    targetDescription.setValueClassName(injectionTypeName);
    bindingDescription.getInjectionTargetDescriptions().add(targetDescription);

    return bindingDescription;
  }
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

    final Map<Class<? extends Annotation>, Set<Class<?>>> instances =
        new HashMap<Class<? extends Annotation>, Set<Class<?>>>();

    final CompositeIndex compositeIndex =
        deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
    if (compositeIndex == null) {
      return; // Can not continue without index
    }

    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
      return; // Can not continue without module
    }
    final ClassLoader classLoader = module.getClassLoader();

    for (FacesAnnotation annotation : FacesAnnotation.values()) {
      final List<AnnotationInstance> annotationInstances =
          compositeIndex.getAnnotations(annotation.indexName);
      if (annotationInstances == null || annotationInstances.isEmpty()) {
        continue;
      }
      final Set<Class<?>> discoveredClasses = new HashSet<Class<?>>();
      instances.put(annotation.annotationClass, discoveredClasses);
      for (AnnotationInstance annotationInstance : annotationInstances) {
        final AnnotationTarget target = annotationInstance.target();
        if (target instanceof ClassInfo) {
          final DotName className = ClassInfo.class.cast(target).name();
          final Class<?> annotatedClass;
          try {
            annotatedClass = classLoader.loadClass(className.toString());
          } catch (ClassNotFoundException e) {
            throw new DeploymentUnitProcessingException(
                JSFMessages.MESSAGES.classLoadingFailed(className));
          }
          discoveredClasses.add(annotatedClass);
        } else {
          throw new DeploymentUnitProcessingException(
              JSFMessages.MESSAGES.invalidAnnotationLocation(annotation, target));
        }
      }
    }
    deploymentUnit.addToAttachmentList(
        ServletContextAttribute.ATTACHMENT_KEY,
        new ServletContextAttribute(FACES_ANNOTATIONS_SC_ATTR, instances));
  }
  @Test
  public void testDefaultCascadePersist() {
    Default defaults = new Default();
    defaults.setCascadePersist(true);
    Index index = getIndex();
    Map<DotName, List<AnnotationInstance>> annotations =
        new HashMap<DotName, List<AnnotationInstance>>();
    annotations.putAll(
        index.getClassByName(DotName.createSimple(Parent.class.getName())).annotations());
    assertEquals(4, annotations.size());
    assertEquals(1, annotations.get(JPADotNames.ENTITY).size());
    assertEquals(1, annotations.get(JPADotNames.ID).size());
    assertEquals(1, annotations.get(JPADotNames.ONE_TO_MANY).size());
    assertEquals(1, annotations.get(JPADotNames.MANY_TO_ONE).size());

    DefaultConfigurationHelper.INSTANCE.applyDefaults(annotations, defaults);

    assertEquals(4, annotations.size());
    assertEquals(1, annotations.get(JPADotNames.ENTITY).size());
    assertEquals(1, annotations.get(JPADotNames.ID).size());
    assertEquals(1, annotations.get(JPADotNames.ONE_TO_MANY).size());
    assertEquals(1, annotations.get(JPADotNames.MANY_TO_ONE).size());
    AnnotationInstance oneToMany = annotations.get(JPADotNames.ONE_TO_MANY).get(0);
    String[] cascadeTypes = oneToMany.value("cascade").asEnumArray();
    assertArrayEquals(new String[] {"ALL", "DETACH", "PERSIST"}, cascadeTypes);
    AnnotationInstance manyToOne = annotations.get(JPADotNames.MANY_TO_ONE).get(0);
    cascadeTypes = manyToOne.value("cascade").asEnumArray();
    assertArrayEquals(new String[] {"PERSIST"}, cascadeTypes);

    annotations.clear();
    annotations.putAll(
        index.getClassByName(DotName.createSimple(Child.class.getName())).annotations());
    assertEquals(3, annotations.size());
    assertEquals(1, annotations.get(JPADotNames.ENTITY).size());
    assertEquals(1, annotations.get(JPADotNames.ID).size());
    assertEquals(1, annotations.get(JPADotNames.MANY_TO_ONE).size());

    DefaultConfigurationHelper.INSTANCE.applyDefaults(annotations, defaults);

    assertEquals(3, annotations.size());
    assertEquals(1, annotations.get(JPADotNames.ENTITY).size());
    assertEquals(1, annotations.get(JPADotNames.ID).size());
    assertEquals(1, annotations.get(JPADotNames.MANY_TO_ONE).size());

    manyToOne = annotations.get(JPADotNames.MANY_TO_ONE).get(0);
    cascadeTypes = manyToOne.value("cascade").asEnumArray();
    assertArrayEquals(new String[] {"PERSIST", "ALL", "DETACH"}, cascadeTypes);
  }
 private DotName toJandexName(Name typeName) {
   if (DotNameAdapter.class.isInstance(typeName)) {
     return ((DotNameAdapter) typeName).jandexName();
   } else {
     return DotName.createSimple(typeName.fullName());
   }
 }
Example #13
0
  /**
   * Entity has a @AttributeOverride on property topic and this property also has a
   * <attribute-override> in orm.xml but with different name by jpa override rules, this two
   * attribute-override should be merged into one @AttributeOverrides
   */
  @Test
  public void testAttributeOverride() {
    Index index = getMockedIndex("AttributeOverride.xml");
    DotName className = DotName.createSimple(Book.class.getName());
    index.printAnnotations();
    assertHasNoAnnotation(index, className, JPADotNames.ATTRIBUTE_OVERRIDE);
    assertAnnotationValue(
        index,
        className,
        JPADotNames.ATTRIBUTE_OVERRIDES,
        new AnnotationValueChecker() {
          @Override
          public void check(AnnotationInstance annotationInstance) {
            AnnotationValue value = annotationInstance.value();
            assertNotNull(value);
            AnnotationInstance[] annotationInstances = value.asNestedArray();
            assertEquals(2, annotationInstances.length);
            AnnotationInstance ai = annotationInstances[0];
            String name = ai.value("name").asString();
            AnnotationValue columnValue = ai.value("column").asNested().value("name");
            if (name.equals("title")) {
              assertEquals("TOC_TITLE", columnValue.asString());

            } else if (name.equals("summary")) {
              assertEquals("TOPIC_SUMMARY", columnValue.asString());
            } else {
              fail(
                  "AttributeOverride's name is "
                      + name
                      + ", should be either 'title' or 'summary'");
            }
          }
        });
  }
  @Test
  public void testDefaultSchemaToAnnotationInstance() {
    Default defaults = new Default();
    defaults.setSchema("hib_schema");
    defaults.setCatalog("hib_catalog");
    Index index = getIndex();
    Map<DotName, List<AnnotationInstance>> annotations =
        new HashMap<DotName, List<AnnotationInstance>>();
    annotations.putAll(
        index.getClassByName(DotName.createSimple(Parent.class.getName())).annotations());
    assertEquals(4, annotations.size());
    assertEquals(1, annotations.get(JPADotNames.ENTITY).size());
    assertEquals(1, annotations.get(JPADotNames.ID).size());
    assertEquals(1, annotations.get(JPADotNames.ONE_TO_MANY).size());
    assertEquals(1, annotations.get(JPADotNames.MANY_TO_ONE).size());
    DefaultConfigurationHelper.INSTANCE.applyDefaults(annotations, defaults);
    assertEquals(5, annotations.size());
    assertEquals(1, annotations.get(JPADotNames.ENTITY).size());
    assertEquals(1, annotations.get(JPADotNames.ID).size());
    assertEquals(1, annotations.get(JPADotNames.ONE_TO_MANY).size());
    assertEquals(1, annotations.get(JPADotNames.MANY_TO_ONE).size());
    assertEquals(1, annotations.get(JPADotNames.TABLE).size());
    AnnotationInstance table = annotations.get(JPADotNames.TABLE).get(0);
    assertEquals("hib_schema", table.value("schema").asString());
    assertEquals("hib_catalog", table.value("catalog").asString());

    annotations.clear();
    annotations.putAll(
        index.getClassByName(DotName.createSimple(Name.class.getName())).annotations());
    DefaultConfigurationHelper.INSTANCE.applyDefaults(annotations, defaults);
    assertEquals(1, annotations.size());
    assertEquals(1, annotations.get(JPADotNames.SECONDARY_TABLES).size());
    AnnotationInstance[] secondaryTables =
        annotations.get(JPADotNames.SECONDARY_TABLES).get(0).value().asNestedArray();
    assertEquals(2, secondaryTables.length);
    AnnotationInstance secondaryTable = secondaryTables[0];
    String name = secondaryTable.value("name").asString();
    if (name.equals("sec1")) {
      assertSt1(secondaryTable);
      assertSt2(secondaryTables[1]);
    } else {
      assertSt1(secondaryTables[1]);
      assertSt2(secondaryTable);
    }
  }
  private void processField(
      final DeploymentUnit deploymentUnit,
      final AnnotationInstance annotation,
      final FieldInfo fieldInfo,
      final EEModuleClassDescription eeModuleClassDescription)
      throws DeploymentUnitProcessingException {

    final String fieldName = fieldInfo.name();
    final AnnotationValue declaredNameValue = annotation.value("name");
    final String declaredName = declaredNameValue != null ? declaredNameValue.asString() : null;
    final String localContextName;
    if (declaredName == null || declaredName.isEmpty()) {
      localContextName = fieldInfo.declaringClass().name().toString() + "/" + fieldName;
    } else {
      localContextName = declaredName;
    }

    // final AnnotationValue declaredTypeValue = annotation.value("type");
    final DotName declaredTypeDotName = fieldInfo.type().name();
    final DotName injectionTypeDotName =
        declaredTypeDotName == null || declaredTypeDotName.toString().equals(Object.class.getName())
            ? fieldInfo.type().name()
            : declaredTypeDotName;

    final String injectionType = injectionTypeDotName.toString();
    final InjectionSource bindingSource =
        this.getBindingSource(deploymentUnit, annotation, injectionType, eeModuleClassDescription);
    if (bindingSource != null) {
      final BindingConfiguration bindingConfiguration =
          new BindingConfiguration(localContextName, bindingSource);
      eeModuleClassDescription.getBindingConfigurations().add(bindingConfiguration);

      // setup the injection target
      final InjectionTarget injectionTarget =
          new FieldInjectionTarget(
              fieldInfo.declaringClass().name().toString(),
              fieldName,
              fieldInfo.type().name().toString());
      // source is always local ENC jndi
      final InjectionSource injectionSource = new LookupInjectionSource(localContextName);
      final ResourceInjectionConfiguration injectionConfiguration =
          new ResourceInjectionConfiguration(injectionTarget, injectionSource);
      eeModuleClassDescription.addResourceInjection(injectionConfiguration);
    }
  }
  @Test
  public void testSingleEntity() {
    Index index =
        JandexHelper.indexForClass(
            service, Paper.class, Stuff.class, Item.class, PricedStuff.class);
    Set<ConfiguredClassHierarchy> hierarchies =
        ConfiguredClassHierarchyBuilder.createEntityHierarchies(index, serviceRegistry);
    assertEquals("There should be only one hierarchy", 1, hierarchies.size());

    Iterator<ConfiguredClass> iter = hierarchies.iterator().next().iterator();
    ConfiguredClass configuredClass = iter.next();
    ClassInfo info = configuredClass.getClassInfo();
    assertEquals("wrong class", DotName.createSimple(Stuff.class.getName()), info.name());
    MappedAttribute property = configuredClass.getMappedProperty("value");
    assertEquals(Price.class, property.getType());

    assertTrue(iter.hasNext());
    configuredClass = iter.next();
    info = configuredClass.getClassInfo();
    assertEquals("wrong class", DotName.createSimple(PricedStuff.class.getName()), info.name());
    assertFalse(
        "PricedStuff should not mapped properties",
        configuredClass.getMappedAttributes().iterator().hasNext());

    assertTrue(iter.hasNext());
    configuredClass = iter.next();
    info = configuredClass.getClassInfo();
    assertEquals("wrong class", DotName.createSimple(Item.class.getName()), info.name());
    // properties are alphabetically ordered!
    property = configuredClass.getMappedProperty("owner");
    assertEquals(SomeGuy.class, property.getType());
    property = configuredClass.getMappedProperty("type");
    assertEquals(PaperType.class, property.getType());

    assertTrue(iter.hasNext());
    configuredClass = iter.next();
    info = configuredClass.getClassInfo();
    assertEquals("wrong class", DotName.createSimple(Paper.class.getName()), info.name());
    assertFalse(
        "Paper should not mapped properties",
        configuredClass.getMappedAttributes().iterator().hasNext());

    assertFalse(iter.hasNext());
  }
Example #17
0
 @Test
 public void testPersistenceUnitDefaultsCascadePersistInXML() {
   Index index = getMockedIndex("AttributeOverride.xml");
   DotName className = DotName.createSimple(Author.class.getName());
   assertAnnotationValue(
       index,
       className,
       JPADotNames.ONE_TO_MANY,
       new CascadeAnnotationValueChecker(new String[] {"PERSIST", "ALL"}));
 }
 ClassInfo createClassInfo(String className) {
   if (StringHelper.isEmpty(className)) {
     throw new AssertionFailure("Class Name used to create ClassInfo is empty.");
   }
   DotName classDotName = DotName.createSimple(className);
   if (classes.containsKey(classDotName)) {
     // classInfoAnnotationsMap.put( classDotName, new HashMap<DotName,
     // List<AnnotationInstance>>(classes.get( classDotName ).annotations()) );
     return classes.get(classDotName);
   }
   Class clazz = serviceRegistry.getService(ClassLoaderService.class).classForName(className);
   DotName superName = null;
   DotName[] interfaces = null;
   short access_flag;
   ClassInfo annClassInfo = index.getClassByName(classDotName);
   if (annClassInfo != null) {
     superName = annClassInfo.superName();
     interfaces = annClassInfo.interfaces();
     access_flag = annClassInfo.flags();
   } else {
     Class superClass = clazz.getSuperclass();
     if (superClass != null) {
       superName = DotName.createSimple(superClass.getName());
     }
     Class[] classInterfaces = clazz.getInterfaces();
     if (classInterfaces != null && classInterfaces.length > 0) {
       interfaces = new DotName[classInterfaces.length];
       for (int i = 0; i < classInterfaces.length; i++) {
         interfaces[i] = DotName.createSimple(classInterfaces[i].getName());
       }
     }
     access_flag = (short) (clazz.getModifiers() | 0x20); // (modifiers | ACC_SUPER)
   }
   Map<DotName, List<AnnotationInstance>> map = new HashMap<DotName, List<AnnotationInstance>>();
   classInfoAnnotationsMap.put(classDotName, map);
   ClassInfo classInfo = ClassInfo.create(classDotName, superName, access_flag, interfaces, map);
   classes.put(classDotName, classInfo);
   addSubClasses(superName, classInfo);
   addImplementors(interfaces, classInfo);
   return classInfo;
 }
  @Test
  public void testTablePerClassDefaultTableName() {
    @Entity
    @Inheritance(strategy = javax.persistence.InheritanceType.TABLE_PER_CLASS)
    class A {
      @Id @GeneratedValue private int id;
    }

    @Entity
    class B extends A {}

    Index index = JandexHelper.indexForClass(service, A.class, B.class);
    AnnotationBindingContext context = new AnnotationBindingContext(index, serviceRegistry);
    Set<ConfiguredClassHierarchy<EntityClass>> hierarchies =
        ConfiguredClassHierarchyBuilder.createEntityHierarchies(context);
    assertEquals("There should be only one hierarchy", 1, hierarchies.size());

    Iterator<EntityClass> iter = hierarchies.iterator().next().iterator();
    EntityClass entityClass = iter.next();
    ClassInfo info = entityClass.getClassInfo();
    assertEquals("wrong class", DotName.createSimple(A.class.getName()), info.name());
    assertTrue(entityClass.hasOwnTable());
    Assert.assertEquals(
        "wrong inheritance type",
        InheritanceType.TABLE_PER_CLASS,
        entityClass.getInheritanceType());
    Assert.assertEquals("wrong table name", "A", entityClass.getPrimaryTableName());

    assertTrue(iter.hasNext());
    entityClass = iter.next();
    info = entityClass.getClassInfo();
    assertEquals("wrong class", DotName.createSimple(B.class.getName()), info.name());
    assertTrue(entityClass.hasOwnTable());
    Assert.assertEquals(
        "wrong inheritance type",
        InheritanceType.TABLE_PER_CLASS,
        entityClass.getInheritanceType());
    Assert.assertEquals("wrong table name", "B", entityClass.getPrimaryTableName());

    assertFalse(iter.hasNext());
  }
 /**
  * Returns the annotation with the specified name or {@code null}
  *
  * @param annotationDotName The annotation to retrieve/check
  * @return Returns the annotation with the specified name or {@code null}. Note, since these are
  *     the annotations defined on a single attribute there can never be more than one.
  */
 public final AnnotationInstance getIfExists(DotName annotationDotName) {
   if (annotations.containsKey(annotationDotName)) {
     List<AnnotationInstance> instanceList = annotations.get(annotationDotName);
     if (instanceList.size() > 1) {
       throw new AssertionFailure(
           "There cannot be more than one @"
               + annotationDotName.toString()
               + " annotation per mapped attribute");
     }
     return instanceList.get(0);
   } else {
     return null;
   }
 }
Example #21
0
  private boolean containsAnnotation(
      ClassInfo classInfo,
      DotName requiredAnnotationName,
      Class<? extends Annotation> requiredAnnotation) {
    // Type and members
    if (classInfo.annotations().containsKey(requiredAnnotationName)) {
      return true;
    }
    // Meta-annotations
    for (DotName annotation : classInfo.annotations().keySet()) {
      try {
        if (annotationClassAnnotationsCache
            .get(annotation)
            .contains(requiredAnnotationName.toString())) {
          return true;
        }
      } catch (ExecutionException e) {
        throw new RuntimeException(e);
      }
    }
    // Superclass
    final DotName superName = classInfo.superName();

    if (superName != null && !OBJECT_NAME.equals(superName)) {
      final ClassInfo superClassInfo = index.getClassByName(superName);
      if (superClassInfo == null) {
        // we are accessing a class that is outside of the jandex index
        // fallback to using reflection
        return SEReflections.containsAnnotation(
            loadClass(superName.toString()), requiredAnnotation);
      }
      if (containsAnnotation(superClassInfo, requiredAnnotationName, requiredAnnotation)) {
        return true;
      }
    }
    return false;
  }
Example #22
0
 public WeldSEClassFileInfo(
     String className,
     IndexView index,
     LoadingCache<DotName, Set<String>> annotationClassAnnotationsCache,
     ClassLoader classLoader) {
   this.index = index;
   this.annotationClassAnnotationsCache = annotationClassAnnotationsCache;
   this.classInfo = index.getClassByName(DotName.createSimple(className));
   if (this.classInfo == null) {
     throw new IllegalStateException("Index for name: " + className + " not found");
   }
   this.isVetoed = isVetoedTypeOrPackage();
   this.hasCdiConstructor = this.classInfo.hasNoArgsConstructor() || hasInjectConstructor();
   this.classLoader = classLoader;
 }
Example #23
0
  private boolean isVetoedTypeOrPackage() {

    if (isAnnotationDeclared(classInfo, DOT_NAME_VETOED)) {
      return true;
    }

    ClassInfo packageInfo =
        index.getClassByName(
            DotName.createSimple(
                getPackageName(classInfo.name()) + DOT_SEPARATOR + PACKAGE_INFO_NAME));

    if (packageInfo != null && isAnnotationDeclared(packageInfo, DOT_NAME_VETOED)) {
      return true;
    }
    return false;
  }
Example #24
0
 @Test
 public void testPersistenceUnitMetadataMetadataComplete() {
   JaxbEntity author = new JaxbEntity();
   author.setClazz(Author.class.getName());
   IndexBuilder indexBuilder = getIndexBuilder();
   EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
   defaults.setMetadataComplete(true);
   EntityMocker entityMocker = new EntityMocker(indexBuilder, author, defaults);
   entityMocker.preProcess();
   entityMocker.process();
   Index index = indexBuilder.build(new EntityMappingsMocker.Default());
   DotName className = DotName.createSimple(Author.class.getName());
   ClassInfo classInfo = index.getClassByName(className);
   assertEquals(1, classInfo.annotations().size());
   assertHasAnnotation(index, className, JPADotNames.ENTITY);
 }
Example #25
0
  private static boolean isWebserviceEndpoint(
      final ServletMetaData servletMD, final List<Index> annotationIndexes) {
    final String endpointClassName = ASHelper.getEndpointName(servletMD);
    if (isJSP(endpointClassName)) return false;

    final DotName endpointDN = DotName.createSimple(endpointClassName);
    ClassInfo endpointClassInfo = null;
    for (final Index index : annotationIndexes) {
      endpointClassInfo = index.getClassByName(endpointDN);
      if (endpointClassInfo != null) {
        if (endpointClassInfo.annotations().containsKey(WEB_SERVICE_ANNOTATION)) return true;
        if (endpointClassInfo.annotations().containsKey(WEB_SERVICE_PROVIDER_ANNOTATION))
          return true;
      }
    }

    return false;
  }
 private SessionType determineSessionType(
     final String ejbClass, final CompositeIndex compositeIndex) {
   if (ejbClass == null) {
     return null;
   }
   final ClassInfo info = compositeIndex.getClassByName(DotName.createSimple(ejbClass));
   if (info == null) {
     return null;
   }
   if (info.annotations().get(STATEFUL_ANNOTATION) != null) {
     return SessionType.Stateful;
   } else if (info.annotations().get(STATELESS_ANNOTATION) != null) {
     return SessionType.Stateless;
   } else if (info.annotations().get(SINGLETON_ANNOTATION) != null) {
     return SessionType.Singleton;
   }
   return null;
 }
Example #27
0
 @Test
 public void testPersistenceUnitDefaultsCascadePersistInAnnotation() {
   JaxbEntity author = new JaxbEntity();
   author.setClazz(Author.class.getName());
   IndexBuilder indexBuilder = getIndexBuilder();
   EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
   defaults.setCascadePersist(true);
   EntityMocker entityMocker = new EntityMocker(indexBuilder, author, defaults);
   entityMocker.preProcess();
   entityMocker.process();
   Index index = indexBuilder.build(new EntityMappingsMocker.Default());
   DotName className = DotName.createSimple(Author.class.getName());
   assertAnnotationValue(
       index,
       className,
       JPADotNames.ONE_TO_MANY,
       new CascadeAnnotationValueChecker("PERSIST", "MERGE"));
 }
 @Override
 public Collection<Annotation> getAnnotation(Class<?> annotationClass) {
   List<AnnotationInstance> instances =
       backingRepository.getAnnotations(DotName.createSimple(annotationClass.getName()));
   ArrayList<Annotation> annotations = new ArrayList<Annotation>(instances.size());
   for (AnnotationInstance instance : instances) {
     AnnotationTarget target = instance.target();
     Annotation annotation = null;
     if (target instanceof MethodInfo) {
       MethodInfo m = (MethodInfo) target;
       List<String> parameterTypes = new ArrayList<String>(m.args().length);
       for (Type type : m.args()) {
         parameterTypes.add(type.toString());
       }
       String declaringClass = m.declaringClass().name().toString();
       annotation =
           new AnnotationImpl(
               declaringClass, cl, parameterTypes, m.name(), true, false, annotationClass);
     }
     if (target instanceof FieldInfo) {
       FieldInfo f = (FieldInfo) target;
       String declaringClass = f.declaringClass().name().toString();
       annotation =
           new AnnotationImpl(declaringClass, cl, null, f.name(), false, true, annotationClass);
     }
     if (target instanceof ClassInfo) {
       ClassInfo c = (ClassInfo) target;
       annotation =
           new AnnotationImpl(c.name().toString(), cl, null, null, false, false, annotationClass);
     }
     if (annotation != null) {
       annotations.add(annotation);
     }
   }
   annotations.trimToSize();
   if (annotations.size() == 0) {
     return null;
   } else {
     return Collections.unmodifiableList(annotations);
   }
 }
 // @Table, @CollectionTable, @JoinTable, @SecondaryTable
 private void overrideSchemaCatalogByDefault(
     DotName annName,
     Map<DotName, List<AnnotationInstance>> indexedAnnotationMap,
     EntityMappingsMocker.Default defaults) {
   List<AnnotationInstance> annotationInstanceList = indexedAnnotationMap.get(annName);
   if (annotationInstanceList == null || annotationInstanceList.isEmpty()) {
     return;
   }
   List<AnnotationInstance> newAnnotationInstanceList =
       new ArrayList<AnnotationInstance>(annotationInstanceList.size());
   for (AnnotationInstance annotationInstance : annotationInstanceList) {
     if (annName.equals(IndexedAnnotationFilter.SECONDARY_TABLES)) {
       AnnotationInstance[] secondaryTableAnnotationInstanceArray =
           annotationInstance.value().asNestedArray();
       AnnotationValue[] newAnnotationValueArray =
           new AnnotationValue[secondaryTableAnnotationInstanceArray.length];
       for (int i = 0; i < secondaryTableAnnotationInstanceArray.length; i++) {
         newAnnotationValueArray[i] =
             MockHelper.nestedAnnotationValue(
                 "",
                 overrideSchemaCatalogByDefault(
                     secondaryTableAnnotationInstanceArray[i], defaults));
       }
       AnnotationInstance secondaryTablesAnnotationInstance =
           MockHelper.create(
               annName,
               annotationInstance.target(),
               new AnnotationValue[] {
                 AnnotationValue.createArrayValue("value", newAnnotationValueArray)
               });
       newAnnotationInstanceList.add(secondaryTablesAnnotationInstance);
     } else {
       newAnnotationInstanceList.add(overrideSchemaCatalogByDefault(annotationInstance, defaults));
     }
   }
   indexedAnnotationMap.put(annName, newAnnotationInstanceList);
 }
/** @author Lance Ball */
public class IndexFactory {
  public static final DotName IMPLICIT_META =
      DotName.createSimple(Implicit.class.getCanonicalName());
  public static final DotName BINDING_META =
      DotName.createSimple(ModelNodeBinding.class.getCanonicalName());
  public static final DotName ADDRESS_META = DotName.createSimple(Address.class.getCanonicalName());
  public static final DotName ADDRESSES_META =
      DotName.createSimple(Addresses.class.getCanonicalName());
  public static final DotName RESOURCE_TYPE =
      DotName.createSimple(ResourceType.class.getCanonicalName());
  public static final DotName SUBRESOURCE_META =
      DotName.createSimple(Subresource.class.getCanonicalName());

  /** Creates an annotation index for the given entity type */
  public static synchronized Index createIndex(Class<?> type) {
    Index index = indices.get(type);
    if (index == null) {
      try {
        Indexer indexer = new Indexer();
        Class<?> currentType = type;
        while (currentType != null) {
          String className = currentType.getName().replace(".", "/") + ".class";
          InputStream stream = type.getClassLoader().getResourceAsStream(className);
          indexer.index(stream);
          currentType = currentType.getSuperclass();
        }
        index = indexer.complete();
        indices.put(type, index);
      } catch (IOException e) {
        throw new RuntimeException("Failed to initialize Indexer", e);
      }
    }
    return index;
  }

  private static final HashMap<Class<?>, Index> indices = new HashMap<>();
}