Java Code Examples for javax.lang.model.element.AnnotationValue

The following examples show how to use javax.lang.model.element.AnnotationValue. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: DataLoader   Source File: DataLoaderProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private <T> T getAnnotation(Element element, Class<? extends Annotation> type, String name) {
    String canonicalName = type.getCanonicalName();
    List<? extends AnnotationMirror> annotationMirrors = elements.getAllAnnotationMirrors(element);
    if (annotationMirrors != null && annotationMirrors.size() > 0) {
        for (AnnotationMirror annotationMirror : annotationMirrors) {
            if (canonicalName.equals(annotationMirror.getAnnotationType().toString())) {
                if (annotationMirror.getElementValues() != null) {
                    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
                            annotationMirror.getElementValues().entrySet()) {
                        ExecutableElement annotationName = entry.getKey();
                        AnnotationValue annotationValue = entry.getValue();
                        if (annotationName.getSimpleName().toString().equals(name)) {
                            return (T) annotationValue.getValue();
                        }
                    }
                }
            }
        }
    }
    return null;
}
 
Example 2
Source Project: j2cl   Source File: MoreApt.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of fully qualified name of a class found in an annotation.
 *
 * <p>Reading values for type Class in annotation processors causes issues, see {@link
 * Element#getAnnotation(Class)}. To work around these issues we treat the annotation value as a
 * String.
 *
 * <p>Note: If this method is invoked with an annotation and method that does not contain a
 * Collection / Array of class files it will throw an {@link IllegalArgumentException}.
 */
public static ImmutableList<String> getClassNamesFromAnnotation(
    Element element, final Class<? extends Annotation> annotationClass, String field) {
  Optional<AnnotationValue> annotationValue = getAnnotationValue(element, annotationClass, field);
  if (!annotationValue.isPresent()) {
    return ImmutableList.<String>of();
  }
  Object value = annotationValue.get().getValue();
  checkArgument(value instanceof List, "The annotation value does not represent a list");
  @SuppressWarnings("unchecked")
  List<AnnotationValue> values = (List<AnnotationValue>) value;
  return values
      .stream()
      .map(input -> extractClassName(input.toString()))
      .collect(toImmutableList());
}
 
Example 3
Source Project: kripton   Source File: FindTasksVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Void visitAnnotation(AnnotationMirror a, String p) {
	if (AnnotationAttributeType.UPDATE_TASKS.getValue().equals(p)) {
		inTasks = true;
	}

	for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : a.getElementValues().entrySet()) {
		String key = entry.getKey().getSimpleName().toString();
		entry.getValue().accept(this, key);
	}

	if (AnnotationAttributeType.UPDATE_TASKS.getValue().equals(p)) {
		inTasks = false;
	}

	return null;
}
 
Example 4
Source Project: RetroFacebook   Source File: AnnotationOutput.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Void visitAnnotation(AnnotationMirror a, StringBuilder sb) {
  sb.append('@').append(typeSimplifier.simplify(a.getAnnotationType()));
  Map<ExecutableElement, AnnotationValue> map = ImmutableMap.copyOf(a.getElementValues());
  if (!map.isEmpty()) {
    sb.append('(');
    String sep = "";
    for (Map.Entry<ExecutableElement, AnnotationValue> entry : map.entrySet()) {
      sb.append(sep).append(entry.getKey().getSimpleName()).append(" = ");
      sep = ", ";
      this.visit(entry.getValue(), sb);
    }
    sb.append(')');
  }
  return null;
}
 
Example 5
Source Project: netbeans   Source File: UseDatabaseGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void checkDatasourceField(TypeElement typeElement, String name) {
    List<VariableElement> elements = ElementFilter.fieldsIn(typeElement.getEnclosedElements());
    VariableElement variableElement = elements.get(0);
    assertTrue(variableElement.getSimpleName().contentEquals(name)); // field name
    DeclaredType declaredType = (DeclaredType) variableElement.asType();
    TypeElement returnTypeElement = (TypeElement) declaredType.asElement();
    assertTrue(returnTypeElement.getQualifiedName().contentEquals("javax.sql.DataSource")); // field type
    AnnotationMirror annotationMirror = variableElement.getAnnotationMirrors().get(0);
    DeclaredType annotationDeclaredType = annotationMirror.getAnnotationType();
    TypeElement annotationTypeElement = (TypeElement) annotationDeclaredType.asElement();
    assertTrue(annotationTypeElement.getQualifiedName().contentEquals("javax.annotation.Resource")); // annotation type
    Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry = annotationMirror.getElementValues().entrySet().iterator().next();
    String attributeName = entry.getKey().getSimpleName().toString();
    String attributeValue = (String) entry.getValue().getValue();
    assertEquals("name", attributeName); // attributes
    assertEquals(name, attributeValue);
}
 
Example 6
Source Project: netbeans   Source File: EntityMappingsUtilities.java    License: Apache License 2.0 6 votes vote down vote up
public static List<JoinColumn> getJoinColumns(final AnnotationModelHelper helper, Map<String, ? extends AnnotationMirror> annByType) {
    final List<JoinColumn> result = new ArrayList<JoinColumn>();
    AnnotationMirror joinColumnAnn = annByType.get("javax.persistence.JoinColumn"); // NOI18N
    if (joinColumnAnn != null) {
        result.add(new JoinColumnImpl(helper, joinColumnAnn));
    } else {
        AnnotationMirror joinColumnsAnnotation = annByType.get("javax.persistence.JoinColumns"); // NOI18N
        if (joinColumnsAnnotation != null) {
            AnnotationParser jcParser = AnnotationParser.create(helper);
            jcParser.expectAnnotationArray("value", helper.resolveType("javax.persistence.JoinColumn"), new ArrayValueHandler() { // NOI18N
                public Object handleArray(List<AnnotationValue> arrayMembers) {
                    for (AnnotationValue arrayMember : arrayMembers) {
                        AnnotationMirror joinColumnAnnotation = (AnnotationMirror)arrayMember.getValue();
                        result.add(new JoinColumnImpl(helper, joinColumnAnnotation));
                    }
                    return null;
                }
            }, null);
            jcParser.parse(joinColumnsAnnotation);
        }
    }
    return result;
}
 
Example 7
private void verifyAnnotations(Iterable<? extends AnnotationMirror> annotations,
                               Set<String> acceptable) {
    for (AnnotationMirror mirror : annotations) {
        Element annotationElement = mirror.getAnnotationType().asElement();

        if (annotationElement.getAnnotation(Documented.class) == null) {
            note("Ignoring undocumented annotation: " + mirror.getAnnotationType());
        }

        verifyTypeAcceptable(mirror.getAnnotationType(), acceptable);

        for (AnnotationValue value : mirror.getElementValues().values()) {
            verifyAnnotationValue(value, acceptable);
        }
    }
}
 
Example 8
Source Project: netbeans   Source File: CodeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private AnnotationTree computeAnnotationTree(AnnotationMirror am) {
    List<ExpressionTree> params = new LinkedList<ExpressionTree>();

    for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : am.getElementValues().entrySet()) {
        ExpressionTree val = createTreeForAnnotationValue(make, entry.getValue());

        if (val == null) {
            LOG.log(Level.WARNING, "Cannot create annotation for: {0}", entry.getValue());
            continue;
        }

        ExpressionTree vt = make.Assignment(make.Identifier(entry.getKey().getSimpleName()), val);

        params.add(vt);
    }

    return make.Annotation(make.Type(am.getAnnotationType()), params);
}
 
Example 9
Source Project: netbeans   Source File: ElementJavadoc.java    License: Apache License 2.0 6 votes vote down vote up
private void appendAnnotation(StringBuilder sb, AnnotationMirror annotationDesc, boolean topLevel) {
    DeclaredType annotationType = annotationDesc.getAnnotationType();
    if (annotationType != null && (!topLevel || isDocumented(annotationType))) {
        appendType(sb, annotationType, false, false, true);
        Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationDesc.getElementValues();
        if (!values.isEmpty()) {
            sb.append('('); //NOI18N
            for (Iterator<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> it = values.entrySet().iterator(); it.hasNext();) {
                Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> value = it.next();
                createLink(sb, value.getKey(), value.getKey().getSimpleName());
                sb.append('='); //NOI18N
                appendAnnotationValue(sb, value.getValue());
                if (it.hasNext())
                    sb.append(","); //NOI18N
            }
            sb.append(')'); //NOI18N
        }
        if (topLevel)
            sb.append("<br>"); //NOI18N
    }
}
 
Example 10
Source Project: netbeans   Source File: InconsistentPortType.java    License: Apache License 2.0 6 votes vote down vote up
protected ErrorDescription[] apply(TypeElement subject, ProblemContext ctx) {
    AnnotationMirror annEntity = Utilities.findAnnotation(subject, ANNOTATION_WEBSERVICE);
    if (subject.getKind() == ElementKind.CLASS && Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_SEI) == null) {
        Service service = ctx.getLookup().lookup(Service.class);
        WSDLModel model = ctx.getLookup().lookup(WSDLModel.class);
        if (service != null && model != null && model.getState() == State.VALID) {
            PortType portType = model.findComponentByName(subject.getSimpleName().toString(), PortType.class);
            if (portType == null) {
                AnnotationValue nameVal = Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_NAME);
                if(nameVal!=null)
                    portType = model.findComponentByName(nameVal.toString(), PortType.class);
            }
            if (portType == null) {
                String label = NbBundle.getMessage(InconsistentPortType.class, "MSG_InconsistentPortType");
                AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo().
                getTrees().getTree(subject, annEntity);
                Tree problemTree = Utilities.getAnnotationArgumentTree(annotationTree, ANNOTATION_ATTRIBUTE_WSDLLOCATION);
                ctx.setElementToAnnotate(problemTree);
                ErrorDescription problem = createProblem(subject, ctx, label, (Fix) null);
                ctx.setElementToAnnotate(null);
                return new ErrorDescription[]{problem};
            }
        }
    }
    return null;
}
 
Example 11
Source Project: netbeans   Source File: JoinTableImpl.java    License: Apache License 2.0 6 votes vote down vote up
public JoinTableImpl(final AnnotationModelHelper helper, AnnotationMirror annotation) {
    AnnotationParser parser = AnnotationParser.create(helper);
    ArrayValueHandler joinColumnHandler = new ArrayValueHandler() {
        public Object handleArray(List<AnnotationValue> arrayMembers) {
            List<JoinColumn> result = new ArrayList<JoinColumn>();
            for (AnnotationValue arrayMember : arrayMembers) {
                AnnotationMirror joinColumnAnnotation = (AnnotationMirror)arrayMember.getValue();
                result.add(new JoinColumnImpl(helper, joinColumnAnnotation));
            }
            return result;
        }
    };
    TypeMirror joinColumnType = helper.resolveType("javax.persistence.JoinColumn"); // NOI18N
    parser.expectAnnotationArray("joinColumn", joinColumnType, joinColumnHandler, parser.defaultValue(Collections.emptyList())); // NOI18N
    parser.expectAnnotationArray("inverseJoinColumn", joinColumnType, joinColumnHandler, parser.defaultValue(Collections.emptyList())); // NOI18N
    parseResult = parser.parse(annotation);
}
 
Example 12
Source Project: netbeans   Source File: FxClassUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to find the {@code @DefaultProperty} annotation on the type, and returns
 * the default property name. Returns null, if @DefaultProperty is not defined
 * 
 * @param te type to inspect
 * @return default property name, or {@code null} if default property is not defined for the type.
 */
public static String getDefaultProperty(TypeElement te) {
    for (AnnotationMirror an : te.getAnnotationMirrors()) {
        if (!((TypeElement)an.getAnnotationType().asElement()).getQualifiedName().contentEquals(DEFAULT_PROPERTY_TYPE_NAME)) {
            continue;
        }
        Map<? extends ExecutableElement, ? extends AnnotationValue> m =  an.getElementValues();
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> en : m.entrySet()) {
            if (en.getKey().getSimpleName().contentEquals(DEFAULT_PROPERTY_VALUE_NAME)) {
                Object v = en.getValue().getValue();
                return v == null ? null : v.toString();
            }
        }
    }
    return null;
}
 
Example 13
Source Project: CallBuilder   Source File: FieldInfo.java    License: Apache License 2.0 6 votes vote down vote up
static FieldInfo from(Elements elementUtils, VariableElement parameter) {
  FieldStyle style = null;

  // Look for style field on the @BuilderField annotation. If the annotation is
  // present, the value of that field overrides the default set above.
  for (AnnotationMirror ann : parameter.getAnnotationMirrors()) {
    if (ann.getAnnotationType().toString()
        .equals(BuilderField.class.getCanonicalName())) {
      for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> annEl :
           ann.getElementValues().entrySet()) {
        if ("style".equals(annEl.getKey().getSimpleName().toString())) {
          style = FieldStyle.fromStyleClass((DeclaredType) annEl.getValue().getValue());
        }
      }
    }
  }

  return new FieldInfo(parameter, style);
}
 
Example 14
private List<TypeMirror> findServiceAnnotation(Element e) throws LayerGenerationException {
    for (AnnotationMirror ann : e.getAnnotationMirrors()) {
        if (!ProjectServiceProvider.class.getName().equals(ann.getAnnotationType().toString())) {
            continue;
        }
        for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> attr : ann.getElementValues().entrySet()) {
            if (!attr.getKey().getSimpleName().contentEquals("service")) {
                continue;
            }
            List<TypeMirror> r = new ArrayList<TypeMirror>();
            for (Object item : (List<?>) attr.getValue().getValue()) {
                TypeMirror type = (TypeMirror) ((AnnotationValue) item).getValue();
                Types typeUtils = processingEnv.getTypeUtils();
                for (TypeMirror otherType : r) {
                    for (boolean swap : new boolean[] {false, true}) {
                        TypeMirror t1 = swap ? type : otherType;
                        TypeMirror t2 = swap ? otherType : type;
                        if (typeUtils.isSubtype(t1, t2)) {
                            processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "registering under both " + typeUtils.asElement(t2).getSimpleName() + " and its subtype " + typeUtils.asElement(t1).getSimpleName() + " will not work if LookupMerger<" + typeUtils.asElement(t2).getSimpleName() + "> is used (#205151)", e, ann, attr.getValue());
                        }
                    }
                }
                r.add(type);
            }
            return r;
        }
        throw new LayerGenerationException("No service attr found", e);
    }
    throw new LayerGenerationException("No @ProjectServiceProvider found", e);
}
 
Example 15
Source Project: java   Source File: OperatorProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private static AnnotationValue getAnnotationElementValue(String elementName, AnnotationMirror am) {
  for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
      am.getElementValues().entrySet()) {
    if (entry.getKey().getSimpleName().contentEquals(elementName)) {
      return entry.getValue();
    }
  }
  return null;
}
 
Example 16
Source Project: litho   Source File: ProcessorUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets an annotation parameter from an annotation. Usually you can just get the parameter
 * directly, but if the parameter has type {@link Class} it doesn't work, because javac doesn't
 * load classes in the normal manner.
 *
 * @see <a
 *     href="https://area-51.blog/2009/02/13/getting-class-values-from-annotations-in-an-annotationprocessor">this
 *     article</a> for more details.
 */
public static @Nullable <T> T getAnnotationParameter(
    Elements elements,
    Element element,
    Class<?> annotationType,
    String parameterName,
    Class<? extends T> expectedReturnType) {
  List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();

  AnnotationMirror mirror = null;
  for (AnnotationMirror m : annotationMirrors) {
    if (m.getAnnotationType().toString().equals(annotationType.getCanonicalName())) {
      mirror = m;
      break;
    }
  }

  if (mirror == null) {
    return null;
  }

  for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
      elements.getElementValuesWithDefaults(mirror).entrySet()) {
    if (parameterName.equals(entry.getKey().getSimpleName().toString())) {
      try {
        return expectedReturnType.cast(entry.getValue().getValue());
      } catch (ClassCastException e) {
        throw new ComponentsProcessingException(
            element,
            mirror,
            String.format(
                "Error processing the annotation '%s'. Are your imports set up correctly? The causing error was: %s",
                annotationType.getCanonicalName(), e));
      }
    }
  }

  return null;
}
 
Example 17
Source Project: SimpleWeibo   Source File: AnnotationOutput.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitArray(List<? extends AnnotationValue> values, StringBuilder sb) {
  sb.append('{');
  String sep = "";
  for (AnnotationValue value : values) {
    sb.append(sep);
    visit(value, sb);
    sep = ", ";
  }
  sb.append('}');
  return null;
}
 
Example 18
Source Project: netbeans   Source File: JUnit4TestGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns fully qualified class name of a class given to an annotation
 * as (the only) argument.
 * 
 * @param  annValue  annotation value
 * @return  fully qualified name of a class represented by the given
 *          annotation value, or {@code null} if the annotation value
 *          does not represent a class
 */
private Name getAnnotationValueClassName(AnnotationValue annValue,
                                         Types types) {
    Object value = annValue.getValue();
    if (value instanceof TypeMirror) {
        TypeMirror typeMirror = (TypeMirror) value;
        Element typeElement = types.asElement(typeMirror);
        if (typeElement.getKind() == ElementKind.CLASS) {
            return ((TypeElement) typeElement).getQualifiedName();
        }
    }
    return null;
}
 
Example 19
Source Project: aircon   Source File: CustomConfigAnnotationParser.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T getAttributeFromElementValues(String attr) {
	for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : mAnnotationMirror.getElementValues()
	                                                                                                .entrySet()) {
		if (entry.getKey()
		         .getSimpleName()
		         .toString()
		         .equals(attr)) {
			return (T) entry.getValue()
			                .getValue();
		}
	}

	return null;
}
 
Example 20
Source Project: karaf-boot   Source File: KarafProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getAnnotationValues(AnnotationMirror mirror) {
    Map<String, Object> map = new HashMap<>();
    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : mirror.getElementValues().entrySet()) {
        map.put(entry.getKey().getSimpleName().toString(), entry.getValue().getValue());
    }
    return map;
}
 
Example 21
Source Project: netbeans   Source File: AnnotationParser.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean checkMembers(List<AnnotationValue> arrayMembers) {
    for (AnnotationValue arrayMember : arrayMembers) {
        Object value = arrayMember.getValue();
        if (!(value instanceof AnnotationMirror)) {
            return false;
        }
        AnnotationMirror annotation = (AnnotationMirror)value;
        if (!isSameAsTypeToCheck(annotation.getAnnotationType())) {
            return false;
        }
    }
    return true;
}
 
Example 22
Source Project: turbine   Source File: TurbineMessager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void printMessage(
    Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v) {
  if (a == null || e == null || e instanceof TurbineNoTypeElement || v == null) {
    printMessage(kind, msg, e, a);
    return;
  }
  SourceFile source = getSource(((TurbineElement) e).sym());
  AnnoInfo anno = ((TurbineAnnotationMirror) a).anno();
  int position = locateInAnnotation(((TurbineAnnotationValueMirror) v).value(), anno);
  if (position == -1) {
    position = anno.tree().position();
  }
  log.withSource(source).diagnostic(kind, position, TurbineError.ErrorKind.PROC, msg);
}
 
Example 23
Source Project: RetroFacebook   Source File: GwtSerialization.java    License: Apache License 2.0 5 votes vote down vote up
private boolean shouldWriteGwtSerializer() {
  Optional<AnnotationMirror> optionalGwtCompatible = gwtCompatibility.gwtCompatibleAnnotation();
  if (optionalGwtCompatible.isPresent()) {
    AnnotationMirror gwtCompatible = optionalGwtCompatible.get();
    for (Map.Entry<ExecutableElement, AnnotationValue> entry :
        Collections.unmodifiableMap(gwtCompatible.getElementValues()).entrySet()) {
      if (entry.getKey().getSimpleName().contentEquals("serializable")
          && entry.getValue().getValue().equals(true)) {
        return true;
      }
    }
  }
  return false;
}
 
Example 24
Source Project: Java-9-Programming-By-Example   Source File: Aptools.java    License: MIT License 5 votes vote down vote up
@Transition(from = "AnnotationTool", end = true)
public String getStringValue(String name) {
  AnnotationValue av = getAnnotationValue(name);
  String value;
  if (av == null) {
    value = null;
  } else {
    value = GetThe.string(av.toString()).unquoted();
  }
  return value;
}
 
Example 25
Source Project: netbeans   Source File: JUnit4TestGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the given annotation is of type
 * <code>{@value #ANN_SUITE}.{@value #ANN_SUITE_MEMBERS}</code>
 * and contains the given list of classes as (the only) argument,
 * in the same order.
 * 
 * @param  annMirror  annotation to be checked
 * @param  suiteMembers  list of fully qualified class names denoting
 *                       content of the test suite
 * @return  {@code true} if the annotation meets the described criteria,
 *          {@code false} otherwise
 */
private boolean checkSuiteMembersAnnotation(AnnotationMirror annMirror,
                                            List<String> suiteMembers,
                                            WorkingCopy workingCopy) {
    Map<? extends ExecutableElement,? extends AnnotationValue> annParams
            = annMirror.getElementValues();
    
    if (annParams.size() != 1) {
        return false;
    }
    
    AnnotationValue annValue = annParams.values().iterator().next();
    Object value = annValue.getValue();
    if (value instanceof java.util.List) {
        List<? extends AnnotationValue> items
                = (List<? extends AnnotationValue>) value;
        
        if (items.size() != suiteMembers.size()) {
            return false;
        }
        
        Types types = workingCopy.getTypes();
        Iterator<String> suiteMembersIt = suiteMembers.iterator();
        for (AnnotationValue item : items) {
            Name suiteMemberName = getAnnotationValueClassName(item, types);
            if (suiteMemberName == null) {
                return false;
            }
            if (!suiteMemberName.contentEquals(suiteMembersIt.next())) {
                return false;
            }
        }
        return true;
    }
    
    return false;
}
 
Example 26
Source Project: netbeans   Source File: JpaControllerUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String findAnnotationValueAsString(AnnotationMirror annotation, String annotationKey) {
    String value = null;
    Map<? extends ExecutableElement,? extends AnnotationValue> annotationMap = annotation.getElementValues();
    for (ExecutableElement key : annotationMap.keySet()) {
        if (annotationKey.equals(key.getSimpleName().toString())) {
            AnnotationValue annotationValue = annotationMap.get(key);
            value = annotationValue.getValue().toString();
            break;
        }
    }
    return value;
}
 
Example 27
Source Project: netbeans   Source File: JUnit5TestGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns fully qualified class name of a class given to an annotation
 * as (the only) argument.
 * 
 * @param  annValue  annotation value
 * @return  fully qualified name of a class represented by the given
 *          annotation value, or {@code null} if the annotation value
 *          does not represent a class
 */
private Name getAnnotationValueClassName(AnnotationValue annValue,
                                         Types types) {
    Object value = annValue.getValue();
    if (value instanceof TypeMirror) {
        TypeMirror typeMirror = (TypeMirror) value;
        Element typeElement = types.asElement(typeMirror);
        if (typeElement.getKind() == ElementKind.CLASS) {
            return ((TypeElement) typeElement).getQualifiedName();
        }
    }
    return null;
}
 
Example 28
Source Project: netbeans   Source File: JaxWsNode.java    License: Apache License 2.0 5 votes vote down vote up
private boolean resolveServiceUrl(CompilationController controller, 
        TypeElement targetElement, String[] serviceName, String[] name) 
            throws IOException 
{
    boolean foundWsAnnotation = false;
    List<? extends AnnotationMirror> annotations = targetElement.getAnnotationMirrors();
    for (AnnotationMirror anMirror : annotations) {
        boolean isWebMethodAnnotation = JaxWsUtils.hasFqn(anMirror, 
                "javax.jws.WebService");   // NOI18N
        if (isWebMethodAnnotation) {
            foundWsAnnotation = true;
            Map<? extends ExecutableElement, ? extends AnnotationValue> 
                expressions = anMirror.getElementValues();
            for (Map.Entry<? extends ExecutableElement, 
                    ? extends AnnotationValue> entry : expressions.entrySet()) 
            {
                if (entry.getKey().getSimpleName().contentEquals("serviceName")) { //NOI18N
                    serviceName[0] = (String) expressions.get(entry.getKey()).
                        getValue();
                    if (serviceName[0] != null) {
                        serviceName[0] = URLEncoder.encode(serviceName[0], 
                                "UTF-8"); //NOI18N
                    }
                } else if (entry.getKey().getSimpleName().
                        contentEquals("name"))  //NOI18N
                {
                    name[0] = (String) expressions.get(entry.getKey()).getValue();
                    if (name[0] != null) {
                        name[0] = URLEncoder.encode(name[0], "UTF-8"); //NOI18N
                    }
                }
                if (serviceName[0] != null && name[0] != null) {
                    break;
                }
            }
            break;
        } // end if
    } // end for
    return foundWsAnnotation;
}
 
Example 29
Source Project: Moxy   Source File: Util.java    License: MIT License 5 votes vote down vote up
public static String getAnnotationValueAsString(AnnotationMirror annotationMirror, String key) {
	AnnotationValue av = getAnnotationValue(annotationMirror, key);

	if (av != null) {
		return av.getValue().toString();
	} else {
		return null;
	}
}
 
Example 30
Source Project: squidb   Source File: ErrorLoggingProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void logErrors(Element element) {
    AnnotationValue errorsArrayValue = utils.getAnnotationValue(element, ModelGenErrors.class, "value");
    List<? extends AnnotationValue> errorsList = (List<? extends AnnotationValue>) errorsArrayValue.getValue();
    for (AnnotationValue error : errorsList) {
        logSingleError(error);
    }
}