javax.lang.model.element.VariableElement Java Examples

The following examples show how to use javax.lang.model.element.VariableElement. 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 Project: netbeans   Author: apache   File: ElementUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isHidden(Element member, List<? extends Element> members, Elements elements, Types types) {
    for (ListIterator<? extends Element> it = members.listIterator(); it.hasNext();) {
        Element hider = it.next();
        if (hider == member)
            return true;
        if (hider.getSimpleName().contentEquals(member.getSimpleName())) {
            if (elements.hides(member, hider)) {
                it.remove();
            } else {
                if (member instanceof VariableElement && hider instanceof VariableElement
                        && (!member.getKind().isField() || hider.getKind().isField()))
                    return true;
                TypeMirror memberType = member.asType();
                TypeMirror hiderType = hider.asType();
                if (memberType.getKind() == TypeKind.EXECUTABLE && hiderType.getKind() == TypeKind.EXECUTABLE) {
                    if (types.isSubsignature((ExecutableType)hiderType, (ExecutableType)memberType))
                        return true;
                } else {
                    return false;
                }
            }
        }
    }
    return false;
}
 
Example #2
Source Project: pandroid   Author: MobileTribe   File: GeneratedClassMapperProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void extractInjectMethod(TypeElement typeElement) {

        ComponentBlock currentBlock = new ComponentBlock(typeElement.asType());
        for (Element content : typeElement.getEnclosedElements()) {
            if (content.getKind().equals(ElementKind.METHOD) && content.getSimpleName().toString().startsWith("inject")) {
                ExecutableElement method = (ExecutableElement) content;
                if (method.getParameters().size() == 1) {
                    VariableElement variableElement = method.getParameters().get(0);
                    TypeMirror paramType = mTypesUtils.erasure(variableElement.asType());
                    currentBlock.injects.add(new InjectBlock(paramType));
                }
            }
        }

        if (!currentBlock.injects.isEmpty())
            componentBlocks.add(currentBlock);

    }
 
Example #3
Source Project: netbeans   Author: apache   File: IdxPropertyPattern.java    License: Apache License 2.0 6 votes vote down vote up
public IdxPropertyPattern(PatternAnalyser analyser, 
                          ExecutableElement getterMethod,
                          ExecutableElement setterMethod,
                          ExecutableElement indexedGetterMethod, 
                          ExecutableElement indexedSetterMethod,
                          VariableElement estimatedField,
                          TypeMirror type,
                          TypeMirror indexedType,
                          String name) throws IntrospectionException {
    super( analyser, getterMethod, setterMethod, estimatedField, type, name );
    
    this.indexedGetterMethod = indexedGetterMethod == null ? null : ElementHandle.create(indexedGetterMethod);
    this.indexedSetterMethod = indexedSetterMethod == null ? null : ElementHandle.create(indexedSetterMethod);
    this.indexedType = TypeMirrorHandle.create(indexedType);
    this.indexedTypeName = typeAsString(indexedType);
}
 
Example #4
Source Project: netbeans   Author: apache   File: NPECheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public State visitInstanceOf(InstanceOfTree node, Void p) {
    super.visitInstanceOf(node, p);
    
    Element e = info.getTrees().getElement(new TreePath(getCurrentPath(), node.getExpression()));

    if (isVariableElement(e)) {
        boolean setState = false;
        State currentState = variable2State.get((VariableElement) e);
        if (currentState == null) {
            setState = !getStateFromAnnotations(info, e).isNotNull();
        } else {
            setState = !variable2State.get((VariableElement) e).isNotNull();
        }
        if (setState) {
            variable2State.put((VariableElement) e, not ? State.INSTANCE_OF_FALSE : State.INSTANCE_OF_TRUE);
        }
    }
    
    return null;
}
 
Example #5
Source Project: netbeans   Author: apache   File: NPECheck.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Records continuation to the exception handler if a throwable is raised.
 * Optimization: the resumeOnExceptionHandler must contain an entry for the
 * throwable and/or its superclass. If not, then no enclosing catch handler
 * is interested in the Throwable and no state snapshot is necessary.
 * 
 * @param thrown thrown exception type
 */
private void recordResumeOnExceptionHandler(TypeMirror thrown, Map<VariableElement, State> variable2State) {
    
    TypeMirror curT = thrown;
    
    do {
        if (curT == null || curT.getKind() != TypeKind.DECLARED) return;
        DeclaredType dtt = (DeclaredType)curT;
        // hack; getSuperclass may provide different type instance for the same element.
        thrown = dtt.asElement().asType();
        Map<VariableElement, State> r = resumeOnExceptionHandler.get(thrown);
        if (r != null) {
            mergeInto(r, variable2State);
            break;
        }
        TypeElement tel = (TypeElement)dtt.asElement();
        if (tel == throwableEl) {
            break;
        }
        curT = tel.getSuperclass();
    } while (curT != null);
}
 
Example #6
Source Project: netbeans   Author: apache   File: InjectionPointParameterAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
private void checkName( ExecutableElement element, VariableElement var,
        WebBeansModel model, Result result)
{
    AnnotationMirror annotation = AnnotationUtil.getAnnotationMirror( 
            var , AnnotationUtil.NAMED, model.getCompilationController());
    if ( annotation!= null){
        result.addNotification( Severity.WARNING , var, element , model,  
                    NbBundle.getMessage(InjectionPointAnalyzer.class, 
                            "WARN_NamedInjectionPoint"));                       // NOI18N
        if ( annotation.getElementValues().size() == 0 ){
            result.addError(var, element,  model, 
                    NbBundle.getMessage( InjectionPointParameterAnalyzer.class, 
                            "ERR_ParameterNamedInjectionPoint"));        // NOI18N
        }
    }
}
 
Example #7
Source Project: netbeans   Author: apache   File: _RetoucheUtil.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static ElementHandle<VariableElement> getFieldHandle(JavaSource javaSource, final String className, final String fieldType, final String fieldName) throws IOException {

    final ElementHandle[] result = new ElementHandle[1];

    javaSource.runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController controller) throws IOException {
            controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            TypeElement typeElement = controller.getElements().getTypeElement(className);
            for (VariableElement variable : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
                if (variable.getSimpleName().contentEquals(fieldName) && fieldType.equals(getTypeName(controller, variable.asType()))) {
                    result[0] = ElementHandle.create(variable);
                    return;
                }
            }
        }
    }, true);

    return result[0];
}
 
Example #8
Source Project: openjdk-8   Author: bpupadhyaya   File: TypeModeler.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
    TypeElement typeElement = getDeclaration(type);
    if (typeElement == null)
        return null;

    if (isSubElement(typeElement, defHolder)) {
        if (type.getKind().equals(TypeKind.DECLARED)) {
            Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
            if (argTypes.size() == 1) {
                return argTypes.iterator().next();
            } else if (argTypes.isEmpty()) {
                VariableElement member = getValueMember(typeElement);
                if (member != null) {
                    return member.asType();
                }
            }
        }
    }
    return null;
}
 
Example #9
Source Project: j2objc   Author: google   File: TypeImplementationGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private String getJniFunctionSignature(FunctionDeclaration function) {
  StringBuilder sb = new StringBuilder();
  sb.append(nameTable.getJniType(function.getReturnType().getTypeMirror()));
  sb.append(' ');
  sb.append(function.getJniSignature()).append('(');
  sb.append("JNIEnv *_env_");
  if (Modifier.isStatic(function.getModifiers())) {
    sb.append(", jclass _cls_");
  }
  if (!function.getParameters().isEmpty()) {
    sb.append(", ");
  }
  for (Iterator<SingleVariableDeclaration> iter = function.getParameters().iterator();
       iter.hasNext(); ) {
    VariableElement var = iter.next().getVariableElement();
    String paramType = nameTable.getJniType(var.asType());
    sb.append(paramType + ' ' + nameTable.getVariableBaseName(var));
    if (iter.hasNext()) {
      sb.append(", ");
    }
  }
  sb.append(')');
  return sb.toString();
}
 
Example #10
Source Project: dagger2-sample   Author: yongjhih   File: InjectFieldValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ValidationReport<VariableElement> validate(VariableElement fieldElement) {
  ValidationReport.Builder<VariableElement> builder =
      ValidationReport.Builder.about(fieldElement);
  Set<Modifier> modifiers = fieldElement.getModifiers();
  if (modifiers.contains(FINAL)) {
    builder.addItem(FINAL_INJECT_FIELD, fieldElement);
  }

  if (modifiers.contains(PRIVATE)) {
    builder.addItem(PRIVATE_INJECT_FIELD, fieldElement);
  }

  ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(fieldElement);
  if (qualifiers.size() > 1) {
    for (AnnotationMirror qualifier : qualifiers) {
      builder.addItem(MULTIPLE_QUALIFIERS, fieldElement, qualifier);
    }
  }

  return builder.build();
}
 
Example #11
Source Project: j2objc   Author: google   File: GraphBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void followFields(DeclaredType type, TypeNode node) {
  TypeElement element = (TypeElement) type.asElement();
  for (VariableElement field : ElementUtil.getDeclaredFields(element)) {
    TypeMirror fieldType = getElementType(typeUtil.asMemberOf(type, field));
    TypeNode target = getOrCreateNode(fieldType);
    String fieldName = ElementUtil.getName(field);
    if (target != null
        && !whitelist.containsField(node, fieldName)
        && !whitelist.containsType(target)
        && !ElementUtil.isStatic(field)
        // Exclude self-referential fields. (likely linked DS or delegate pattern)
        && !typeUtil.isAssignable(type, fieldType)
        && !isWeakReference(field)
        && !isRetainedWithField(field)) {
      addEdge(Edge.newFieldEdge(node, target, fieldName));
    }
  }
}
 
Example #12
Source Project: j2objc   Author: google   File: HeaderImportCollector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(MethodDeclaration node) {
  if (filter.include(node)) {
    addForwardDecl(node.getReturnTypeMirror());
    for (VariableElement param : node.getExecutableElement().getParameters()) {
      addForwardDecl(param.asType());
    }
  }
  return false;
}
 
Example #13
Source Project: netbeans   Author: apache   File: JavaElementHandler.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSignature getSignature(TypeElement classElement, ExecutableElement element, String[] typeParameters, Types types) {
            String name = element.getSimpleName().toString();
            String[] parameters = new String[element.getParameters().size()];

            for (int i = 0; i < parameters.length; i++) {
                VariableElement var = element.getParameters().get(i);
                TypeMirror type = var.asType();
                String typeString = null;

                if (type.getKind() == TypeKind.TYPEVAR) {
                    List<? extends TypeParameterElement> declaredTypeParameters = element.getTypeParameters();
                    if (declaredTypeParameters.isEmpty()) {
                        declaredTypeParameters = classElement.getTypeParameters();
                    }
                    int j = -1;
                    for (TypeParameterElement typeParam : declaredTypeParameters) {
                        j++;
                        if (typeParam.getSimpleName().toString().equals(type.toString())) {
                            break;
                        }
                    }
// FIXME why we were doing this for signatures ??
//                    if (j >= 0 && j < typeParameters.length) {
//                        typeString = typeParameters[j];
//                    } else {
                        typeString = types.erasure(type).toString();
//                    }
                } else {
                    typeString = type.toString();
                }

                int index = typeString.indexOf('<');
                if (index >= 0) {
                    typeString = typeString.substring(0, index);
                }
                parameters[i] = typeString;
            }
            return new MethodSignature(name, parameters);
        }
 
Example #14
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: JNIWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
String signature(ExecutableElement e) {
    StringBuilder sb = new StringBuilder("(");
    String sep = "";
    for (VariableElement p: e.getParameters()) {
        sb.append(sep);
        sb.append(types.erasure(p.asType()).toString());
        sep = ",";
    }
    sb.append(")");
    return sb.toString();
}
 
Example #15
Source Project: netbeans   Author: apache   File: ConvertAnonymousToInner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitIdentifier(IdentifierTree node, Set<VariableElement> p) {
    Element el = info.getTrees().getElement(getCurrentPath());
    TreePath elPath = el != null ? info.getTrees().getPath(el) : null;
    
    if (el != null && elPath != null && VARIABLES.contains(el.getKind()) && !isParent(newClassToConvert, elPath)) {
        p.add((VariableElement) el);
    }
    
    return super.visitIdentifier(node, p);
}
 
Example #16
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: WebServiceVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected boolean isLegalSei(TypeElement interfaceElement) {
    for (VariableElement field : ElementFilter.fieldsIn(interfaceElement.getEnclosedElements()))
        if (field.getConstantValue() != null) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_SEI_CANNOT_CONTAIN_CONSTANT_VALUES(
                    interfaceElement.getQualifiedName(), field.getSimpleName()));
            return false;
        }
    return methodsAreLegal(interfaceElement);
}
 
Example #17
Source Project: doma   Author: domaframework   File: MoreElements.java    License: Apache License 2.0 5 votes vote down vote up
public VariableElement getSingleParameterOfRecordConstructor(TypeElement record) {
  if (!ElementKindUtil.isRecord(record.getKind())) {
    throw new AptIllegalStateException(record.getQualifiedName() + " must be a record type.");
  }
  return ElementFilter.constructorsIn(record.getEnclosedElements()).stream()
      .filter(c -> c.getModifiers().contains(Modifier.PUBLIC))
      .filter(c -> c.getParameters().size() == 1)
      .flatMap(c -> c.getParameters().stream())
      .findFirst()
      .orElse(null);
}
 
Example #18
Source Project: netbeans   Author: apache   File: ElementNode.java    License: Apache License 2.0 5 votes vote down vote up
private static String createHtmlHeader(boolean deprecated, VariableElement e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    if (deprecated) sb.append("<s>");
    sb.append(e.getSimpleName());
    if (deprecated) sb.append("</s>");
    if ( e.getKind() != ElementKind.ENUM_CONSTANT ) {
        sb.append( " : " ); // NOI18N
        sb.append(translateToHTML(print(e.asType())));
    }
    return sb.toString();
}
 
Example #19
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: JavahTask.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void checkMethodParameters(Set<TypeElement> classes) {
    Types types = processingEnv.getTypeUtils();
    for (TypeElement te: classes) {
        for (ExecutableElement ee: ElementFilter.methodsIn(te.getEnclosedElements())) {
            for (VariableElement ve: ee.getParameters()) {
                TypeMirror tm = ve.asType();
                checkMethodParametersVisitor.visit(tm, types);
            }
        }
    }
}
 
Example #20
Source Project: hottub   Author: dsrg-uoft   File: WebServiceVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected boolean isLegalParameter(VariableElement param,
                                   ExecutableElement method,
                                   TypeElement typeElement,
                                   int paramIndex) {
    if (!isLegalType(param.asType())) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_PARAMETER_TYPES_CANNOT_IMPLEMENT_REMOTE(typeElement.getQualifiedName(),
                method.getSimpleName(),
                param.getSimpleName(),
                param.asType().toString()), param);
        return false;
    }
    TypeMirror holderType;
    holderType = builder.getHolderValueType(param.asType());
    WebParam webParam = param.getAnnotation(WebParam.class);
    WebParam.Mode mode = null;
    if (webParam != null)
        mode = webParam.mode();

    if (holderType != null) {
        if (mode != null && mode == WebParam.Mode.IN)
            builder.processError(WebserviceapMessages.WEBSERVICEAP_HOLDER_PARAMETERS_MUST_NOT_BE_IN_ONLY(typeElement.getQualifiedName(), method.toString(), paramIndex), param);
    } else if (mode != null && mode != WebParam.Mode.IN) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_NON_IN_PARAMETERS_MUST_BE_HOLDER(typeElement.getQualifiedName(), method.toString(), paramIndex), param);
    }

    return true;
}
 
Example #21
Source Project: j2objc   Author: google   File: Rewriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(QualifiedName node) {
  VariableElement var = TreeUtil.getVariableElement(node);
  Expression qualifier = node.getQualifier();
  if (var != null && var.getKind().isField() && TreeUtil.getVariableElement(qualifier) != null) {
    // FieldAccess nodes are more easily mutated than QualifiedName.
    FieldAccess fieldAccess =
        new FieldAccess(var, node.getTypeMirror(), TreeUtil.remove(qualifier));
    node.replaceWith(fieldAccess);
    fieldAccess.accept(this);
    return false;
  }
  return true;
}
 
Example #22
Source Project: auto   Author: google   File: FactoryDescriptorGenerator.java    License: Apache License 2.0 5 votes vote down vote up
FactoryMethodDescriptor generateDescriptorForConstructor(final AutoFactoryDeclaration declaration,
    ExecutableElement constructor) {
  checkNotNull(constructor);
  checkArgument(constructor.getKind() == ElementKind.CONSTRUCTOR);
  TypeElement classElement = MoreElements.asType(constructor.getEnclosingElement());
  ImmutableListMultimap<Boolean, ? extends VariableElement> parameterMap =
      Multimaps.index(constructor.getParameters(), Functions.forPredicate(
          new Predicate<VariableElement>() {
            @Override
            public boolean apply(VariableElement parameter) {
              return isAnnotationPresent(parameter, Provided.class);
            }
          }));
  ImmutableSet<Parameter> providedParameters =
      Parameter.forParameterList(parameterMap.get(true), types);
  ImmutableSet<Parameter> passedParameters =
      Parameter.forParameterList(parameterMap.get(false), types);
  return FactoryMethodDescriptor.builder(declaration)
      .name("create")
      .returnType(classElement.asType())
      .publicMethod(classElement.getModifiers().contains(PUBLIC))
      .providedParameters(providedParameters)
      .passedParameters(passedParameters)
      .creationParameters(Parameter.forParameterList(constructor.getParameters(), types))
      .isVarArgs(constructor.isVarArgs())
      .build();
}
 
Example #23
Source Project: reductor   Author: Yarikx   File: AutoReducerProcessingStep.java    License: Apache License 2.0 5 votes vote down vote up
private void emitActionCreator(StringReducerElement reducerElement, String packageName) throws IOException {
    TypeSpec.Builder actionCreatorBuilder = TypeSpec.interfaceBuilder(reducerElement.getSimpleName() + "Actions")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(ActionCreator.class);

    boolean hasActions = false;
    for (ReduceAction action : reducerElement.actions) {
        if (!action.generateActionCreator) continue;
        hasActions = true;
        final List<VariableElement> args = action.args;

        String fieldName = action.action.replaceAll(" +", "_").toUpperCase();
        actionCreatorBuilder.addField(FieldSpec.builder(String.class, fieldName)
                .addModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.PUBLIC)
                .initializer("\"$L\"", action.action)
                .build());

        MethodSpec.Builder actionCreatorMethodBuilder = MethodSpec.methodBuilder(action.getMethodName())
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .addAnnotation(AnnotationSpec.builder(ActionCreator.Action.class)
                        .addMember("value", "$N", fieldName)
                        .build())
                .returns(Action.class);

        if (!args.isEmpty()) {
            for (VariableElement arg : args) {
                actionCreatorMethodBuilder.addParameter(TypeName.get(arg.asType()), arg.getSimpleName().toString());
            }
        }
        actionCreatorBuilder.addMethod(actionCreatorMethodBuilder.build());

    }
    if (hasActions) {
        JavaFile.builder(packageName, actionCreatorBuilder.build())
                .skipJavaLangImports(true)
                .addFileComment(createGeneratedFileComment())
                .build()
                .writeTo(env.getFiler());
    }
}
 
Example #24
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: VisibleMemberMap.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void addToPropertiesMap(ExecutableElement setter,
                                ExecutableElement getter,
                                ExecutableElement propertyMethod,
                                VariableElement field) {
    if (field == null || utils.getDocCommentTree(field) == null) {
        addToPropertiesMap(setter, propertyMethod);
        addToPropertiesMap(getter, propertyMethod);
        addToPropertiesMap(propertyMethod, propertyMethod);
    } else {
        addToPropertiesMap(getter, field);
        addToPropertiesMap(setter, field);
        addToPropertiesMap(propertyMethod, field);
    }
}
 
Example #25
Source Project: netbeans   Author: apache   File: InjectionPointParameterAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
private TypeMirror getParameterType( VariableElement var,
        ExecutableElement element, TypeElement parent , 
        CompilationController controller )
{
    ExecutableType method = (ExecutableType)controller.getTypes().asMemberOf(
            (DeclaredType)parent.asType(), element);
    List<? extends TypeMirror> parameterTypes = method.getParameterTypes();
    List<? extends VariableElement> parameters = element.getParameters();
    int paramIndex = parameters.indexOf(var);
    return parameterTypes.get(paramIndex);
}
 
Example #26
Source Project: Ollie   Author: pardom-zz   File: ColumnElement.java    License: Apache License 2.0 5 votes vote down vote up
public ColumnElement(Registry registry, TypeElement enclosingType, VariableElement element) {
	this.element = element;
	this.column = element.getAnnotation(Column.class);
	this.enclosingType = enclosingType;
	this.deserializedType = registry.getElements().getTypeElement(element.asType().toString());

	final TypeAdapterElement typeAdapterElement = registry.getTypeAdapterElement(deserializedType);
	final TypeElement modelElement = registry.getElements().getTypeElement("ollie.Model");
	final DeclaredType modelType = registry.getTypes().getDeclaredType(modelElement);
	isModel = registry.getTypes().isAssignable(element.asType(), modelType);

	if (isModel) {
		final Table table = deserializedType.getAnnotation(Table.class);
		serializedType = registry.getElements().getTypeElement(Long.class.getName());
		modelTableName = table.value();
	} else if (typeAdapterElement != null) {
		serializedType = typeAdapterElement.getSerializedType();
	} else {
		serializedType = deserializedType;
	}

	this.sqlType = SQL_TYPE_MAP.get(getSerializedQualifiedName());

	List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
	for (AnnotationMirror annotationMirror : annotationMirrors) {
		try {
			Class annotationClass = Class.forName(annotationMirror.getAnnotationType().toString());
			annotations.put(annotationClass, element.getAnnotation(annotationClass));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
 
Example #27
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: JavaCompilerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public J2SJAXBModel bind(
    Collection<Reference> rootClasses,
    Map<QName,Reference> additionalElementDecls,
    String defaultNamespaceRemap,
    ProcessingEnvironment env) {

    ModelBuilder<TypeMirror, TypeElement, VariableElement, ExecutableElement> builder =
            new ModelBuilder<TypeMirror, TypeElement, VariableElement, ExecutableElement>(
            InlineAnnotationReaderImpl.theInstance,
            new ApNavigator(env),
            Collections.<TypeElement, TypeElement>emptyMap(),
            defaultNamespaceRemap );

    builder.setErrorHandler(new ErrorHandlerImpl(env.getMessager()));

    for ( Reference ref : rootClasses ) {
        TypeMirror t = ref.type;

        XmlJavaTypeAdapter xjta = ref.annotations.getAnnotation(XmlJavaTypeAdapter.class);
        XmlList xl = ref.annotations.getAnnotation(XmlList.class);

        builder.getTypeInfo(new Ref<TypeMirror, TypeElement>(builder, t, xjta, xl));
    }

    TypeInfoSet<TypeMirror, TypeElement, VariableElement, ExecutableElement> r = builder.link();
    if(r==null)     return null;

    if(additionalElementDecls==null)
        additionalElementDecls = Collections.emptyMap();
    else {
        // fool proof check
        for (Map.Entry<QName, ? extends Reference> e : additionalElementDecls.entrySet()) {
            if(e.getKey()==null)
                throw new IllegalArgumentException("nulls in additionalElementDecls");
        }
    }
    return new JAXBModelImpl(r, builder.reader, rootClasses, new HashMap<QName, Reference>(additionalElementDecls));
}
 
Example #28
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: WebServiceVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected boolean isValidOneWayMethod(ExecutableElement method, TypeElement typeElement) {
    boolean valid = true;
    if (!(method.getReturnType().accept(NO_TYPE_VISITOR, null))) {
        // this is an error, cannot be OneWay and have a return type
        builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_OPERATION_CANNOT_HAVE_RETURN_TYPE(typeElement.getQualifiedName(), method.toString()), method);
        valid = false;
    }
    VariableElement outParam = getOutParameter(method);
    if (outParam != null) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_AND_OUT(typeElement.getQualifiedName(), method.toString()), outParam);
        valid = false;
    }
    if (!isDocLitWrapped() && soapStyle.equals(SOAPStyle.DOCUMENT)) {
        int inCnt = getModeParameterCount(method, WebParam.Mode.IN);
        if (inCnt != 1) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_AND_NOT_ONE_IN(typeElement.getQualifiedName(), method.toString()), method);
            valid = false;
        }
    }
    for (TypeMirror thrownType : method.getThrownTypes()) {
        TypeElement thrownElement = (TypeElement) ((DeclaredType) thrownType).asElement();
        if (builder.isServiceException(thrownType)) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_ONEWAY_OPERATION_CANNOT_DECLARE_EXCEPTIONS(
                    typeElement.getQualifiedName(), method.toString(), thrownElement.getQualifiedName()), method);
            valid = false;
        }
    }
    return valid;
}
 
Example #29
Source Project: j2objc   Author: google   File: NilCheckResolver.java    License: Apache License 2.0 5 votes vote down vote up
private void addSafeVars(Set<VariableElement> vars) {
  if (scope != null && vars != null) {
    for (VariableElement var : vars) {
      scope.vars.put(var, true);
    }
  }
}
 
Example #30
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: SerializedFormBuilder.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build the serial UID information for the given class.
 *
 * @param node the XML element that specifies which components to document
 * @param classTree content tree to which the serial UID information will be added
 */
public void buildSerialUIDInfo(XMLNode node, Content classTree) {
    Content serialUidTree = writer.getSerialUIDInfoHeader();
    for (Element e : utils.getFieldsUnfiltered(currentTypeElement)) {
        VariableElement field = (VariableElement)e;
        if (field.getSimpleName().toString().compareTo(SERIAL_VERSION_UID) == 0 &&
            field.getConstantValue() != null) {
            writer.addSerialUIDInfo(SERIAL_VERSION_UID_HEADER,
                                    utils.constantValueExpresion(field), serialUidTree);
            break;
        }
    }
    classTree.addContent(serialUidTree);
}