/**
  * Method called to create a "default instance" of the bean, currently only needed for obtaining
  * default field values which may be used for suppressing serialization of fields that have "not
  * changed".
  *
  * @param fixAccess If true, method is allowed to fix access to the default constructor (to be
  *     able to call non-public constructor); if false, has to use constructor as is.
  * @return Instance of class represented by this descriptor, if suitable default constructor was
  *     found; null otherwise.
  */
 public Object instantiateBean(boolean fixAccess) {
   AnnotatedConstructor ac = _classInfo.getDefaultConstructor();
   if (ac == null) {
     return null;
   }
   if (fixAccess) {
     ac.fixAccess();
   }
   try {
     return ac.getAnnotated().newInstance();
   } catch (Exception e) {
     Throwable t = e;
     while (t.getCause() != null) {
       t = t.getCause();
     }
     if (t instanceof Error) throw (Error) t;
     if (t instanceof RuntimeException) throw (RuntimeException) t;
     throw new IllegalArgumentException(
         "Failed to instantiate bean of type "
             + _classInfo.getAnnotated().getName()
             + ": ("
             + t.getClass().getName()
             + ") "
             + t.getMessage(),
         t);
   }
 }
  protected BeanPropertyWriter _constructVirtualProperty(
      JsonAppend.Prop prop, MapperConfig<?> config, AnnotatedClass ac) {
    PropertyMetadata metadata =
        prop.required() ? PropertyMetadata.STD_REQUIRED : PropertyMetadata.STD_OPTIONAL;
    PropertyName propName = _propertyName(prop.name(), prop.namespace());
    JavaType type = config.constructType(prop.type());
    // now, then, we need a placeholder for member (no real Field/Method):
    AnnotatedMember member =
        new VirtualAnnotatedMember(
            ac, ac.getRawType(), propName.getSimpleName(), type.getRawClass());
    // and with that and property definition
    SimpleBeanPropertyDefinition propDef =
        SimpleBeanPropertyDefinition.construct(config, member, propName, metadata, prop.include());

    Class<?> implClass = prop.value();

    HandlerInstantiator hi = config.getHandlerInstantiator();
    VirtualBeanPropertyWriter bpw =
        (hi == null) ? null : hi.virtualPropertyWriterInstance(config, implClass);
    if (bpw == null) {
      bpw =
          (VirtualBeanPropertyWriter)
              ClassUtil.createInstance(implClass, config.canOverrideAccessModifiers());
    }

    // one more thing: give it necessary contextual information
    return bpw.withConfig(config, ac, propDef, type);
  }
 @Test
 public void shouldThrowIfNoConverter() throws Exception {
   TypeDescriptor targetType = AnnotatedClass.getFieldTypeDescriptor();
   reset(application);
   thrown.expect(IllegalStateException.class);
   thrown.expectMessage("No JSF converter located for ID 'example'");
   converter.convert(source, sourceType, targetType);
 }
 @Test
 public void shouldReThrowFacesException() throws Exception {
   TypeDescriptor targetType = AnnotatedClass.getFieldTypeDescriptor();
   reset(application);
   given(application.createConverter("example")).willThrow(new FacesException());
   thrown.expect(FacesException.class);
   converter.convert(source, sourceType, targetType);
 }
  protected BeanPropertyWriter _constructVirtualProperty(
      JsonAppend.Attr attr, MapperConfig<?> config, AnnotatedClass ac, JavaType type) {
    PropertyMetadata metadata =
        attr.required() ? PropertyMetadata.STD_REQUIRED : PropertyMetadata.STD_OPTIONAL;
    // could add Index, Description in future, if those matter
    String attrName = attr.value();

    // allow explicit renaming; if none, default to attribute name
    PropertyName propName = _propertyName(attr.propName(), attr.propNamespace());
    if (!propName.hasSimpleName()) {
      propName = PropertyName.construct(attrName);
    }
    // now, then, we need a placeholder for member (no real Field/Method):
    AnnotatedMember member =
        new VirtualAnnotatedMember(ac, ac.getRawType(), attrName, type.getRawClass());
    // and with that and property definition
    SimpleBeanPropertyDefinition propDef =
        SimpleBeanPropertyDefinition.construct(config, member, propName, metadata, attr.include());
    // can construct the property writer
    return AttributePropertyWriter.construct(attrName, propDef, ac.getAnnotations(), type);
  }
 public List<AnnotatedMethod> getFactoryMethods() {
   // must filter out anything that clearly is not a factory method
   List<AnnotatedMethod> candidates = _classInfo.getStaticMethods();
   if (candidates.isEmpty()) {
     return candidates;
   }
   ArrayList<AnnotatedMethod> result = new ArrayList<AnnotatedMethod>();
   for (AnnotatedMethod am : candidates) {
     if (isFactoryMethod(am)) {
       result.add(am);
     }
   }
   return result;
 }
 /**
  * Method that can be called to find if introspected class declares a static "valueOf" factory
  * method that returns an instance of introspected type, given one of acceptable types.
  *
  * @param expArgTypes Types that the matching single argument factory method can take: will also
  *     accept super types of these types (ie. arg just has to be assignable from expArgType)
  */
 public Method findFactoryMethod(Class<?>... expArgTypes) {
   // So, of all single-arg static methods:
   for (AnnotatedMethod am : _classInfo.getStaticMethods()) {
     if (isFactoryMethod(am)) {
       // And must take one of expected arg types (or supertype)
       Class<?> actualArgType = am.getParameterClass(0);
       for (Class<?> expArgType : expArgTypes) {
         // And one that matches what we would pass in
         if (actualArgType.isAssignableFrom(expArgType)) {
           return am.getAnnotated();
         }
       }
     }
   }
   return null;
 }
 /**
  * Method that can be called to locate a single-arg constructor that takes specified exact type
  * (will not accept supertype constructors)
  *
  * @param argTypes Type(s) of the argument that we are looking for
  */
 public Constructor<?> findSingleArgConstructor(Class<?>... argTypes) {
   for (AnnotatedConstructor ac : _classInfo.getConstructors()) {
     // This list is already filtered to only include accessible
     /* (note: for now this is a redundant check; but in future
      * that may change; thus leaving here for now)
      */
     if (ac.getParameterCount() == 1) {
       Class<?> actArg = ac.getParameterClass(0);
       for (Class<?> expArg : argTypes) {
         if (expArg == actArg) {
           return ac.getAnnotated();
         }
       }
     }
   }
   return null;
 }
Example #9
0
  public void printAnnotations() {
    // Get Class object of the AnnotatedClass class
    Class c = ac.getClass();
    // Get all annotations applied to the AnnotatedClass class.
    // Only the annotations with RUNTIME retention are retained during runtime.
    Annotation[] annotations = c.getAnnotations();
    int numberOfAnnotations = annotations.length;
    System.out.println(
        "La Clase " + c.getName() + " tiene " + numberOfAnnotations + " anotaciones");

    for (int i = 0; i < numberOfAnnotations; i++) {
      System.out.println(
          "Anotacion "
              + i
              + ": "
              + annotations[i]
              + ", tipo"
              + annotations[i].annotationType().getName());
    }
  }
 public AnnotatedMethod findMethod(String name, Class<?>[] paramTypes) {
   return _classInfo.findMethod(name, paramTypes);
 }
 public List<AnnotatedConstructor> getConstructors() {
   return _classInfo.getConstructors();
 }
 /**
  * Method that will locate the no-arg constructor for this class, if it has one, and that
  * constructor has not been marked as ignorable.
  *
  * @since 1.9
  */
 @Override
 public AnnotatedConstructor findDefaultConstructor() {
   return _classInfo.getDefaultConstructor();
 }
 /**
  * Method for checking whether class being described has any annotations recognized by registered
  * annotation introspector.
  */
 @Override
 public boolean hasKnownClassAnnotations() {
   return _classInfo.hasAnnotations();
 }
  private PackageClass parseClass(Element classNode) {
    PackageClass newClass = new PackageClass();
    _package.getClasses().add(newClass);

    newClass.setComponentType(PackageClass.ComponentType.getType(classNode.getAttribute(ATR_TYPE)));
    newClass.setStatic(Boolean.parseBoolean(classNode.getAttribute(ATR_STATIC)));
    newClass.setName(getElementByName(classNode, EL_NAME).getTextContent());
    final String source = getElementStringByName(classNode, EL_FILE);
    if (source != null) {
      newClass.setSource(source);
    }
    newClass.setTarget(getElementStringByName(classNode, EL_EXTENDS));
    newClass.setDescription(getElementByName(classNode, EL_DESCRIPTION).getTextContent());
    newClass.setIcon(getElementByName(classNode, EL_ICON).getTextContent());

    // parse all variables declared in the corresponding specification
    if (newClass.getComponentType().hasSpec()) {
      final String newClassName = newClass.getName();
      try {
        switch (RuntimeProperties.getSpecParserKind()) {
          case REGEXP:
            {
              ClassList classList = new ClassList();
              SpecParser.parseSpecClass(newClassName, getWorkingDir(), classList);
              newClass.setSpecFields(classList.getType(newClassName).getFields());
              break;
            }
          case ANTLR:
            {
              if (specificationLoader == null) {
                specificationLoader =
                    new SpecificationLoader(new PackageSpecSourceProvider(_package), null);
              }
              final AnnotatedClass annotatedClass =
                  specificationLoader.getSpecification(newClassName);
              newClass.setSpecFields(annotatedClass.getFields());
              break;
            }
          default:
            throw new IllegalStateException("Undefined specification language parser");
        }
      } catch (SpecParseException e) {
        final String msg = "Unable to parse the specification of class " + newClassName;
        logger.error(msg, e);
        collector.collectDiagnostic(msg + "\nReason: " + e.getMessage() + "\nLine: " + e.getLine());
      }
    }

    // Graphics
    Element grNode = getElementByName(classNode, EL_GRAPHICS);
    newClass.addGraphics(
        getGraphicsParser().parse(grNode/*, newClass.getComponentType() == ComponentType.REL*/ ));

    Element painter;
    if ((painter = getElementByName(grNode, EL_PAINTER)) != null) {
      newClass.setPainterName(painter.getTextContent());
    }

    // Ports
    NodeList ports = classNode.getElementsByTagName(EL_PORT);
    for (int i = 0; i < ports.getLength(); i++) {
      parsePort(newClass, (Element) ports.item(i));
    }

    // Fields
    NodeList fields = classNode.getElementsByTagName(EL_FIELD);
    for (int i = 0; i < fields.getLength(); i++) {
      parseField(newClass, (Element) fields.item(i));
    }

    return newClass;
  }
 @Test
 public void shouldMatchIfHasAnnotationOnMethod() throws Exception {
   TypeDescriptor targetType = AnnotatedClass.getMethodParamTypeDescriptor();
   assertTrue(converter.matches(sourceType, targetType));
 }
 @Override
 public Annotations getClassAnnotations() {
   return _classInfo.getAnnotations();
 }
 @Test
 public void shouldConvertAnnotationOnMethod() throws Exception {
   TypeDescriptor targetType = AnnotatedClass.getMethodParamTypeDescriptor();
   assertEquals(converted, converter.convert(source, sourceType, targetType));
 }