Java Code Examples for javax.annotation.processing.Messager

The following are top voted examples for showing how to use javax.annotation.processing.Messager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: EventBusAnnotationProcessor.java   View source code 6 votes vote down vote up
private void collectSubscribers(Set<? extends TypeElement> annotations, RoundEnvironment env, Messager messager) {
    for (TypeElement annotation : annotations) {
        Set<? extends Element> elements = env.getElementsAnnotatedWith(annotation);
        for (Element element : elements) {
            if (element instanceof ExecutableElement) {
                ExecutableElement method = (ExecutableElement) element;
                if (checkHasNoErrors(method, messager)) {
                    TypeElement classElement = (TypeElement) method.getEnclosingElement();
                    methodsByClass.putElement(classElement, method);
                }
            } else {
                messager.printMessage(Diagnostic.Kind.ERROR, "@Subscribe is only valid for methods", element);
            }
        }
    }
}
 
Example 2
Project: Barricade   File: CodeGenerator.java   View source code 6 votes vote down vote up
private static MethodSpec.Builder generateConstructorBuilder(
    HashMap<String, BarricadeResponseSet> values, Messager messager) {
  MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(PUBLIC);
  methodBuilder.addStatement("configs = new HashMap<>()");

  for (Map.Entry<String, BarricadeResponseSet> entry : values.entrySet()) {
    BarricadeResponseSet barricadeResponseSet = entry.getValue();

    String listName = "barricadeResponsesFor" + entry.getKey();

    methodBuilder.addStatement("$T<$T> " + listName + " = new $T<>()", List.class,
        BarricadeResponse.class, ArrayList.class);

    for (BarricadeResponse barricadeResponse : barricadeResponseSet.responses) {
      methodBuilder.addStatement(listName + ".add(new $T($L, $S, $S))", BarricadeResponse.class,
          barricadeResponse.statusCode, barricadeResponse.responseFileName,
          barricadeResponse.contentType);
    }

    methodBuilder.addStatement(
        "configs.put($S, new $T(" + listName + ", " + barricadeResponseSet.defaultIndex + "))",
        entry.getKey(), TYPE_BARRICADE_RESPONSE_SET);
  }
  return methodBuilder;
}
 
Example 3
Project: AnnotationProcessorStarter   File: AnnotatedClass.java   View source code 6 votes vote down vote up
public void writeInto(final Filer pFiler, final Messager pMessager) {
    // prepare generated class
    final GeneratedClass lGeneratedClass = new GeneratedClass(mEnclosingClass, mMethods);

    final TypeSpec lTypeSpecGeneratedClass = lGeneratedClass.buildTypeSpec();
    final String lPackageName = lGeneratedClass.packageName();

    // create generated class to a file
    try {
        JavaFile.builder(lPackageName, lTypeSpecGeneratedClass)
                .build()
                .writeTo(pFiler);
    } catch (IOException pE) {
        logError(pMessager, mEnclosingClass, "error while writing generated class");
    }
}
 
Example 4
Project: dataenum   File: SpecParser.java   View source code 6 votes vote down vote up
public static Spec parse(Element element, ProcessingEnvironment processingEnv) {
  Messager messager = processingEnv.getMessager();

  if (element.getKind() != ElementKind.INTERFACE) {
    messager.printMessage(
        Diagnostic.Kind.ERROR, "@DataEnum can only be used on interfaces.", element);
    return null;
  }

  TypeElement dataEnum = (TypeElement) element;

  List<TypeVariableName> typeVariableNames = new ArrayList<>();
  for (TypeParameterElement typeParameterElement : dataEnum.getTypeParameters()) {
    typeVariableNames.add(TypeVariableName.get(typeParameterElement));
  }

  List<Value> values = ValuesParser.parse(dataEnum, processingEnv);
  if (values == null) {
    return null;
  }

  ClassName enumInterface = ClassName.get(dataEnum);
  return new Spec(enumInterface, typeVariableNames, values);
}
 
Example 5
Project: AptSpring   File: SpringAnnotationParser.java   View source code 6 votes vote down vote up
private boolean parseBeanMethod(ExecutableElement beanMethod, String[] beanNames, Messager messager) {
  boolean valid = true;
  if (beanNames.length == 0) {
    valid = false;
    messager.printMessage(Kind.ERROR, "All @Bean annotations must define at least one name for a bean.", beanMethod);
  }
  if (beanMethod.getReturnType().getKind() != TypeKind.DECLARED) {
    valid = false;
    messager.printMessage(Kind.ERROR, "@Bean methods must return an Object", beanMethod);
  }
  if (!beanMethod.getModifiers().contains(Modifier.PUBLIC)) {
    valid = false;
    messager.printMessage(Kind.ERROR, "@Bean methods must be marked public", beanMethod);
  }
  List<Modifier> illegalModifiers = getIllegalModifiers(beanMethod.getModifiers(), DISALLOWED_ON_METHOD);
  if (illegalModifiers.size() != 0) {
    valid = false;
    messager.printMessage(Kind.ERROR, "Illegal modifiers found on spring @Bean method: "
         + illegalModifiers.stream().map(m -> m.name()).collect(Collectors.joining(", ")),
        beanMethod);
  }
  return valid;
}
 
Example 6
Project: openjdk-jdk10   File: AnnotationProcessing.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (processingEnv.getElementUtils().getModuleElement("m1x") == null) {
        throw new AssertionError("No m1x module found.");
    }

    Messager messager = processingEnv.getMessager();

    for (TypeElement clazz : ElementFilter.typesIn(roundEnv.getRootElements())) {
        for (VariableElement field : ElementFilter.fieldsIn(clazz.getEnclosedElements())) {
            messager.printMessage(Kind.NOTE, "field: " + field.getSimpleName());
        }
    }

    return false;
}
 
Example 7
Project: jtsgen   File: TSModuleHandlerTest.java   View source code 6 votes vote down vote up
@Before
public void init() {
    Messager messenger = mock(Messager.class);

    this.annotationValue = mock(AnnotationValue.class);

    this.annotationTypeMirror = mock(TypeMirror.class);
    this.executableElement = mock(ExecutableElement.class);

    this.annotationElement = mock(TypeElement.class);
    when(this.annotationElement.asType()).thenReturn(this.annotationTypeMirror);

    this.elementUtils = mock(Elements.class);
    when(this.elementUtils.getTypeElement(any())).thenReturn(this.annotationElement);

    this.processingEnv = mock(ProcessingEnvironment.class);
    when(processingEnv.getMessager()).thenReturn(messenger);
    when(processingEnv.getElementUtils()).thenReturn(this.elementUtils);

    // finally....
    this.testee = new TSModuleHandler(processingEnv);
}
 
Example 8
Project: EgTest   File: Settings.java   View source code 6 votes vote down vote up
static Settings instance(Messager messager, Map<String,String> options) {
    String targetDirStr = options.getOrDefault(TARGET_DIR_KEY, "");
    if (targetDirStr.equals("")) {
        return illegalInstance("initialization failed; no "+TARGET_DIR_KEY+"; options are "+options);
    }
    String onDirExistsStr = options.get(DIR_EXISTS_BEHAVIOR_KEY);
    AlreadyExistsBehavior targetDirExistsBehavior = AlreadyExistsBehavior.OVERWRITE;
    if (onDirExistsStr != null) {
        try {
            targetDirExistsBehavior = AlreadyExistsBehavior.valueOf(onDirExistsStr);
        }
        catch (IllegalArgumentException ex) {
            return handleBadDirExistsBehavior(messager, onDirExistsStr);
        }
    }
    EgLanguage          language = EgLanguage.valueOf(options.getOrDefault(TARGET_LANGUAGE_KEY, "JAVA"));
    boolean    failOnUnsupported = booleanOption(options.get(FAIL_ON_UNSUPPORTED_KEY), true);
    boolean             selfTest = booleanOption(options.get(SELF_TEST_KEY), false);
    return new Settings(language, new File(targetDirStr), targetDirExistsBehavior, failOnUnsupported, selfTest);
}
 
Example 9
Project: immu   File: ImmuCompilerTest.java   View source code 6 votes vote down vote up
@Test
public void write_withIOException() throws Exception {
  final ProcessingEnvironment env = mock(ProcessingEnvironment.class);
  final Messager messager = mock(Messager.class);
  final Filer filer = mock(Filer.class);

  when(env.getMessager()).thenReturn(messager);
  when(env.getFiler()).thenReturn(filer);

  compiler.init(env);

  final JavaFile javaFile = mock(JavaFile.class);
  doThrow(IOException.class).when(javaFile).writeTo(any(Filer.class));

  compiler.writeSource(javaFile);

  verify(messager, times(1)).printMessage(eq(Diagnostic.Kind.ERROR), any());
}
 
Example 10
Project: remoter   File: BindingManager.java   View source code 6 votes vote down vote up
/**
 * Initialize with the given details from the annotation processing enviornment
 */
public BindingManager(Elements elementUtils, Filer filer, Messager messager, Types typeUtils) {
    this.elementUtils = elementUtils;
    this.filer = filer;
    this.messager = messager;
    this.typeUtils = typeUtils;
    this.typeBuilderMap = new HashMap<>();

    stringTypeMirror = getType("java.lang.String");
    listTypeMirror = getType("java.util.List");
    mapTypeMirror = getType("java.util.Map");
    charSequenceTypeMirror = getType("java.lang.CharSequence");
    parcellableTypeMirror = getType("android.os.Parcelable");
    try {
        parcelClass = Class.forName("org.parceler.Parcel");
    } catch (ClassNotFoundException ignored) {
    }
}
 
Example 11
Project: java-code-templates   File: ProcessorModule.java   View source code 5 votes vote down vote up
@Provides @Singleton @Named(DESCRIPTOR_KEY)
static Inventory provideDescriptorInventory(@Named(DESCRIPTOR_KEY) final TypeElement descriptorElement,
		final ClassName outputClassName, final Types types, final Elements elements, final Trees trees,
		final Messager messager, @Named(TEMPLATE_KEY) Inventory templateInventory,
		final ImmutableSet<TypeElement> typesToReceiveAnnotations) {
	return new Inventory(descriptorElement, outputClassName, types, elements, trees, messager, true,
			templateInventory.rawTypeNameSubstitutions(), typesToReceiveAnnotations);
}
 
Example 12
Project: autojackson   File: AutoJacksonProcessor.java   View source code 5 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);

    final Types typeUtils = processingEnv.getTypeUtils();
    final Elements elementUtils = processingEnv.getElementUtils();
    final Filer filer = processingEnv.getFiler();
    final Messager messager = processingEnv.getMessager();

    this.processorUtil = new ProcessorUtil(elementUtils, messager);
    this.implementationCreator = new ImplementationCreator(typeUtils, elementUtils, filer, this.processorUtil);
    this.simpleDeserializerCreator = new SimpleDeserializerCreator(typeUtils, elementUtils, filer, this.processorUtil);
    this.complexDeserializerCreator = new ComplexDeserializerCreator(typeUtils, elementUtils, filer, this.processorUtil);
    this.setupCreator = new SetupCreator(filer, this.processorUtil);
}
 
Example 13
Project: GitHub   File: EventBusAnnotationProcessor.java   View source code 5 votes vote down vote up
private TypeMirror getParamTypeMirror(VariableElement param, Messager messager) {
    TypeMirror typeMirror = param.asType();
    // Check for generic type
    if (typeMirror instanceof TypeVariable) {
        TypeMirror upperBound = ((TypeVariable) typeMirror).getUpperBound();
        if (upperBound instanceof DeclaredType) {
            if (messager != null) {
                messager.printMessage(Diagnostic.Kind.NOTE, "Using upper bound type " + upperBound +
                        " for generic parameter", param);
            }
            typeMirror = upperBound;
        }
    }
    return typeMirror;
}
 
Example 14
Project: andcouchbaseentity   File: LoggerTest.java   View source code 5 votes vote down vote up
@Before
public void init() {
    mMock = Mockito.mock(ProcessingEnvironment.class);

    mMessagerMock = Mockito.mock(Messager.class);
    Mockito.when(mMock.getMessager()).thenReturn(mMessagerMock);
}
 
Example 15
Project: openjdk-jdk10   File: MessagerDiags.java   View source code 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations,
                       RoundEnvironment roundEnv) {
    Messager messager = processingEnv.getMessager();
    for (Element e : roundEnv.getRootElements()) {
        messager.printMessage(WARNING, WRN_NO_SOURCE);
        messager.printMessage(WARNING, WRN_WITH_SOURCE, e);
        messager.printMessage(WARNING, WRN_NO_SOURCE);
    }
    return false;
}
 
Example 16
Project: Barricade   File: CodeGenerator.java   View source code 5 votes vote down vote up
/**
 * Generates the code for the Barricade configuration based on the annotations found.
 *
 * @param processingEnv Processing environment
 * @param configs Configuration detected by annotation processing
 * @param messager Messager to print logs
 * @throws IOException
 */
static void generateClass(ProcessingEnvironment processingEnv,
    HashMap<String, BarricadeResponseSet> configs, Messager messager) throws IOException {

  messager.printMessage(Diagnostic.Kind.NOTE, "Generating configuration code...");

  TypeSpec.Builder classBuilder = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL);

  FieldSpec valuesField = FieldSpec.builder(TYPE_CONFIG, "configs").addModifiers(PRIVATE).build();
  FieldSpec instanceField =
      FieldSpec.builder(ClassName.get(PACKAGE_NAME, CLASS_NAME), "barricadeConfig")
          .addModifiers(PRIVATE, STATIC)
          .build();

  MethodSpec.Builder instanceMethodBuilder = generateGetInstanceMethodBuilder();
  MethodSpec.Builder constructorMethodBuilder = generateConstructorBuilder(configs, messager);
  MethodSpec.Builder valuesMethod = generateGetConfigsMethodBuilder();
  MethodSpec.Builder getResponseMethodBuilder = generateGetResponseMethodBuilder();

  classBuilder.addType(generateEndpointsInnerClass(configs.keySet()));
  classBuilder.addType(generateResponsesInnerClass(configs));
  classBuilder.addField(instanceField);
  classBuilder.addField(valuesField);
  classBuilder.addMethod(instanceMethodBuilder.build());
  classBuilder.addMethod(constructorMethodBuilder.build());
  classBuilder.addMethod(valuesMethod.build());
  classBuilder.addMethod(getResponseMethodBuilder.build());

  classBuilder.addSuperinterface(IBarricadeConfig.class);

  JavaFile.Builder javaFileBuilder = builder(PACKAGE_NAME, classBuilder.build());
  JavaFile javaFile = javaFileBuilder.build();
  javaFile.writeTo(processingEnv.getFiler());

  messager.printMessage(Diagnostic.Kind.NOTE, "Code generation complete!");
}
 
Example 17
Project: java-code-templates   File: ProcessorException.java   View source code 5 votes vote down vote up
public void emitError(final Messager messager) {
	if (troubleMaker.isPresent()) {
		messager.printMessage(ERROR, getMessage(), troubleMaker.get());
	} else {
		messager.printMessage(ERROR, getMessage());
	}
}
 
Example 18
Project: AptSpring   File: SpringAnnotationParser.java   View source code 5 votes vote down vote up
/**
 * Read a TypeElement to get application structure.
 * 
 * @param te definition type element.
 * @param messager presents error messages for the compiler to pass to the user.
 * @return the {@link DefinitionModel} parsed from a properly annotated {@link TypeElement}
 */
public DefinitionModel extractDefinition(TypeElement te, Messager messager) {  
  Verified verified = te.getAnnotation(Verified.class);
  DefinitionModel model = new DefinitionModel(te, verified == null ? false : verified.root());

  errorIfInvalidClass(te, messager);
  
  model.addDependencyNames(getImportsTypes(te));
  String[] configurationBeanNames  = AnnotationValueExtractor
      .getAnnotationValue(te, CONFIGURATION_TYPE, DEFAULT_ANNOTATION_VALUE);
  String[] componentBeanNames  = AnnotationValueExtractor
      .getAnnotationValue(te, COMPONENT_TYPE, DEFAULT_ANNOTATION_VALUE);
  if (configurationBeanNames != null) {
    for (Element enclosed : te.getEnclosedElements()) {
      handleEnclosedElements(messager, model, enclosed);
    }
  } else {
    if (componentBeanNames != null) {
      addModelsFromComponent(te, model, componentBeanNames, messager);
    } else {
      messager.printMessage(Kind.ERROR, "@Verified annotation must only be used on @Configuration or @Component classes", te);
    }
  }
  
  for (String expectedBean : verified.expectedBeans()) {
    model.addDefinition(new ExpectedModel(expectedBean, te));
  }
  return model;
}
 
Example 19
Project: auto-adapter   File: AnnotatedModel.java   View source code 5 votes vote down vote up
AnnotatedModel(final TypeElement model, final Types typeUtils, final Elements elementUtils, final Messager messager,
               final Optional<AnnotationValue> annotationValue, Set<Integer> viewIds) {

    this.annotationValue = annotationValue;
    this.typeUtils = typeUtils;
    this.elementUtils = elementUtils;
    this.messager = messager;
    this.viewHolderFactoryClassName = getViewHolderFactoryClassName(model);
    this.model = model;
    this.viewBinderClassName = getViewBinderClassName(model);
    this.viewIds = viewIds;
}
 
Example 20
Project: AptSpring   File: SpringAnnotationParser.java   View source code 5 votes vote down vote up
/**
 * Builds an instance model by finding the autowired constructor of an @Component model as well as 
 * 
 * @param te the TypeElement corresponding to the @Component class.
 * @param dm the definitionModel built from the @Component.
 * @param names the list if names in an @Component annotation.  Users must explicitly define one.
 * @param messager errors are added to this APT messager.
 */
private void addModelsFromComponent(TypeElement te, DefinitionModel dm, String[] names, Messager messager) {
  List<InstanceDependencyModel> dependencies = new ArrayList<>();
  ExecutableElement chosenConstructor = findAutowiredConstructor(extractConstructorsFromComponent(te));
  if (chosenConstructor == null) {
    messager.printMessage(Kind.ERROR, "No single default constructor or single @Autowired constructor", te);
  } else {
    dependencies = execElementDependency(messager, dm, chosenConstructor);
    //dm.getExpectedDefinitions()
  }
  te.getEnclosedElements().stream()
      .filter(el -> el instanceof VariableElement)
      .map(el -> (VariableElement) el)
      .filter(ve -> !staticPrivateFinalLiteralField.test(ve) && !privateFinalField.test(ve))
      .forEach(ve -> messager
          .printMessage(Kind.ERROR, "@Component classes my only have static final constant fields or final private fields", ve));
  
  InstanceModel model = new InstanceModel(names[0],
      dm.getIdentity(), 
      chosenConstructor, 
      te.getQualifiedName().toString(),
      dependencies, 
      new ArrayList<>());
  
  dm.addDefinition(model);
  for (InstanceDependencyModel dep : dependencies) {
    ExpectedModel expectedModel = new ExpectedModel(dep.getIdentity());
    expectedModel.addDefinitionReferenceToType(model.getIdentity(), dep.getType());
    dm.addDefinition(expectedModel);
  }
}
 
Example 21
Project: AptSpring   File: SpringAnnotationParser.java   View source code 5 votes vote down vote up
private void errorIfInvalidClass(TypeElement te, Messager messager) {
  if (te.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
    messager.printMessage(Kind.ERROR, "The class must be a top level class, not an internal class", te);
  }
  if (AnnotationValueExtractor.getAnnotationValue(te, COMPONENTSCAN_TYPE, "basePackages") != null
      || AnnotationValueExtractor.getAnnotationValue(te, COMPONENTSCANS_TYPE, "basePackages") != null) {
    messager.printMessage(Kind.ERROR, "You may not use @ComponentScan(s) on @Verified classes", te);
  }
}
 
Example 22
Project: AptSpring   File: AptParsingContext.java   View source code 5 votes vote down vote up
/**
 * Gives user feedback as info/warnings/errors during compilation (works in m2e with takari-lifecycle).
 * 
 * @param messager APT round handler for user messages
 */
public void outputErrors(Messager messager) {
  Iterable<ErrorModel> errors = checkAndStoreValid();
  for (ErrorModel error : errors) {
    for (AbstractModel model : error.getInvolved()) {
      if (model.getSourceElement().isPresent()) {
        messager.printMessage(Kind.ERROR, error.getMessageOn(model, k -> getMessageFormats().getMessage(k)),
            getCorrespondingElement(elementUtils, model.getSourceElement().get()));
      } 
    }
  }
}
 
Example 23
Project: java-code-templates   File: AstSubstitutionProcessor.java   View source code 5 votes vote down vote up
AstSubstitutionProcessor(final Trees trees
		, final Inventory substitutionInventory // To identify when we have found a substitution
		, final Inventory fieldsInventory       // Provides fields to use as replacements
		, final Messager messager
		)
{
	this.trees = trees;
	this.substitutionInventory = substitutionInventory;
	this.fields = fieldsInventory.beanProperties().stream().map(BeanProperty::propertyName).collect(toImmutableSet());
	this.messager = messager;
}
 
Example 24
Project: domino   File: ProcessorElement.java   View source code 5 votes vote down vote up
public ProcessorElement(Element element, Elements elementUtils, Types typeUtils,
                        Messager messager) {
    this.element = element;
    this.elementUtils = elementUtils;
    this.typeUtils = typeUtils;
    this.messager = messager;
}
 
Example 25
Project: domino   File: PresentersCollector.java   View source code 5 votes vote down vote up
public PresentersCollector(Messager messager, Types typeUtils, Elements elementUtils,
                           BaseProcessor.ElementFactory elementFactory, Set<String> presenters) {
    this.messager = messager;
    this.typeUtils = typeUtils;
    this.elementUtils = elementUtils;
    this.elementFactory = elementFactory;
    this.presenters = presenters;
}
 
Example 26
Project: domino   File: Register.java   View source code 5 votes vote down vote up
public Register(String fileName, Set<String> items, Messager messager,
                ProcessingEnvironment processingEnv) {

    this.items = items;
    this.messager = messager;
    this.processingEnv = processingEnv;
    this.fileName=fileName;
}
 
Example 27
Project: domino   File: CommandsCollector.java   View source code 5 votes vote down vote up
public CommandsCollector(Messager messager, Types typeUtils,
                         BaseProcessor.ElementFactory elementFactory, Set<String> requests) {
    this.messager = messager;
    this.typeUtils = typeUtils;
    this.elementFactory = elementFactory;
    this.requests = requests;
}
 
Example 28
Project: illuminati   File: IlluminatiPropertiesHelper.java   View source code 5 votes vote down vote up
public static IlluminatiProperties getIlluminatiProperties(final Class<? extends IlluminatiProperties> clazz, Messager messager, final String configPropertiesFileName) {
    IlluminatiProperties illuminatiProperties = null;

    for (String extension : CONFIG_FILE_EXTENSTIONS) {
        String dotBeforeExtension = ".";

        if (StringObjectUtils.isValid(PROFILES_PHASE)) {
            dotBeforeExtension = "-" + PROFILES_PHASE + ".";
        }

        final String fullFileName = configPropertiesFileName + dotBeforeExtension + extension;
        illuminatiProperties = getIlluminatiPropertiesByFile(clazz, messager, fullFileName);

        if (illuminatiProperties != null) {
            break;
        }
    }

    if (illuminatiProperties == null) {
        illuminatiProperties = getIlluminatiPropertiesFromBasicFiles(clazz, messager);
    }

    if (illuminatiProperties == null) {
        if (messager != null) {
            messager.printMessage(Diagnostic.Kind.WARNING, "Sorry, unable to find " + configPropertiesFileName);
        }

        IlluminatiPropertiesHelper.FILEUTIL_LOGGER.debug("Sorry, unable to find " + configPropertiesFileName);
    }

    return illuminatiProperties;
}
 
Example 29
Project: illuminati   File: IlluminatiPropertiesHelper.java   View source code 5 votes vote down vote up
private static IlluminatiProperties getIlluminatiPropertiesFromBasicFiles(final Class<? extends IlluminatiProperties> clazz, Messager messager) {
    IlluminatiProperties illuminatiProperties = null;

    for (String fileName : BASIC_CONFIG_FILES) {
        illuminatiProperties = getIlluminatiPropertiesByFile(clazz, messager, fileName);

        if (illuminatiProperties != null) {
            return illuminatiProperties;
        }
    }

    return null;
}
 
Example 30
Project: jtsgen   File: TsGenProcessorNoAbortTest.java   View source code 5 votes vote down vote up
@Test
public void test_Exception_process() throws Exception {
    TsGenProcessor testee=new TsGenProcessor();
    ProcessingEnvironment processingEnvMock = mock(ProcessingEnvironment.class);
    Messager messenger = mock(Messager.class);
    when(processingEnvMock.getMessager()).thenReturn(messenger);
    testee.init(processingEnvMock);
    testee.process(new HashSet<>(),null);
    verify(messenger).printMessage(any(),any());
}
 
Example 31
Project: jtsgen   File: ModuleGeneratorTest.java   View source code 5 votes vote down vote up
@Test
public void writeModule() throws Exception {
    TypeScriptRenderModel model = new TypeScriptRenderModel(TypeScriptModel.newModelWithDefaultModule());
    ProcessingEnvironment env = mock(ProcessingEnvironment.class);
    Filer filer = mock(Filer.class);
    Messager messager = mock(Messager.class);
    when(env.getMessager()).thenReturn(messager);
    when(filer.createSourceFile(any(),any(),any(),any())).thenThrow(new IOException("mocked IO Error"));
    when(filer.createResource(any(),any(),any())).thenThrow(new IOException("mocked IO Error"));
    when(env.getFiler()).thenReturn(filer);
    ModuleGenerator testee = new ModuleGenerator(model,env);
    testee.writeModule();

    verify(messager).printMessage(any(),any());
}
 
Example 32
Project: jtsgen   File: MirrotTypeToTSConverterVisitorTest.java   View source code 5 votes vote down vote up
@Before
public void init() {
    this.typeElement = Mockito.mock(TypeElement.class);
    this.param = Mockito.mock(TSProcessingInfo.class);
    when(this.param.getTsModel()).thenReturn(TypeScriptModel.newModelWithDefaultModule());
    ProcessingEnvironment processingEnvMock = mock(ProcessingEnvironment.class);
    Messager messenger = mock(Messager.class);
    when(processingEnvMock.getMessager()).thenReturn(messenger);
    when(this.param.getpEnv()).thenReturn(processingEnvMock);


    this.testee = new MirrotTypeToTSConverterVisitor(this.typeElement,this.param) ;
}
 
Example 33
Project: EgTest   File: Settings.java   View source code 5 votes vote down vote up
private static Settings handleBadDirExistsBehavior(Messager messager, String onDirExistsStr) {
    String legalValues = Arrays.stream(AlreadyExistsBehavior.values())
            .map(Enum::name)
            .reduce((a,b) -> a+", "+b)
            .orElse("(No known values)");
    messager.printMessage(ERROR, "Bad value for "+DIR_EXISTS_BEHAVIOR_KEY+" '"+onDirExistsStr+"', "+
            "legal values are "+legalValues);
    return illegalInstance("initialization failed; bad "+DIR_EXISTS_BEHAVIOR_KEY);
}
 
Example 34
Project: remoter   File: RemoteBuilder.java   View source code 5 votes vote down vote up
protected RemoteBuilder(Messager messager, Element remoterInterfaceElement) {
    this.messager = messager;
    this.remoterInterfaceElement = remoterInterfaceElement;
    if (remoterInterfaceElement != null) {
        this.remoterInterfacePackageName = getPackage(remoterInterfaceElement).getQualifiedName().toString();
        this.remoterInterfaceClassName = remoterInterfaceElement.getSimpleName().toString();
    }
}
 
Example 35
Project: annotation-processor-toolkit   File: AnnotationProcessorWrapperTest.java   View source code 4 votes vote down vote up
@Test
public void testWrappedInitCall() {

    AbstractProcessor processorSpy = Mockito.spy(AbstractProcessor.class);

    Messager messager = Mockito.spy(Messager.class);
    ProcessingEnvironment processingEnvironment = Mockito.spy(ProcessingEnvironment.class);
    Mockito.when(processingEnvironment.getMessager()).thenReturn(messager);

    Processor unit = AnnotationProcessorWrapper.wrapProcessor(processorSpy);
    unit.init(processingEnvironment);

    Mockito.verify(processorSpy).init(processingEnvironment);


}
 
Example 36
Project: annotation-processor-toolkit   File: AnnotationProcessorWrapperTest.java   View source code 4 votes vote down vote up
@Test
public void testWrappedProcessCall() {

    AbstractProcessor processorSpy = Mockito.spy(AbstractProcessor.class);

    Messager messager = Mockito.spy(Messager.class);
    ProcessingEnvironment processingEnvironment = Mockito.spy(ProcessingEnvironment.class);
    Mockito.when(processingEnvironment.getMessager()).thenReturn(messager);

    Processor unit = AnnotationProcessorWrapper.wrapProcessor(processorSpy);
    unit.init(processingEnvironment);


    Set<? extends TypeElement> set = new HashSet<TypeElement>();
    RoundEnvironment roundEnvironment = Mockito.mock(RoundEnvironment.class);


    unit.process(set, roundEnvironment);

    Mockito.verify(messager).printMessage(Diagnostic.Kind.NOTE, AbstractAnnotationProcessorTest.TEST_EXECUTION_MESSAGE);
    Mockito.verify(processorSpy).process(set, roundEnvironment);

}
 
Example 37
Project: annotation-processor-toolkit   File: MessagerUtils.java   View source code 4 votes vote down vote up
public Messager getMessager() {
    return ToolingProvider.getTooling().getMessager();
}
 
Example 38
Project: GitHub   File: EventBusAnnotationProcessor.java   View source code 4 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    Messager messager = processingEnv.getMessager();
    try {
        String index = processingEnv.getOptions().get(OPTION_EVENT_BUS_INDEX);
        if (index == null) {
            messager.printMessage(Diagnostic.Kind.ERROR, "No option " + OPTION_EVENT_BUS_INDEX +
                    " passed to annotation processor");
            return false;
        }
        verbose = Boolean.parseBoolean(processingEnv.getOptions().get(OPTION_VERBOSE));
        int lastPeriod = index.lastIndexOf('.');
        String indexPackage = lastPeriod != -1 ? index.substring(0, lastPeriod) : null;

        round++;
        if (verbose) {
            messager.printMessage(Diagnostic.Kind.NOTE, "Processing round " + round + ", new annotations: " +
                    !annotations.isEmpty() + ", processingOver: " + env.processingOver());
        }
        if (env.processingOver()) {
            if (!annotations.isEmpty()) {
                messager.printMessage(Diagnostic.Kind.ERROR,
                        "Unexpected processing state: annotations still available after processing over");
                return false;
            }
        }
        if (annotations.isEmpty()) {
            return false;
        }

        if (writerRoundDone) {
            messager.printMessage(Diagnostic.Kind.ERROR,
                    "Unexpected processing state: annotations still available after writing.");
        }
        collectSubscribers(annotations, env, messager);
        checkForSubscribersToSkip(messager, indexPackage);

        if (!methodsByClass.isEmpty()) {
            createInfoIndexFile(index);
        } else {
            messager.printMessage(Diagnostic.Kind.WARNING, "No @Subscribe annotations found");
        }
        writerRoundDone = true;
    } catch (RuntimeException e) {
        // IntelliJ does not handle exceptions nicely, so log and print a message
        e.printStackTrace();
        messager.printMessage(Diagnostic.Kind.ERROR, "Unexpected error in EventBusAnnotationProcessor: " + e);
    }
    return true;
}
 
Example 39
Project: remoter   File: ShortParamBuilder.java   View source code 4 votes vote down vote up
protected ShortParamBuilder(Messager messager, Element element) {
    super(messager, element);
}
 
Example 40
Project: GitHub   File: MvpCompiler.java   View source code 4 votes vote down vote up
public static Messager getMessager() {
	return sMessager;
}