Java Code Examples for javax.lang.model.util.Elements#getPackageOf()

The following examples show how to use javax.lang.model.util.Elements#getPackageOf() . 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 check out the related API usage on the sidebar.
Example 1
Source File: ElementJavadoc.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StringBuilder getContainingClassOrPackageHeader(Element el, Elements elements, ElementUtilities eu) {
    StringBuilder sb = new StringBuilder();
    if (el.getKind() != ElementKind.PACKAGE && el.getKind() != ElementKind.MODULE) {
        TypeElement cls = eu.enclosingTypeElement(el);
        if (cls != null) {
            switch(cls.getEnclosingElement().getKind()) {
                case ANNOTATION_TYPE:
                case CLASS:
                case ENUM:
                case INTERFACE:
                case PACKAGE:
                    sb.append("<font size='+0'><b>"); //NOI18N
                    createLink(sb, cls, makeNameLineBreakable(cls.getQualifiedName().toString()));
                    sb.append("</b></font>"); //NOI18N)
            }
        } else {
            PackageElement pkg = elements.getPackageOf(el);
            if (pkg != null) {
                sb.append("<font size='+0'><b>"); //NOI18N
                createLink(sb, pkg, makeNameLineBreakable(pkg.getQualifiedName().toString()));
                sb.append("</b></font>"); //NOI18N)
            }
        }
    }
    return sb;
}
 
Example 2
Source File: TypeUtils.java    From ParcelablePlease with Apache License 2.0 5 votes vote down vote up
/**
 * Get the Package name
 *
 * @throws IOException
 */
public static String getPackageName(Elements elementUtils, TypeElement type) throws IOException {
  PackageElement pkg = elementUtils.getPackageOf(type);
  if (!pkg.isUnnamed()) {
    return pkg.getQualifiedName().toString();
  } else {
    return ""; // Default package
  }
}
 
Example 3
Source File: FactoryCodeBuilder.java    From ShapeView with Apache License 2.0 5 votes vote down vote up
public void generateCode(Messager messager, Elements elementUtils, Filer filer) throws IOException {
    TypeElement superClassName = elementUtils.getTypeElement(mSupperClsName);
    String factoryClassName = superClassName.getSimpleName() + SUFFIX;
    PackageElement pkg = elementUtils.getPackageOf(superClassName);
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();

    TypeSpec typeSpec = TypeSpec
        .classBuilder(factoryClassName)
        .addModifiers(Modifier.PUBLIC)
        .addMethod(newCreateMethod(elementUtils, superClassName))
        .build();

    // Write file
    JavaFile.builder(packageName, typeSpec).build().writeTo(filer);
}
 
Example 4
Source File: BindDaoFactoryBuilder.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Build dao factory interface.
 *
 * @param elementUtils the element utils
 * @param filer the filer
 * @param schema the schema
 * @return schema typeName
 * @throws Exception the exception
 */
public String buildDaoFactoryInterface(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
	String schemaName = generateDaoFactoryName(schema);

	PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
	String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

	AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, schemaName);
	classBuilder = buildDaoFactoryInterfaceInternal(elementUtils, filer, schema);
	TypeSpec typeSpec = classBuilder.build();
	JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);

	return schemaName;
}
 
Example 5
Source File: ProxyInfo.java    From ioc-apt-sample with Apache License 2.0 5 votes vote down vote up
public ProxyInfo(Elements elementUtils, TypeElement classElement)
{
    this.typeElement = classElement;
    PackageElement packageElement = elementUtils.getPackageOf(classElement);
    String packageName = packageElement.getQualifiedName().toString();
    //classname
    String className = ClassValidator.getClassName(classElement, packageName);
    this.packageName = packageName;
    this.proxyClassName = className + "$$" + PROXY;
}
 
Example 6
Source File: ProxyInfo.java    From MPermissions with Apache License 2.0 5 votes vote down vote up
public ProxyInfo(Elements elementUtils, TypeElement classElement)
{
    PackageElement packageElement = elementUtils.getPackageOf(classElement);
    String packageName = packageElement.getQualifiedName().toString();
    //classname
    String className = ClassValidator.getClassName(classElement, packageName);
    this.packageName = packageName;
    this.proxyClassName = className + "$$" + PROXY;
}
 
Example 7
Source File: ProxyInfo.java    From FABridge with Apache License 2.0 5 votes vote down vote up
public ProxyInfo(Elements elementUtils, TypeElement classElement)
{
    PackageElement packageElement = elementUtils.getPackageOf(classElement);
    String packageName = packageElement.getQualifiedName().toString();
    //classname
    String className = ClassValidator.getClassName(classElement, packageName);
    this.packageName = packageName;
    this.proxyClassName = className + "$$" + PROXY;
    this.typeElement = classElement;
}
 
Example 8
Source File: ConfiguredObjectRegistrationGenerator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void processAnnotatedElement(final Elements elementUtils,
                                     final TypeElement annotationElement,
                                     final Element e)
{
    if (e.getKind().equals(ElementKind.INTERFACE) || e.getKind().equals(ElementKind.CLASS))
    {
        PackageElement packageElement = elementUtils.getPackageOf(e);
        String packageName = packageElement.getQualifiedName().toString();
        String className = e.getSimpleName().toString();
        AnnotationMirror annotation = getAnnotation(e, annotationElement);

        AnnotationValue registerValue = getAnnotationValue(annotation, "register");

        if(registerValue == null || (Boolean) registerValue.getValue() )
        {
            AnnotationValue typeValue = getAnnotationValue(annotation, "type");

            if (typeValue != null)
            {
                _typeMap.put(packageName + "." + className, (String) typeValue.getValue());
                processingEnv.getMessager()
                        .printMessage(Diagnostic.Kind.NOTE,
                                      "looking for " + packageName + "." + className);
                _categoryMap.put(packageName + "." + className, getCategory((TypeElement) e));

            }


            Set<String> classNames = _managedObjectClasses.get(packageName);
            if (classNames == null)
            {
                classNames = new HashSet<>();
                _managedObjectClasses.put(packageName, classNames);
            }
            classNames.add(className);
        }
    }
}
 
Example 9
Source File: Briefnessor.java    From Briefness with Apache License 2.0 5 votes vote down vote up
public Briefnessor(Elements elementUtils, TypeElement classElement) {
    this.typeElement = classElement;
    PackageElement packageElement = elementUtils.getPackageOf(classElement);
    String packageName = packageElement.getQualifiedName().toString();
    className = ClassValidator.getClassName(classElement, packageName);
    this.packageName = packageName;
    this.proxyClassName = className + PROXY;
}
 
Example 10
Source File: DocCommentTreeApiTester.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests DocTrees.getDocTreePath(PackageElement p, FileObject fo).
 *
 * @param javaFileName the java anchor file
 * @param pkgFileName the package file name
 * @throws Exception e if something goes awry
 */
public void runDocTreePath(String javaFileName, String pkgFileName) throws Exception  {
    List<File> javaFiles = new ArrayList<>();
    javaFiles.add(new File(testSrc, javaFileName));

    List<File> dirs = new ArrayList<>();
    dirs.add(new File(testSrc));

    try (StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null)) {
        fm.setLocation(javax.tools.StandardLocation.SOURCE_PATH, dirs);
        Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(javaFiles);

        final JavacTask t = javac.getTask(null, fm, null, null, null, fos);
        final DocTrees trees = DocTrees.instance(t);
        final Elements elementUtils = t.getElements();

        Iterable<? extends Element> elements = t.analyze();

        Element klass = elements.iterator().next();
        PackageElement pkg = elementUtils.getPackageOf(klass);

        FileObject htmlFo = fm.getFileForInput(javax.tools.StandardLocation.SOURCE_PATH,
                t.getElements().getPackageOf(klass).getQualifiedName().toString(),
                "package.html");
        System.out.println();
        DocTreePath treePath = trees.getDocTreePath(htmlFo, pkg);
        DocCommentTree dcTree = treePath.getDocComment();

        StringWriter sw = new StringWriter();
        printer.print(dcTree, sw);
        String found = sw.toString();

        String expected = getExpected(htmlFo.openReader(true));
        astcheck(pkgFileName, expected, found);
    }
}
 
Example 11
Source File: InjectorGenerator.java    From PreferenceRoom with Apache License 2.0 5 votes vote down vote up
public InjectorGenerator(
    @NonNull PreferenceComponentAnnotatedClass annotatedClass,
    @NonNull TypeElement injectedElement,
    @NonNull Elements elementUtils) {
  this.annotatedClazz = annotatedClass;
  this.injectedElement = injectedElement;
  PackageElement packageElement = elementUtils.getPackageOf(injectedElement);
  this.packageName =
      packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString();
}
 
Example 12
Source File: Utils.java    From Aurora with Apache License 2.0 5 votes vote down vote up
public static String getPackageName(Elements elements, TypeElement typeElement) throws NoPackageNameException {
    PackageElement pkg = elements.getPackageOf(typeElement);
    if (pkg.isUnnamed()) {
        throw new NoPackageNameException(typeElement);
    }
    return pkg.getQualifiedName().toString();
}
 
Example 13
Source File: EncapsulateFieldRefactoringPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * returns true if elm is accessible from clazz. elm must be member of clazz
 * or its superclass
 */
private static boolean isAccessible(CompilationInfo javac, TypeElement clazz, Element elm) {
    if (clazz == elm.getEnclosingElement()) {
        return true;
    }
    Set<Modifier> mods = elm.getModifiers();
    if (mods.contains(Modifier.PUBLIC) || mods.contains(Modifier.PROTECTED)) {
        return true;
    } else if (mods.contains(Modifier.PRIVATE)) {
        return false;
    }
    Elements utils = javac.getElements();
    return utils.getPackageOf(elm) == utils.getPackageOf(clazz);
}
 
Example 14
Source File: PreferenceComponentAnnotatedClass.java    From PreferenceRoom with Apache License 2.0 4 votes vote down vote up
public PreferenceComponentAnnotatedClass(
    @NonNull TypeElement annotatedElement,
    @NonNull Elements elementUtils,
    @NonNull Map<String, String> annotatedEntityTypeMap)
    throws VerifyException {
  PackageElement packageElement = elementUtils.getPackageOf(annotatedElement);
  this.packageName =
      packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString();
  this.annotatedElement = annotatedElement;
  this.typeName = TypeName.get(annotatedElement.asType());
  this.clazzName = annotatedElement.getSimpleName().toString();
  this.entities = new ArrayList<>();
  this.keyNames = new ArrayList<>();
  this.generatedClazzList = new ArrayList<>();

  annotatedElement.getEnclosedElements().stream()
      .filter(element -> element instanceof ExecutableElement)
      .map(element -> (ExecutableElement) element)
      .forEach(
          method -> {
            MethodSpec methodSpec = MethodSpec.overriding(method).build();
            if (methodSpec.returnType != TypeName.get(Void.TYPE)
                && methodSpec.parameters.size() == 1) {
              throw new VerifyException(
                  String.format(
                      "return type should be void : '%s' method with return type '%s'",
                      methodSpec.name, methodSpec.returnType));
            } else if (methodSpec.parameters.size() > 1) {
              throw new VerifyException(
                  String.format(
                      "length of parameter should be 1 or 0 : '%s' method with parameters '%s'",
                      methodSpec.name, methodSpec.parameters.toString()));
            }
          });

  Set<String> entitySet = new HashSet<>();
  annotatedElement.getAnnotationMirrors().stream()
      .filter(
          annotationMirror ->
              TypeName.get(annotationMirror.getAnnotationType())
                  .equals(TypeName.get(PreferenceComponent.class)))
      .forEach(
          annotationMirror ->
              annotationMirror
                  .getElementValues()
                  .forEach(
                      (type, value) -> {
                        String[] values = value.getValue().toString().split(",");
                        List<String> valueList = Arrays.asList(values);
                        entitySet.addAll(valueList);
                      }));

  entitySet.forEach(
      value -> {
        if (!annotatedEntityTypeMap.containsKey(value)) {
          throw new VerifyException(String.format("%s is not a preference entity.", value));
        } else {
          keyNames.add(annotatedEntityTypeMap.get(value));
          generatedClazzList.add(ENTITY_PREFIX + annotatedEntityTypeMap.get(value));
        }
      });

  entities.addAll(entitySet);
}
 
Example 15
Source File: PreferenceKeyField.java    From PreferenceRoom with Apache License 2.0 4 votes vote down vote up
public PreferenceKeyField(
    @NonNull VariableElement variableElement, @NonNull Elements elementUtils)
    throws IllegalAccessException {
  KeyName annotation_keyName = variableElement.getAnnotation(KeyName.class);
  this.variableElement = variableElement;
  PackageElement packageElement = elementUtils.getPackageOf(variableElement);
  this.packageName =
      packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString();
  this.typeName = TypeName.get(variableElement.asType());
  this.clazzName = variableElement.getSimpleName().toString();
  this.value = variableElement.getConstantValue();
  setTypeStringName();

  if (annotation_keyName != null)
    this.keyName =
        Strings.isNullOrEmpty(annotation_keyName.value())
            ? StringUtils.toUpperCamel(this.clazzName)
            : annotation_keyName.value();
  else this.keyName = StringUtils.toUpperCamel(this.clazzName);

  if (this.isObjectField) {
    variableElement.getAnnotationMirrors().stream()
        .filter(
            annotationMirror ->
                TypeName.get(annotationMirror.getAnnotationType())
                    .equals(TypeName.get(TypeConverter.class)))
        .forEach(
            annotationMirror ->
                annotationMirror
                    .getElementValues()
                    .forEach(
                        (type, value) -> {
                          String[] split = value.getValue().toString().split("\\.");
                          StringBuilder builder = new StringBuilder();
                          for (int i = 0; i < split.length - 1; i++)
                            builder.append(split[i] + ".");
                          this.converterPackage =
                              builder.toString().substring(0, builder.toString().length() - 1);
                          this.converter = split[split.length - 1];
                        }));
  }

  if (variableElement.getModifiers().contains(Modifier.PRIVATE)) {
    throw new IllegalAccessException(
        String.format("Field \'%s\' should not be private.", variableElement.getSimpleName()));
  } else if (!this.isObjectField && !variableElement.getModifiers().contains(Modifier.FINAL)) {
    throw new IllegalAccessException(
        String.format("Field \'%s\' should be final.", variableElement.getSimpleName()));
  }
}
 
Example 16
Source File: SensorAnnotationsFileBuilder.java    From SensorAnnotations with Apache License 2.0 4 votes vote down vote up
/**
 * Generates the code for our "Sensor Binder" class and writes it to the same package as the
 * annotated class.
 *
 * @param groupedMethodsMap Map of annotated methods per class.
 * @param elementUtils ElementUtils class from {@link ProcessingEnvironment}.
 * @param filer File writer class from {@link ProcessingEnvironment}.
 * @throws IOException
 * @throws ProcessingException
 */
static void generateCode(@NonNull Map<String, AnnotatedMethodsPerClass> groupedMethodsMap,
    @NonNull Elements elementUtils, @NonNull Filer filer)
    throws IOException, ProcessingException {
    for (AnnotatedMethodsPerClass groupedMethods : groupedMethodsMap.values()) {
        // If we've annotated methods in an activity called "ExampleActivity" then that will be
        // the enclosing type element.
        TypeElement enclosingClassTypeElement =
            elementUtils.getTypeElement(groupedMethods.getEnclosingClassName());

        // Create the parameterized type that our generated class will implement,
        // (such as "SensorBinder<ExampleActivity>").
        ParameterizedTypeName parameterizedInterface = ParameterizedTypeName.get(SENSOR_BINDER,
            TypeName.get(enclosingClassTypeElement.asType()));

        // Create the target parameter that will be used in the constructor and bind method,
        // (such as "ExampleActivity").
        ParameterSpec targetParameter =
            ParameterSpec.builder(TypeName.get(enclosingClassTypeElement.asType()), "target")
                .addModifiers(Modifier.FINAL)
                .build();

        MethodSpec constructor =
            createConstructor(targetParameter, groupedMethods.getItemsMap());
        MethodSpec bindMethod = createBindMethod(targetParameter, groupedMethods);

        TypeSpec sensorBinderClass =
            TypeSpec.classBuilder(enclosingClassTypeElement.getSimpleName() + SUFFIX)
                .addModifiers(Modifier.FINAL)
                .addSuperinterface(parameterizedInterface)
                .addField(SENSOR_MANAGER_FIELD)
                .addField(LISTENER_WRAPPERS_FIELD)
                .addMethod(constructor)
                .addMethod(bindMethod)
                .addMethod(UNBIND_METHOD)
                .build();

        // Output our generated file with the same package as the target class.
        PackageElement packageElement = elementUtils.getPackageOf(enclosingClassTypeElement);
        JavaFileObject jfo =
            filer.createSourceFile(enclosingClassTypeElement.getQualifiedName() + SUFFIX);
        Writer writer = jfo.openWriter();
        JavaFile.builder(packageElement.toString(), sensorBinderClass)
            .addFileComment("This class is generated code from Sensor Lib. Do not modify!")
            .addStaticImport(CONTEXT, "SENSOR_SERVICE")
            .build()
            .writeTo(writer);
        writer.close();
    }
}
 
Example 17
Source File: ProcessorUtils.java    From jackdaw with Apache License 2.0 4 votes vote down vote up
public static String packageName(final TypeElement element) {
    final ProcessingEnvironment env = ProcessorContextHolder.getProcessingEnvironment();
    final Elements elementUtils = env.getElementUtils();
    final PackageElement packageElement = elementUtils.getPackageOf(element);
    return packageElement.getQualifiedName().toString();
}
 
Example 18
Source File: BindSharedPreferencesBuilder.java    From kripton with Apache License 2.0 4 votes vote down vote up
/**
 * Generate shared preference manager.
 *
 * @param elementUtils
 *            the element utils
 * @param filer
 *            the filer
 * @param entity
 *            the entity
 * @return typeName of generated class
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static String generate(Elements elementUtils, Filer filer, PrefsEntity entity) throws IOException {
	com.abubusoft.kripton.common.Converter<String, String> converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
	String beanClassName = entity.getElement().getSimpleName().toString();
	String className = getBuildPreferenceName(entity);
	ModelAnnotation annotation = entity.getAnnotation(BindSharedPreferences.class);
	String sharedPreferenceName = annotation.getAttribute(AnnotationAttributeType.VALUE);
	boolean generateRx = entity.hasRxProperties();
	boolean generateLiveData = entity.hasLiveDataProperties();

	PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
	String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

	AnnotationProcessorUtilis.infoOnGeneratedClasses(BindSharedPreferences.class, packageName, className);
	// @formatter:off
	builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)
			.superclass(AbstractSharedPreference.class);

	BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(entity.getElement()),
			Modifier.PRIVATE);

	// @formatter:on	
	builder.addJavadoc("This class is the shared preference binder defined for $T\n\n", entity.getElement());
	JavadocUtility.generateJavadocGeneratedBy(builder);
	builder.addJavadoc("@see $T\n", entity.getElement());

	if (StringUtils.hasText(sharedPreferenceName)) {
		builder.addField(FieldSpec.builder(String.class, "SHARED_PREFERENCE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
				.initializer("$S", converter.convert(entity.getSimpleName().toString())).addJavadoc("shared preferences typeName for $T\n", entity.getElement()).build());
	}

	builder.addField(FieldSpec.builder(className(beanClassName), "defaultBean", Modifier.PRIVATE, Modifier.FINAL).addJavadoc("working instance of bean\n").build());

	{
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("edit").addJavadoc("create an editor to modify shared preferences\n").returns(typeName("BindEditor"))
				.addModifiers(Modifier.PUBLIC);
		methodBuilder.addStatement("return new $T()", typeName("BindEditor"));
		builder.addMethod(methodBuilder.build());
	}

	generateEditor(entity);

	generateCreate(sharedPreferenceName, beanClassName, generateRx, generateLiveData);

	generateConstructor(entity, sharedPreferenceName, beanClassName);

	generateRefresh(sharedPreferenceName, className);

	generateRxSupport(sharedPreferenceName, beanClassName, generateRx, entity);

	generateLiveDataSupport(sharedPreferenceName, beanClassName, generateLiveData, entity);

	generateResetMethod(entity);

	generateReadMethod(entity);

	generateWriteMethod(entity);

	generateSingleReadMethod(entity);

	// generate all needed writer and reader
	List<PrefsProperty> fields = entity.getCollection();
	List<PrefsProperty> filteredFields = new ArrayList<>();

	// we need to avoid generation of persists values
	for (PrefsProperty item : fields) {
		if (SetPrefsTransformation.isStringSet(item)) {
			continue;
		} else {
			filteredFields.add(item);
		}
	}

	// avoid to consider StringSet
	ManagedPropertyPersistenceHelper.generateFieldPersistance(context, filteredFields, PersistType.STRING, false, Modifier.PROTECTED);

	generateInstance(className);

	TypeSpec typeSpec = builder.build();
	JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);

	return className;
}