Example usage for javax.lang.model.element Element getAnnotation

List of usage examples for javax.lang.model.element Element getAnnotation

Introduction

In this page you can find the example usage for javax.lang.model.element Element getAnnotation.

Prototype

@Override
<A extends Annotation> A getAnnotation(Class<A> annotationType);

Source Link

Usage

From source file:Main.java

/**
 * Returns only the elements that are annotated with the given class. For some reason
 * RoundEnvironment is returning elements annotated by other annotations.
 *///from   w  w w .  j  a  v a  2  s  .com
static List<Element> getElementsAnnotatedWith(RoundEnvironment roundEnv,
        Class<? extends Annotation> annotationClass) {
    ArrayList<Element> elements = new ArrayList<Element>();
    for (Element element : roundEnv.getElementsAnnotatedWith(annotationClass)) {
        if (element.getAnnotation(annotationClass) != null) {
            elements.add(element);
        }
    }
    return elements;
}

From source file:cat.ogasoft.protocolizer.processor.CompilerPhase.java

public static void processCompiler(RoundEnvironment roundEnv) throws CompilerException {
    try {//from  www. j  a  v a 2s  .c  om
        String protocPath = "src" + File.separatorChar + "cat" + File.separatorChar + "ogasoft"
                + File.separatorChar + "protocolizer" + File.separatorChar + "protoc";

        DefaultExecutor de = new DefaultExecutor();
        for (Element element : roundEnv.getElementsAnnotatedWith(ProtoFileV2.Compiler.class)) {
            ProtoFileV2.Compiler compiler = element.getAnnotation(ProtoFileV2.Compiler.class);
            if (compiler.compile()) {
                String base = protocPath.replace('.', File.separatorChar);
                File dst = new File(base);
                if (!dst.exists() && !dst.mkdirs()) {
                    throw new Exception("Cann not be created directory " + dst.getAbsolutePath());
                }
                File rootDirectori = new File(base);
                //Compile all the files in compiler.protoFilePaths()
                FileFilter filter = new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return pathname.getName().toLowerCase().endsWith(".proto");
                    }
                };
                for (File protoc : rootDirectori.listFiles(filter)) {
                    String target = base + File.separatorChar + protoc.getName();
                    LOG.info("\tCompiling " + target + "...");
                    CommandLine cmd = CommandLine.parse(compiler.command() + " --proto_path=" + protocPath + " "
                            + compiler.language().option + "=src " + target);
                    int result = de.execute(cmd);
                    if (result != 0) {
                        throw new CompilerException("HO ho... somthing went wrong, code: " + result);
                    }
                    LOG.info("\t" + target + " compiled");
                }
            }
        }
    } catch (Exception e) {
        //Any exception is a CompilerException.
        throw new CompilerException(e.getMessage());
    }
}

From source file:cop.raml.utils.example.JsonExample.java

/**
 * Returns all ignored fields for given {@code typeElement}. This time support only {@link JsonIgnoreProperties} and {@link JsonIgnore}
 * annotations. But in the following article <a href="http://www.baeldung.com/jackson-ignore-properties-on-serialization">Jackson Ignore
 * Properties on Marshalling</a>, more ways to ignore properties can be found, but there're not supported this time.
 *
 * @param typeElement type element//w ww  .  j  a v a2s  .c  o m
 * @return not {@code null} list of ignored fields
 */
@NotNull
private static Set<String> getIgnoredFields(TypeElement typeElement) {
    if (typeElement == null)
        return Collections.emptySet();

    Set<String> res = new HashSet<>();
    JsonIgnoreProperties annotation = typeElement.getAnnotation(JsonIgnoreProperties.class);

    if (annotation != null && ArrayUtils.isNotEmpty(annotation.value()))
        Collections.addAll(res, annotation.value());

    JsonIgnore ann;

    for (Element element : typeElement.getEnclosedElements())
        if ((ann = element.getAnnotation(JsonIgnore.class)) != null && ann.value())
            res.add(element.toString());

    return res;
}

From source file:org.eclim.annotation.CommandListingProcessor.java

public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    Options options = new Options();
    Pattern pattern = null;/*from   w  w w. j  a v a2  s .c  o m*/
    String filter = this.processingEnv.getOptions().get("filter");
    if (filter != null) {
        pattern = Pattern.compile(filter);
    }
    for (TypeElement element : annotations) {
        for (Element e : env.getElementsAnnotatedWith(element)) {
            Command command = e.getAnnotation(Command.class);
            if (pattern == null || pattern.matcher(command.name()).matches()) {
                Collection<Option> opts = options.parseOptions(command.options());
                System.out.print(command.name());
                for (Option opt : opts) {
                    String display = "-" + opt.getOpt();
                    if (opt.hasArg()) {
                        display += " " + opt.getLongOpt();
                    }
                    if (opt.isRequired()) {
                        System.out.print(" " + display);
                    } else {
                        System.out.print(" [" + display + "]");
                    }
                }
                System.out.println("\n\tclass: " + e);
            }
        }
    }
    return true;
}

From source file:me.oriley.shiv.holders.ExtraBindingHolder.java

@Override
void addElement(@NonNull Element element) {
    super.addElement(element);
    if (!element.getAnnotation(BindExtra.class).optional()) {
        mHasNonOptionalExtra = true;//from  w  ww  . j a  v  a  2  s  .  c om
    }
}

From source file:org.drombler.acp.core.action.impl.ActionAnnotationProcessor.java

@Override
protected boolean handleProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element element : roundEnv.getElementsAnnotatedWith(Action.class)) {
        Action actionAnnotation = element.getAnnotation(Action.class);
        if (actionAnnotation != null) {
            registerAction(element, actionAnnotation);
        }//from  w  w w  .ja va 2  s  .c  o m
    }

    for (Element element : roundEnv.getElementsAnnotatedWith(ToggleAction.class)) {
        ToggleAction actionAnnotation = element.getAnnotation(ToggleAction.class);
        if (actionAnnotation != null) {
            registerToggleAction(element, actionAnnotation);
        }
    }

    return false;
}

From source file:me.oriley.shiv.holders.ExtraBindingHolder.java

@NonNull
private CodeBlock generateBindExtrasMethod() throws ShivException {
    CodeBlock.Builder builder = CodeBlock.builder()
            .add("$T $N = ($T) $N;\n", mHostType, FIELD_HOST, mHostType, OBJECT)
            .add("$T $N;\n", Object.class, EXTRA);

    if (ProcessorUtils.isSubtypeOfType(mHostType, Activity.class)) {
        builder.add("$T $N = $N.getIntent();\n", Intent.class, INTENT, FIELD_HOST);
        builder.add("$T $N = $N != null ? $N.getExtras() : null;\n", Bundle.class, BUNDLE, INTENT, INTENT);
    } else if (ProcessorUtils.isSubtypeOfType(mHostType, Fragment.class)
            || ProcessorUtils.isSubtypeOfType(mHostType, android.support.v4.app.Fragment.class)) {
        builder.add("$T $N = $N.getArguments();\n", Bundle.class, BUNDLE, FIELD_HOST);
    } else {//from   w  w  w  . ja  va 2s  .c  om
        throw new ShivException("Unsupported class: " + mHostType.getQualifiedName());
    }

    builder.beginControlFlow("if ($N == null)", BUNDLE);
    if (mHasNonOptionalExtra) {
        builder.add("throw new $T(\"$T contains non-optional extra and bundle was null\");\n",
                IllegalStateException.class, mHostType);
    } else {
        builder.add("return;\n");
    }
    builder.endControlFlow();

    for (Element element : mElements) {
        BindExtra bindExtra = element.getAnnotation(BindExtra.class);

        builder.add("$N = $N.get($S);\n", EXTRA, BUNDLE, bindExtra.value());
        if (isNullable(element) || bindExtra.optional()) {
            builder.add("if ($N != null) {\n", EXTRA)
                    .add("    $N.$N = ($T) $N;\n", FIELD_HOST, element.getSimpleName(), element.asType(), EXTRA)
                    .add("}\n");
        } else {
            builder.add("if ($N == null) {\n", EXTRA)
                    .add("    throw new $T(\"Non-optional extra for $T.$N was not found\");\n",
                            NullPointerException.class, mHostType, element.getSimpleName())
                    .add("}\n")
                    .add("$N.$N = ($T) $N;\n", FIELD_HOST, element.getSimpleName(), element.asType(), EXTRA);
        }
    }

    return builder.build();
}

From source file:me.oriley.shiv.holders.ViewBindingHolder.java

@NonNull
private CodeBlock generateProtectedBindViewsMethod() throws ShivException {
    CodeBlock.Builder builder = CodeBlock.builder()
            .add("$T $N = ($T) $N;\n", mHostType, FIELD_HOST, mHostType, OBJECT)
            .add("int size = $N.getChildCount();\n", VIEW_GROUP).add("int $N = 0;\n", BOUND)
            .beginControlFlow("for (int i = 0; i < size; i++)")
            .add("$T $N = $N.getChildAt(i);\n", View.class, VIEW, VIEW_GROUP)
            .beginControlFlow("if ($N instanceof $T)", VIEW, ViewGroup.class)
            .add("$N += $N($N, ($T) $N);\n", BOUND, BIND_VIEWS, OBJECT, ViewGroup.class, VIEW).endControlFlow()
            .beginControlFlow("switch ($N.getId())", VIEW);

    for (Element element : mElements) {
        builder.add("case $L:\n", element.getAnnotation(BindView.class).value())
                .add("    $N.$N = ($T) $N;\n", FIELD_HOST, element.getSimpleName(), element.asType(), VIEW)
                .add("    $N++;\n", BOUND).add("    break;\n");
    }/*from  w  w w.j av  a 2 s. c o m*/

    builder.endControlFlow().beginControlFlow("if ($N >= $N)", BOUND, VIEW_COUNT).add("break;\n")
            .endControlFlow().endControlFlow().add("return $N;\n", BOUND);

    return builder.build();
}

From source file:org.mule.devkit.module.generation.LifecycleAdapterFactoryGenerator.java

public void generate(Element element) throws GenerationException {
    Module module = element.getAnnotation(Module.class);
    if (!module.poolable())
        return;/*ww  w .j ava 2s.  c o m*/

    DefinedClass lifecycleAdapterFactory = getLifecycleAdapterFactoryClass(element);
    lifecycleAdapterFactory.javadoc()
            .add("A <code>" + lifecycleAdapterFactory.name() + "</code> is an implementation  ");
    lifecycleAdapterFactory.javadoc().add(" of {@link ObjectFactory} interface for ");
    lifecycleAdapterFactory.javadoc().add(ref(element.asType()));

    DefinedClass poolObjectClass = context
            .getClassForRole(context.getNameUtils().generateModuleObjectRoleKey((TypeElement) element));
    context.setClassRole(context.getNameUtils().generatePoolObjectRoleKey((TypeElement) element),
            poolObjectClass);

    generateFields(element, lifecycleAdapterFactory);

    generateInitialiseMethod(lifecycleAdapterFactory);
    generateDisposeMethod(lifecycleAdapterFactory);
    generateGetInstanceMethod(element, lifecycleAdapterFactory, poolObjectClass);
    generateGetObjectClassMethod(lifecycleAdapterFactory, poolObjectClass);
    generateAddObjectInitialisationCallback(lifecycleAdapterFactory);
    generateIsSingleton(lifecycleAdapterFactory);
    generateIsAutoWireObject(lifecycleAdapterFactory);
    generateIsExternallyManagedLifecycle(lifecycleAdapterFactory);
}

From source file:org.mule.devkit.module.generation.PoolAdapterGenerator.java

public void generate(Element element) throws GenerationException {
    Module module = element.getAnnotation(Module.class);
    if (!module.poolable())
        return;//from  w  w w. ja v  a2s  . com

    DefinedClass poolAdapter = getPoolAdapterClass(element);
    poolAdapter.javadoc().add("A <code>" + poolAdapter.name() + "</code> is a wrapper around ");
    poolAdapter.javadoc().add(ref(element.asType()));
    poolAdapter.javadoc().add(" that enables pooling on the POJO.");

    java.util.List<VariableElement> variables = ElementFilter.fieldsIn(element.getEnclosedElements());
    for (VariableElement variable : variables) {
        Configurable configurable = variable.getAnnotation(Configurable.class);

        if (configurable == null)
            continue;

        FieldVariable configField = poolAdapter.field(Modifier.PRIVATE, ref(variable.asType()),
                variable.getSimpleName().toString());
        generateSetter(poolAdapter, configField);
    }

    FieldVariable muleContext = generateFieldForMuleContext(poolAdapter);
    FieldVariable flowConstruct = generateFieldForFlowConstruct(poolAdapter);
    FieldVariable poolingProfile = poolAdapter.field(Modifier.PROTECTED, ref(PoolingProfile.class),
            "poolingProfile");
    FieldVariable lifecyleEnabledObjectPool = poolAdapter.field(Modifier.PROTECTED,
            ref(LifecyleEnabledObjectPool.class), "lifecyleEnabledObjectPool");

    generateSetter(poolAdapter, poolingProfile);
    generateGetter(poolAdapter, poolingProfile);
    generateSetter(poolAdapter, lifecyleEnabledObjectPool);
    generateGetter(poolAdapter, lifecyleEnabledObjectPool);
    generateSetFlowConstructMethod(poolAdapter, flowConstruct);
    generateSetMuleContextMethod(poolAdapter, muleContext);

    generateStartMethod((TypeElement) element, poolAdapter, lifecyleEnabledObjectPool, muleContext,
            poolingProfile);
    generateStopMethod(poolAdapter, lifecyleEnabledObjectPool);
}