Java Code Examples for javax.lang.model.util.Types#asElement()

The following examples show how to use javax.lang.model.util.Types#asElement() . 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: JpaControllerUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static TypeMirror stripCollection(TypeMirror passedType, Types types) {
    if (TypeKind.DECLARED != passedType.getKind() || !(passedType instanceof DeclaredType)) {
        return passedType;
    }
    TypeElement passedTypeElement = (TypeElement) types.asElement(passedType);
    String passedTypeQualifiedName = passedTypeElement.getQualifiedName().toString();   //does not include type parameter info
    Class passedTypeClass = null;
    try {
        passedTypeClass = Class.forName(passedTypeQualifiedName);
    } catch (ClassNotFoundException e) {
        //just let passedTypeClass be null
    }
    if (passedTypeClass != null && Collection.class.isAssignableFrom(passedTypeClass)) {
        List<? extends TypeMirror> passedTypeArgs = ((DeclaredType)passedType).getTypeArguments();
        if (passedTypeArgs.isEmpty()) {
            return passedType;
        }
        return passedTypeArgs.get(0);
    }
    return passedType;
}
 
Example 2
Source File: JavaSourceParserUtil.java    From jeddict with Apache License 2.0 6 votes vote down vote up
public static TypeMirror stripCollection(TypeMirror passedType, Types types) {
    if (TypeKind.DECLARED != passedType.getKind() || !(passedType instanceof DeclaredType)) {
        return passedType;
    }
    TypeElement passedTypeElement = (TypeElement) types.asElement(passedType);
    String passedTypeQualifiedName = passedTypeElement.getQualifiedName().toString();   //does not include type parameter info
    Class passedTypeClass = null;
    try {
        passedTypeClass = Class.forName(passedTypeQualifiedName);
    } catch (ClassNotFoundException e) {
        //just let passedTypeClass be null
    }
    if (passedTypeClass != null && Collection.class.isAssignableFrom(passedTypeClass)) {
        List<? extends TypeMirror> passedTypeArgs = ((DeclaredType) passedType).getTypeArguments();
        if (passedTypeArgs.isEmpty()) {
            return passedType;
        }
        return passedTypeArgs.get(0);
    }
    return passedType;
}
 
Example 3
Source File: DelegateAssignabilityChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isAssignable( TypeMirror from, TypeMirror to, Types types )
{
    if ( !super.isAssignable(from, to, types) ){
        return false; 
    }
    else {
        Element fromElement = types.asElement(from);
        Collection<TypeMirror> restrictedTypes = RestrictedTypedFilter
                .getRestrictedTypes(fromElement,
                        getImplementation());
        if (restrictedTypes == null) {
            return getImplementation().getHelper()
                    .getCompilationController().getTypes()
                        .isAssignable(from, to);
        }
        for ( TypeMirror restrictedType : restrictedTypes ){
            if ( types.isSameType( types.erasure(restrictedType), 
                    types.erasure( to )))
            {
                return true;
            }
        }
        return false;
    }
}
 
Example 4
Source File: ProcessorUtils.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
public static TypeElement getWrappedType(final TypeMirror mirror) {
    final ProcessingEnvironment env = ProcessorContextHolder.getProcessingEnvironment();
    final Types typeUtils = env.getTypeUtils();

    final TypeKind kind = mirror.getKind();
    final boolean primitive = kind.isPrimitive();

    if (primitive) {
        return typeUtils.boxedClass((PrimitiveType) mirror);
    }
    return (TypeElement) typeUtils.asElement(mirror);
}
 
Example 5
Source File: Mirrors.java    From requery with Apache License 2.0 5 votes vote down vote up
private static boolean extendsClass(Types types, TypeElement element, String className) {
    if (namesEqual(element, className)) {
        return true;
    }
    // check super types
    TypeMirror superType = element.getSuperclass();
    while (superType != null && superType.getKind() != TypeKind.NONE) {
        TypeElement superTypeElement = (TypeElement) types.asElement(superType);
        if (namesEqual(superTypeElement, className)) {
            return true;
        }
        superType = superTypeElement.getSuperclass();
    }
    return false;
}
 
Example 6
Source File: RetroWeiboProcessor.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
private boolean ancestorIsRetroWeibo(TypeElement type) {
  while (true) {
    TypeMirror parentMirror = type.getSuperclass();
    if (parentMirror.getKind() == TypeKind.NONE) {
      return false;
    }
    Types typeUtils = processingEnv.getTypeUtils();
    TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
    if (parentElement.getAnnotation(RetroWeibo.class) != null) {
      return true;
    }
    type = parentElement;
  }
}
 
Example 7
Source File: TypeSimplifier.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Given a set of referenced types, works out which of them should be imported and what the
 * resulting spelling of each one is.
 *
 * <p>This method operates on a {@code Set<TypeMirror>} rather than just a {@code Set<String>}
 * because it is not strictly possible to determine what part of a fully-qualified type name is
 * the package and what part is the top-level class. For example, {@code java.util.Map.Entry} is a
 * class called {@code Map.Entry} in a package called {@code java.util} assuming Java conventions
 * are being followed, but it could theoretically also be a class called {@code Entry} in a
 * package called {@code java.util.Map}. Since we are operating as part of the compiler, our goal
 * should be complete correctness, and the only way to achieve that is to operate on the real
 * representations of types.
 *
 * @param codePackageName The name of the package where the class containing these references is
 *     defined. Other classes within the same package do not need to be imported.
 * @param referenced The complete set of declared types (classes and interfaces) that will be
 *     referenced in the generated code.
 * @param defined The complete set of declared types (classes and interfaces) that are defined
 *     within the scope of the generated class (i.e. nested somewhere in its superclass chain, or
 *     in its interface set)
 * @return a map where the keys are fully-qualified types and the corresponding values indicate
 *     whether the type should be imported, and how the type should be spelled in the source code.
 */
private static Map<String, Spelling> findImports(
    Elements elementUtils,
    Types typeUtils,
    String codePackageName,
    Set<TypeMirror> referenced,
    Set<TypeMirror> defined) {
  Map<String, Spelling> imports = new HashMap<>();
  Set<TypeMirror> typesInScope = new TypeMirrorSet();
  typesInScope.addAll(referenced);
  typesInScope.addAll(defined);
  Set<String> ambiguous = ambiguousNames(typeUtils, typesInScope);
  for (TypeMirror type : referenced) {
    TypeElement typeElement = (TypeElement) typeUtils.asElement(type);
    String fullName = typeElement.getQualifiedName().toString();
    String simpleName = typeElement.getSimpleName().toString();
    String pkg = packageNameOf(typeElement);
    boolean importIt;
    String spelling;
    if (ambiguous.contains(simpleName)) {
      importIt = false;
      spelling = fullName;
    } else if (pkg.equals("java.lang")) {
      importIt = false;
      spelling = javaLangSpelling(elementUtils, codePackageName, typeElement);
    } else if (pkg.equals(codePackageName)) {
      importIt = false;
      spelling = fullName.substring(pkg.isEmpty() ? 0 : pkg.length() + 1);
    } else {
      importIt = true;
      spelling = simpleName;
    }
    imports.put(fullName, new Spelling(spelling, importIt));
  }
  return imports;
}
 
Example 8
Source File: RetroFacebookProcessor.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
private boolean ancestorIsRetroFacebook(TypeElement type) {
  while (true) {
    TypeMirror parentMirror = type.getSuperclass();
    if (parentMirror.getKind() == TypeKind.NONE) {
      return false;
    }
    Types typeUtils = processingEnv.getTypeUtils();
    TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
    if (parentElement.getAnnotation(RetroFacebook.class) != null) {
      return true;
    }
    type = parentElement;
  }
}
 
Example 9
Source File: RetroFacebookProcessor.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
private boolean ancestorIsRetroFacebook(TypeElement type) {
  while (true) {
    TypeMirror parentMirror = type.getSuperclass();
    if (parentMirror.getKind() == TypeKind.NONE) {
      return false;
    }
    Types typeUtils = processingEnv.getTypeUtils();
    TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
    if (parentElement.getAnnotation(RetroFacebook.class) != null) {
      return true;
    }
    type = parentElement;
  }
}
 
Example 10
Source File: TypeSimplifier.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
/**
 * Given a set of referenced types, works out which of them should be imported and what the
 * resulting spelling of each one is.
 *
 * <p>This method operates on a {@code Set<TypeMirror>} rather than just a {@code Set<String>}
 * because it is not strictly possible to determine what part of a fully-qualified type name is
 * the package and what part is the top-level class. For example, {@code java.util.Map.Entry} is
 * a class called {@code Map.Entry} in a package called {@code java.util} assuming Java
 * conventions are being followed, but it could theoretically also be a class called {@code Entry}
 * in a package called {@code java.util.Map}. Since we are operating as part of the compiler, our
 * goal should be complete correctness, and the only way to achieve that is to operate on the real
 * representations of types.
 *
 * @param packageName The name of the package where the class containing these references is
 *     defined. Other classes within the same package do not need to be imported.
 * @param referenced The complete set of declared types (classes and interfaces) that will be
 *     referenced in the generated code.
 * @param defined The complete set of declared types (classes and interfaces) that are defined
 *     within the scope of the generated class (i.e. nested somewhere in its superclass chain,
 *     or in its interface set)
 * @return a map where the keys are fully-qualified types and the corresponding values indicate
 *     whether the type should be imported, and how the type should be spelled in the source code.
 */
private static Map<String, Spelling> findImports(
    Types typeUtils, String packageName, Set<TypeMirror> referenced, Set<TypeMirror> defined) {
  Map<String, Spelling> imports = new HashMap<String, Spelling>();
  Set<TypeMirror> typesInScope = new TypeMirrorSet();
  typesInScope.addAll(referenced);
  typesInScope.addAll(defined);
  Set<String> ambiguous = ambiguousNames(typeUtils, typesInScope);
  for (TypeMirror type : referenced) {
    TypeElement typeElement = (TypeElement) typeUtils.asElement(type);
    String fullName = typeElement.getQualifiedName().toString();
    String simpleName = typeElement.getSimpleName().toString();
    String pkg = packageNameOf(typeElement);
    boolean importIt;
    String spelling;
    if (ambiguous.contains(simpleName)) {
      importIt = false;
      spelling = fullName;
    } else if (pkg.equals(packageName) || pkg.equals("java.lang")) {
      importIt = false;
      spelling = fullName.substring(pkg.isEmpty() ? 0 : pkg.length() + 1);
    } else {
      importIt = true;
      spelling = simpleName;
    }
    imports.put(fullName, new Spelling(spelling, importIt));
  }
  return imports;
}
 
Example 11
Source File: ContentHeaderAnnotationValidator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private boolean isValidType(TypeMirror type)
{
    Types typeUtils = processingEnv.getTypeUtils();
    Elements elementUtils = processingEnv.getElementUtils();
    Element typeElement = typeUtils.asElement(type);

    if (VALID_PRIMITIVE_TYPES.contains(type.getKind()))
    {
        return true;
    }
    for (TypeKind primitive : VALID_PRIMITIVE_TYPES)
    {
        if (typeUtils.isSameType(type, typeUtils.boxedClass(typeUtils.getPrimitiveType(primitive)).asType()))
        {
            return true;
        }
    }
    if (typeElement != null && typeElement.getKind() == ElementKind.ENUM)
    {
        return true;
    }
    if (typeUtils.isSameType(type, elementUtils.getTypeElement("java.lang.String").asType()))
    {
        return true;
    }
    return false;
}
 
Example 12
Source File: AbstractAssignabilityChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected boolean isAssignable( TypeMirror from, TypeMirror to, Types types )
{
    Element element = types.asElement(to);
    boolean isGeneric = (element instanceof TypeElement)
            && ((TypeElement) element).getTypeParameters().size() != 0;
    return  !isGeneric && ( to instanceof DeclaredType );
}
 
Example 13
Source File: FromEntityBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getRelationClassName(CompilationController controller, ExecutableElement executableElement, boolean isFieldAccess) {
    TypeMirror passedReturnType = executableElement.getReturnType();
    if (TypeKind.DECLARED != passedReturnType.getKind() || !(passedReturnType instanceof DeclaredType)) {
        return null;
    }
    Types types = controller.getTypes();
    TypeMirror passedReturnTypeStripped = JpaControllerUtil.stripCollection((DeclaredType)passedReturnType, types);
    if (passedReturnTypeStripped == null) {
        return null;
    }
    TypeElement passedReturnTypeStrippedElement = (TypeElement) types.asElement(passedReturnTypeStripped);
    return passedReturnTypeStrippedElement.getSimpleName().toString();
}
 
Example 14
Source File: JUnit5TestGenerator.java    From netbeans with 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 15
Source File: TestGenerator.java    From netbeans with 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 16
Source File: JsfForm.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static void createTablesForRelated(CompilationController controller, TypeElement bean, int formType, String variable,
        String idProperty, boolean isInjection, StringBuffer stringBuffer, JpaControllerUtil.EmbeddedPkSupport embeddedPkSupport, String controllerClass, List<String> entities, String jsfUtilClass) {
    ExecutableElement methods [] = JpaControllerUtil.getEntityMethods(bean);
    String entityClass = bean.getQualifiedName().toString();
    String simpleClass = bean.getSimpleName().toString();
    String managedBean = JSFClientGenerator.getManagedBeanName(simpleClass);
    boolean fieldAccess = JpaControllerUtil.isFieldAccess(bean);
    //generate tables of objects with ToMany relationships
    if (formType == FORM_TYPE_DETAIL) {
        for (ExecutableElement method : methods) {
            String methodName = method.getSimpleName().toString();
            if (methodName.startsWith("get")) {
                int isRelationship = JpaControllerUtil.isRelationship(method, fieldAccess);
                String name = methodName.substring(3);
                String propName = JpaControllerUtil.getPropNameFromMethod(methodName);
                if (isRelationship == JpaControllerUtil.REL_TO_MANY) {
                    Types types = controller.getTypes();
                    TypeMirror t = method.getReturnType();
                    TypeMirror typeArgMirror = JpaControllerUtil.stripCollection(t, types);
                    TypeElement typeElement = (TypeElement)types.asElement(typeArgMirror);
                    if (typeElement != null) {
                        TypeElement tAsElement = (TypeElement) types.asElement(t);
                        boolean isCollectionTypeAssignableToSet = isCollectionTypeAssignableToSet(tAsElement);
                        String relatedClass = typeElement.getSimpleName().toString();
                        String relatedManagedBean = JSFClientGenerator.getManagedBeanName(relatedClass);
                        String tableVarName = getFreeTableVarName("item", entities); //NOI18N
                        stringBuffer.append("<h:outputText value=\"" + name + ":\" />\n");
                        stringBuffer.append("<h:panelGroup>\n");
                        stringBuffer.append("<h:outputText rendered=\"#{empty " + variable + "." + propName + "}\" value=\"(No Items)\"/>\n");
                        String valueAttribute = isCollectionTypeAssignableToSet ? variable + ".jsfcrud_transform[jsfcrud_class['" + jsfUtilClass + "'].jsfcrud_method.setToList][jsfcrud_null]." + propName : variable + "." + propName;
                        stringBuffer.append("<h:dataTable value=\"#{" + valueAttribute + "}\" var=\"" + tableVarName + "\" \n");
                        stringBuffer.append("border=\"0\" cellpadding=\"2\" cellspacing=\"0\" rowClasses=\"jsfcrud_odd_row,jsfcrud_even_row\" rules=\"all\" style=\"border:solid 1px\" \n rendered=\"#{not empty " + variable + "." + propName + "}\">\n"); //NOI18N

                        String commands = "<h:column>\n"
                                + "<f:facet name=\"header\">\n"
                                + "<h:outputText escape=\"false\" value=\"&nbsp;\"/>\n"
                                + "</f:facet>\n"
                                + "<h:commandLink value=\"Show\" action=\"#'{'" + relatedManagedBean + ".detailSetup'}'\">\n"
                                + "<f:param name=\"jsfcrud.current" + simpleClass + "\" value=\"#'{'jsfcrud_class[''" + jsfUtilClass + "''].jsfcrud_method[''getAsConvertedString''][" + variable + "][" + managedBean + ".converter].jsfcrud_invoke'}'\"/>\n"
                                + "<f:param name=\"jsfcrud.current" + relatedClass + "\" value=\"#'{'jsfcrud_class[''" + jsfUtilClass + "''].jsfcrud_method[''getAsConvertedString''][{0}][" + relatedManagedBean + ".converter].jsfcrud_invoke'}'\"/>\n"
                                + "<f:param name=\"jsfcrud.relatedController\" value=\"" + managedBean + "\" />\n"
                                + "<f:param name=\"jsfcrud.relatedControllerType\" value=\"" + controllerClass + "\" />\n"
                                + "</h:commandLink>\n"
                                + "<h:outputText value=\" \"/>\n"
                                + "<h:commandLink value=\"Edit\" action=\"#'{'" + relatedManagedBean + ".editSetup'}'\">\n"
                                + "<f:param name=\"jsfcrud.current" + simpleClass + "\" value=\"#'{'jsfcrud_class[''" + jsfUtilClass + "''].jsfcrud_method[''getAsConvertedString''][" + variable + "][" + managedBean + ".converter].jsfcrud_invoke'}'\"/>\n"
                                + "<f:param name=\"jsfcrud.current" + relatedClass + "\" value=\"#'{'jsfcrud_class[''" + jsfUtilClass + "''].jsfcrud_method[''getAsConvertedString''][{0}][" + relatedManagedBean + ".converter].jsfcrud_invoke'}'\"/>\n"
                                + "<f:param name=\"jsfcrud.relatedController\" value=\"" + managedBean + "\" />\n"
                                + "<f:param name=\"jsfcrud.relatedControllerType\" value=\"" + controllerClass + "\" />\n"
                                + "</h:commandLink>\n"
                                + "<h:outputText value=\" \"/>\n"
                                + "<h:commandLink value=\"Destroy\" action=\"#'{'" + relatedManagedBean + ".destroy'}'\">\n"
                                + "<f:param name=\"jsfcrud.current" + simpleClass + "\" value=\"#'{'jsfcrud_class[''" + jsfUtilClass + "''].jsfcrud_method[''getAsConvertedString''][" + variable + "][" + managedBean + ".converter].jsfcrud_invoke'}'\"/>\n"
                                + "<f:param name=\"jsfcrud.current" + relatedClass + "\" value=\"#'{'jsfcrud_class[''" + jsfUtilClass + "''].jsfcrud_method[''getAsConvertedString''][{0}][" + relatedManagedBean + ".converter].jsfcrud_invoke'}'\"/>\n"
                                + "<f:param name=\"jsfcrud.relatedController\" value=\"" + managedBean + "\" />\n"
                                + "<f:param name=\"jsfcrud.relatedControllerType\" value=\"" + controllerClass + "\" />\n"
                                + "</h:commandLink>\n"
                                + "</h:column>\n";

                        JsfTable.createTable(controller, typeElement, variable + "." + propName, stringBuffer, commands, embeddedPkSupport, tableVarName);
                        stringBuffer.append("</h:dataTable>\n");
                        stringBuffer.append("</h:panelGroup>\n");
                    } else {
                        Logger.getLogger(JsfForm.class.getName()).log(Level.INFO, "cannot find referenced class: " + method.getReturnType()); // NOI18N
                    }
                }
            }
        }
    }
}
 
Example 17
Source File: ThrowableInitCause.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static ErrorDescription initCause(HintContext ctx, boolean toThrow) {
    TypeElement throwable = ctx.getInfo().getElements().getTypeElement("java.lang.Throwable");

    if (throwable == null) return null;

    TreePath exc = ctx.getVariables().get("$exc");
    TypeMirror excType = ctx.getInfo().getTrees().getTypeMirror(exc);
    Types t = ctx.getInfo().getTypes();

    if (!t.isSubtype(t.erasure(excType), t.erasure(throwable.asType()))) {
        return null;
    }

    Element el = t.asElement(excType);

    if (el == null || el.getKind() != ElementKind.CLASS) {
        //should not happen
        return null;
    }

    List<TypeMirror> constrParams = new LinkedList<TypeMirror>();
    TreePath str = ctx.getVariables().get("$str");
    String target;

    if (   (str != null && (   MatcherUtilities.matches(ctx, str, "$del.toString()")
                            || (    MatcherUtilities.matches(ctx, str, "$del.getMessage()")
                                && !ctx.getPreferences().getBoolean(STRICT_KEY, STRICT_DEFAULT))
                            || (    MatcherUtilities.matches(ctx, str, "$del.getLocalizedMessage()")
                                && !ctx.getPreferences().getBoolean(STRICT_KEY, STRICT_DEFAULT)))
        || (str == null && !ctx.getPreferences().getBoolean(STRICT_KEY, STRICT_DEFAULT)))) {
        target = "new $exc($del)";
    } else {
        TypeElement jlString = ctx.getInfo().getElements().getTypeElement("java.lang.String");

        if (jlString == null) return null;

        constrParams.add(jlString.asType());

        if (str != null) {
            target = "new $exc($str, $del)";
        } else {
            target = "new $exc(null, $del)"; //TODO: might lead to incompilable code (for overloaded constructors)
        }
    }

    if (toThrow) {
        target = "throw " + target + ";";
    }

    TreePath del = ctx.getVariables().get("$del");
    TypeMirror delType = ctx.getInfo().getTrees().getTypeMirror(del);

    constrParams.add(delType);

    if (!findConstructor(el, t, constrParams)) return null;

    String fixDisplayName = NbBundle.getMessage(ThrowableInitCause.class, "FIX_ThrowableInitCause");
    String displayName = NbBundle.getMessage(ThrowableInitCause.class, "ERR_ThrowableInitCause");
    TreePath toUnderline = ctx.getVariables().get("$excVar");

    if (toUnderline == null) {
        toUnderline = ctx.getPath();
    }

    return ErrorDescriptionFactory.forTree(ctx, toUnderline, displayName, JavaFixUtilities.rewriteFix(ctx, fixDisplayName, ctx.getPath(), target));
}
 
Example 18
Source File: PullUpTransformer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private <E extends Tree> E fixGenericTypes(E tree, final TreePath path, final Element member) {
    final Map<TypeMirror, TypeParameterElement> mappings = new HashMap<TypeMirror, TypeParameterElement>();
    DeclaredType declaredType = (DeclaredType) sourceType.asType();
    for (TypeMirror typeMirror : declaredType.getTypeArguments()) {
        DeclaredType currentElement = declaredType;
        deepSearchTypes(currentElement, typeMirror, typeMirror, mappings);
    }
    final Types types = workingCopy.getTypes();

    final Map<IdentifierTree, Tree> original2Translated = new HashMap<IdentifierTree, Tree>();
    ErrorAwareTreeScanner<Void, Void> scanner = new ErrorAwareTreeScanner<Void, Void>() {

        @Override
        public Void visitIdentifier(IdentifierTree node, Void p) {
            Element element = workingCopy.getTrees().getElement(new TreePath(path, node));
            if (element != null && element.getKind() == ElementKind.TYPE_PARAMETER) {
                Element typeElement = types.asElement(element.asType());
                if (typeElement != null && typeElement.getKind() == ElementKind.TYPE_PARAMETER) {
                    TypeParameterElement parameterElement = (TypeParameterElement) typeElement;
                    Element genericElement = parameterElement.getGenericElement();
                    if (genericElement != member) {
                        // genericElement is niet gelijk aan het te verplaatsen element. Dus we moeten deze veranderen.
                        // Is het parameterElement gebruikt bij het maken van de superclass

                        Tree type;
                        TypeParameterElement target = mappings.get(parameterElement.asType());
                        if (target != null) {
                            type = make.Type(target.asType());
                        } else {
                            List<? extends TypeMirror> bounds = parameterElement.getBounds();
                            if (bounds.isEmpty()) {
                                type = make.Type("Object"); // NOI18N
                            } else {
                                type = make.Type(bounds.get(0));
                            }
                        }
                        original2Translated.put(node, type);
                    }
                }
            }
            return super.visitIdentifier(node, p);
        }
    };
    scanner.scan(tree, null);
    E result = (E) workingCopy.getTreeUtilities().translate(tree, original2Translated);
    return result;
}
 
Example 19
Source File: JavaSourceParserUtil.java    From jeddict with Apache License 2.0 4 votes vote down vote up
public static ExecutableElement getOtherSideOfRelation(CompilationController controller, ExecutableElement executableElement, boolean isFieldAccess) {
    TypeMirror passedReturnType = executableElement.getReturnType();
    if (TypeKind.DECLARED != passedReturnType.getKind() || !(passedReturnType instanceof DeclaredType)) {
        return null;
    }
    Types types = controller.getTypes();
    TypeMirror passedReturnTypeStripped = stripCollection((DeclaredType) passedReturnType, types);
    if (passedReturnTypeStripped == null) {
        return null;
    }
    TypeElement passedReturnTypeStrippedElement = (TypeElement) types.asElement(passedReturnTypeStripped);

    //try to find a mappedBy annotation element on the possiblyAnnotatedElement
    Element possiblyAnnotatedElement = isFieldAccess ? JavaSourceParserUtil.guessField(executableElement) : executableElement;
    String mappedBy = null;
    AnnotationMirror persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, ONE_TO_ONE_FQN);  //NOI18N"
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, ONE_TO_MANY_FQN);  //NOI18N"
    }
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, MANY_TO_ONE_FQN);  //NOI18N"
    }
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JavaSourceParserUtil.findAnnotation(possiblyAnnotatedElement, MANY_TO_MANY_FQN);  //NOI18N"
    }
    if (persistenceAnnotation != null) {
        mappedBy = JavaSourceParserUtil.findAnnotationValueAsString(persistenceAnnotation, "mappedBy");  //NOI18N
    }
    for (ExecutableElement method : JavaSourceParserUtil.getMethods(passedReturnTypeStrippedElement)) {
        if (mappedBy != null && mappedBy.length() > 0) {
            String tail = mappedBy.length() > 1 ? mappedBy.substring(1) : "";
            String getterName = "get" + mappedBy.substring(0, 1).toUpperCase() + tail;
            if (getterName.equals(method.getSimpleName().toString())) {
                return method;
            }
        } else {
            TypeMirror iteratedReturnType = method.getReturnType();
            iteratedReturnType = stripCollection(iteratedReturnType, types);
            TypeMirror executableElementEnclosingType = executableElement.getEnclosingElement().asType();
            if (types.isSameType(executableElementEnclosingType, iteratedReturnType)) {
                return method;
            }
        }
    }
    return null;
}
 
Example 20
Source File: JpaControllerUtil.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static ExecutableElement getOtherSideOfRelation(CompilationController controller, ExecutableElement executableElement, boolean isFieldAccess) {
    TypeMirror passedReturnType = executableElement.getReturnType();
    if (TypeKind.DECLARED != passedReturnType.getKind() || !(passedReturnType instanceof DeclaredType)) {
        return null;
    }
    Types types = controller.getTypes();
    TypeMirror passedReturnTypeStripped = stripCollection((DeclaredType)passedReturnType, types);
    if (passedReturnTypeStripped == null) {
        return null;
    }
    TypeElement passedReturnTypeStrippedElement = (TypeElement) types.asElement(passedReturnTypeStripped);
    
    //try to find a mappedBy annotation element on the possiblyAnnotatedElement
    Element possiblyAnnotatedElement = isFieldAccess ? JpaControllerUtil.guessField(executableElement) : executableElement;
    String mappedBy = null;
    AnnotationMirror persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.OneToOne");  //NOI18N"
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.OneToMany");  //NOI18N"
    }
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.ManyToOne");  //NOI18N"
    }
    if (persistenceAnnotation == null) {
        persistenceAnnotation = JpaControllerUtil.findAnnotation(possiblyAnnotatedElement, "javax.persistence.ManyToMany");  //NOI18N"
    }
    if (persistenceAnnotation != null) {
        mappedBy = JpaControllerUtil.findAnnotationValueAsString(persistenceAnnotation, "mappedBy");  //NOI18N
    }
    for (ExecutableElement method : JpaControllerUtil.getEntityMethods(passedReturnTypeStrippedElement)) {
        if (mappedBy != null && mappedBy.length() > 0) {
            String tail = mappedBy.length() > 1 ? mappedBy.substring(1) : "";
            String getterName = "get" + mappedBy.substring(0,1).toUpperCase() + tail;
            if (getterName.equals(method.getSimpleName().toString())) {
                return method;
            }
        }
        else {
            TypeMirror iteratedReturnType = method.getReturnType();
            iteratedReturnType = stripCollection(iteratedReturnType, types);
            TypeMirror executableElementEnclosingType = executableElement.getEnclosingElement().asType();
            if (types.isSameType(executableElementEnclosingType, iteratedReturnType)) {
                return method;
            }
        }
    }
    return null;
}