com.github.javaparser.ast.type.Type Java Examples

The following examples show how to use com.github.javaparser.ast.type.Type. 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: Sources.java    From sundrio with Apache License 2.0 6 votes vote down vote up
public TypeRef apply(Type type) {
    if (type instanceof VoidType) {
        return new VoidRef();
    } else if (type instanceof WildcardType) {
        return new WildcardRef();
    } else if (type instanceof ReferenceType) {
        ReferenceType referenceType = (ReferenceType) type;
        int dimensions = referenceType.getArrayCount();
        TypeRef typeRef = TYPEREF.apply(referenceType.getType());
        if (dimensions == 0) {
            return typeRef;
        } else if (typeRef instanceof ClassRef) {
            return new ClassRefBuilder((ClassRef)typeRef).withDimensions(dimensions).build();
        } else if (typeRef instanceof PrimitiveRef) {
            return new PrimitiveRefBuilder((PrimitiveRef)typeRef).withDimensions(dimensions).build();
        } else if (typeRef instanceof TypeParamRef) {
            return new TypeParamRefBuilder((TypeParamRef)typeRef).withDimensions(dimensions).build();
        }
    } else if (type instanceof PrimitiveType) {
        PrimitiveType primitiveType = (PrimitiveType) type;
        return new PrimitiveRefBuilder().withName(primitiveType.getType().name()).build();
    } else if (type instanceof ClassOrInterfaceType) {
        return CLASS_OR_TYPEPARAM_REF.apply((ClassOrInterfaceType) type);
    }
    throw new IllegalArgumentException("Can't handle type:[" + type + "].");
}
 
Example #2
Source File: ParserTypeUtil.java    From JRemapper with MIT License 6 votes vote down vote up
/**
 * @param type
 *            JavaParser type. Must be an object type.
 * @return Internal descriptor from type, assuming the type is available.
 */
private static String typeToDesc(Type type) {
	String key = null;
	if (type instanceof ClassOrInterfaceType) {
		try {
			key = ((ClassOrInterfaceType) type).resolve().getQualifiedName();
		} catch(Exception ex) { /* ignored */ }
	}
	if (key == null)
		key = type.asString();
	StringBuilder sbDesc = new StringBuilder();
	for (int i = 0; i < type.getArrayLevel(); i++)
		sbDesc.append("[");
	sbDesc.append("L");
	sbDesc.append(key.replace('.', '/'));
	sbDesc.append(";");
	return sbDesc.toString();
}
 
Example #3
Source File: ParserTypeUtil.java    From JRemapper with MIT License 6 votes vote down vote up
/**
 * @param md
 *            JavaParser method declaration.
 * @return Internal descriptor from declaration, or {@code null} if any parsing
 *         failures occured.
 */
private static String getMethodDesc(MethodDeclaration md) {
	StringBuilder sbDesc = new StringBuilder("(");
	// Append the method parameters for the descriptor
	NodeList<Parameter> params = md.getParameters();
	for (Parameter param : params) {
		Type pType = param.getType();
		String pDesc = getDescriptor(pType);
		if (pDesc == null)
			return null;
		sbDesc.append(pDesc);
	}
	// Append the return type for the descriptor
	Type typeRet = md.getType();
	String retDesc = getDescriptor(typeRet);
	if (retDesc == null)
		return null;
	sbDesc.append(")");
	sbDesc.append(retDesc);
	return sbDesc.toString();
}
 
Example #4
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private OpenAPI createBasicModel() {
    OpenAPI openAPI = new OpenAPI();

    Info info = new Info();
    info.setTitle(configuration.getApplicationTitle());
    info.setVersion(configuration.getApplicationApiVersion());
    openAPI.setInfo(info);

    Paths paths = new Paths();
    openAPI.setPaths(paths);

    Server server = new Server();
    server.setUrl(configuration.getServerUrl());
    server.setDescription(configuration.getServerDescription());
    openAPI.setServers(Collections.singletonList(server));
    Components components = new Components();
    SecurityScheme vaadinConnectOAuth2Scheme = new SecurityScheme()
            .type(SecurityScheme.Type.OAUTH2)
            .flows(new OAuthFlows().password(new OAuthFlow()
                    .tokenUrl(VAADIN_CONNECT_OAUTH2_TOKEN_URL)
                    .scopes(new Scopes())));
    components.addSecuritySchemes(VAADIN_CONNECT_OAUTH2_SECURITY_SCHEME,
            vaadinConnectOAuth2Scheme);
    openAPI.components(components);
    return openAPI;
}
 
Example #5
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private ApiResponse createApiSuccessfulResponse(
        MethodDeclaration methodDeclaration) {
    Content successfulContent = new Content();
    // "description" is a REQUIRED property of Response
    ApiResponse successfulResponse = new ApiResponse().description("");
    methodDeclaration.getJavadoc().ifPresent(javadoc -> {
        for (JavadocBlockTag blockTag : javadoc.getBlockTags()) {
            if (blockTag.getType() == JavadocBlockTag.Type.RETURN) {
                successfulResponse.setDescription(
                        "Return " + blockTag.getContent().toText());
            }
        }
    });
    if (!methodDeclaration.getType().isVoidType()) {
        MediaType mediaItem = createReturnMediaType(methodDeclaration);
        successfulContent.addMediaType("application/json", mediaItem);
        successfulResponse.content(successfulContent);
    }
    return successfulResponse;
}
 
Example #6
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void visit(final VariableDeclarator n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    n.getName().accept(this, arg);

    Type commonType = n.getAncestorOfType(NodeWithVariables.class).get().getMaximumCommonType();

    Type type = n.getType();

    ArrayType arrayType = null;

    for (int i = commonType.getArrayLevel(); i < type.getArrayLevel(); i++) {
        if (arrayType == null) {
            arrayType = (ArrayType) type;
        } else {
            arrayType = (ArrayType) arrayType.getComponentType();
        }
        printAnnotations(arrayType.getAnnotations(), true, arg);
        printer.print("[]");
    }

    if (n.getInitializer().isPresent()) {
        printer.print(" = ");
        n.getInitializer().get().accept(this, arg);
    }
}
 
Example #7
Source File: JavaParsingAtomicArrayQueueGenerator.java    From JCTools with Apache License 2.0 6 votes vote down vote up
/**
 * Given a variable declaration of some sort, check it's name and type and
 * if it looks like any of the key type changes between unsafe and atomic
 * queues, perform the conversion to change it's type.
 */
void processSpecialNodeTypes(NodeWithType<?, Type> node, String name) {
    Type type = node.getType();
    if ("buffer".equals(name) && isRefArray(type, "E")) {
        node.setType(atomicRefArrayType((ArrayType) type));
    } else if ("sBuffer".equals(name) && isLongArray(type)) {
        node.setType(atomicLongArrayType());
    } else if (PrimitiveType.longType().equals(type)) {
        switch(name) {
        case "mask":
        case "offset":
        case "seqOffset":
        case "lookAheadSeqOffset":
        case "lookAheadElementOffset":
            node.setType(PrimitiveType.intType());
        }
    }
}
 
Example #8
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with Apache License 2.0 6 votes vote down vote up
/**
 * Given a variable declaration of some sort, check it's name and type and
 * if it looks like any of the key type changes between unsafe and atomic
 * queues, perform the conversion to change it's type.
 */
void processSpecialNodeTypes(NodeWithType<?, Type> node, String name) {
    Type type = node.getType();
    if (node instanceof MethodDeclaration && ("newBufferAndOffset".equals(name) || "nextArrayOffset".equals(name))) {
        node.setType(PrimitiveType.intType());
    } else if (PrimitiveType.longType().equals(type)) {
        switch(name) {
        case "offset":
        case "offsetInNew":
        case "offsetInOld":
        case "lookAheadElementOffset":
            node.setType(PrimitiveType.intType());
        }
    } else if (isRefType(type, "LinkedQueueNode")) {
        node.setType(simpleParametricType("LinkedQueueAtomicNode", "E"));
    } else if (isRefArray(type, "E")) {
        node.setType(atomicRefArrayType((ArrayType) type));
    }
}
 
Example #9
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
protected boolean isRefType(Type in, String className) {
    // Does not check type parameters
    if (in instanceof ClassOrInterfaceType) {
        return (className.equals(((ClassOrInterfaceType) in).getNameAsString()));
    }
    return false;
}
 
Example #10
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
protected boolean isRefArray(Type in, String refClassName) {
    if (in instanceof ArrayType) {
        ArrayType aType = (ArrayType) in;
        return isRefType(aType.getComponentType(), refClassName);
    }
    return false;
}
 
Example #11
Source File: JavaParsingAtomicArrayQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
private boolean isLongArray(Type in) {
    if (in instanceof ArrayType) {
        ArrayType aType = (ArrayType) in;
        return PrimitiveType.longType().equals(aType.getComponentType());
    }
    return false;
}
 
Example #12
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
protected ClassOrInterfaceType simpleParametricType(String className, String... typeArgs) {
    NodeList<Type> typeArguments = new NodeList<Type>();
    for (String typeArg : typeArgs) {
        typeArguments.add(classType(typeArg));
    }
    return new ClassOrInterfaceType(null, new SimpleName(className), typeArguments);
}
 
Example #13
Source File: MultiTypeParameterMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean doIsEquals(MultiTypeParameter first, MultiTypeParameter second) {

    if(!getMerger(VariableDeclaratorId.class).isEquals(first.getId(),second.getId())) return false;

    List<Type> firstTypes = first.getTypes();
    List<Type> secondTypes = second.getTypes();

    if(firstTypes == null) return secondTypes == null;
    if(secondTypes == null) return false;

    if(firstTypes.size() != secondTypes.size()) return false;

    for(Type ft : firstTypes){
        boolean found = false;
        AbstractMerger merger = getMerger(ft.getClass());
        for(Type st : secondTypes){
            if(merger.isEquals(ft, st)){
                found = true; break;
            }
        }
        if(!found) return false;
    }

    return true;
}
 
Example #14
Source File: ClassOrInterfaceTypeToTypeDef.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public TypeDef apply(ClassOrInterfaceType item) {
    List<TypeParamDef> parameters = new ArrayList<TypeParamDef>();

    for (Type type : item.getTypeArgs()) {
        new TypeParamDefBuilder()
                .build();
    }

    return new TypeDefBuilder()
            .withName(item.getName())
            .withParameters(parameters)
            .build();
}
 
Example #15
Source File: AnnotatedMember.java    From jeddict with Apache License 2.0 5 votes vote down vote up
static Optional<String> getClassNameAttribute(AnnotationExpr annotationExpr, String attributeName) {
    try {
        return getResolvedClassAttribute(annotationExpr, attributeName)
                .map(ResolvedTypeDeclaration::getQualifiedName);
    } catch (Exception e) {
        return getTypeClassAttribute(annotationExpr, attributeName)
                .map(Type::toString);
    }
}
 
Example #16
Source File: AnnotationExplorer.java    From jeddict with Apache License 2.0 5 votes vote down vote up
public Optional<String> getClassName(String attributeName) {
    try {
        return getResolvedClassAttribute(annotationExpr, attributeName)
                .map(ResolvedTypeDeclaration::getQualifiedName);
    } catch (Exception e) {
        return getTypeClassAttribute(annotationExpr, attributeName)
                .map(Type::toString);
    }
}
 
Example #17
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Schema parseTypeToSchema(Type javaType, String description) {
    try {
        Schema schema = parseResolvedTypeToSchema(javaType.resolve());
        if (GeneratorUtils.isNotBlank(description)) {
            schema.setDescription(description);
        }
        return schema;
    } catch (Exception e) {
        getLogger().info(String.format(
                "Can't resolve type '%s' for creating custom OpenAPI Schema. Using the default ObjectSchema instead.",
                javaType.asString()), e);
    }
    return new ObjectSchema();
}
 
Example #18
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private MediaType createReturnMediaType(
        MethodDeclaration methodDeclaration) {
    MediaType mediaItem = new MediaType();
    Type methodReturnType = methodDeclaration.getType();
    Schema schema = parseTypeToSchema(methodReturnType, "");
    if (methodDeclaration.isAnnotationPresent(Nullable.class)) {
        schema = schemaResolver.createNullableWrapper(schema);
    }
    usedTypes.putAll(collectUsedTypesFromSchema(schema));
    mediaItem.schema(schema);
    return mediaItem;
}
 
Example #19
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
private void processSpecialNodeTypes(ObjectCreationExpr node) {
    Type type = node.getType();
    if (isRefType(type, "LinkedQueueNode")) {
        node.setType(simpleParametricType("LinkedQueueAtomicNode", "E"));
    } else if (isRefArray(type, "E")) {
        node.setType(atomicRefArrayType((ArrayType) type));
    }
}
 
Example #20
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private String getTypeName(Type t) {
//    if (t instanceof ReferenceType) {
//      t = ((ReferenceType<?>)t).getType();
//    }
    
    if (t instanceof PrimitiveType) {
      return ((PrimitiveType)t).toString(); 
    }
    if (t instanceof ClassOrInterfaceType) {
      return ((ClassOrInterfaceType)t).getNameAsString();
    }
    Misc.internalError(); return null;
  }
 
Example #21
Source File: ClassOrInterfaceTypeMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean doIsEquals(ClassOrInterfaceType first, ClassOrInterfaceType second) {

    if(!StringUtils.equals(first.getName(),second.getName())) return false;

    // check type args in order
    List<Type> firstTypeArgs = first.getTypeArgs();
    List<Type> secondTypeArgs = second.getTypeArgs();

    if(firstTypeArgs == secondTypeArgs) return true;

    if(firstTypeArgs == null || secondTypeArgs == null) return false;

    for(int i = 0; i < firstTypeArgs.size(); i++){
        Type ft = firstTypeArgs.get(i);
        Type st = secondTypeArgs.get(i);
        if(ft.getClass().equals(st.getClass())) {
            AbstractMerger merger = getMerger(ft.getClass());
            if(!merger.isEquals(ft,st)) return false;
        }else {
            return false;
        }
    }

    // check scope recursively
    if(isAllNotNull(first.getScope(),second.getScope())){
        if(!isEquals(first.getScope(),second.getScope())) return false;

    }else if(!isAllNull(first.getScope(),second.getScope())){
        return false;
    }

    return true;
}
 
Example #22
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private void addCastExpr(Statement stmt, Type castType) {
  ReturnStmt rstmt = (ReturnStmt) stmt;
  Optional<Expression> o_expr = rstmt.getExpression(); 
  Expression expr = o_expr.isPresent() ? o_expr.get() : null;
  CastExpr ce = new CastExpr(castType, expr);
  rstmt.setExpression(ce);  // removes the parent link from expr
  if (expr != null) {
    expr.setParentNode(ce); // restore it
  }
}
 
Example #23
Source File: ParserTypeUtil.java    From JRemapper with MIT License 5 votes vote down vote up
/**
 * @param type
 *            JavaParser type. Must be a primitive.
 * @return Internal descriptor.
 */
private static String primTypeToDesc(Type type) {
	String desc = null;
	switch (type.asString()) {
		case "boolean":
			desc = "Z";
			break;
		case "int":
			desc = "I";
			break;
		case "long":
			desc = "J";
			break;
		case "short":
			desc = "S";
			break;
		case "byte":
			desc = "B";
			break;
		case "double":
			desc = "D";
			break;
		case "float":
			desc = "F";
			break;
		case "void":
			desc = "V";
			break;
		default:
			throw new RuntimeException("Unknown primitive type field '" + type.asString() + "'");
	}
	StringBuilder sbDesc = new StringBuilder();
	for (int i = 0; i < type.getArrayLevel(); i++)
		sbDesc.append("[");
	sbDesc.append(desc);
	return sbDesc.toString();
}
 
Example #24
Source File: RuleUnitDTOSourceClass.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private FieldDeclaration createField() {
    Type type = toQueryType();

    VariableDeclarator variableDeclarator = new VariableDeclarator(type, ruleUnitVariable.getName());
    if (isDataSource && !isSingletonStore) {
        variableDeclarator.setInitializer("java.util.Collections.emptyList()");
    }

    return new FieldDeclaration()
            .setModifiers(Modifier.Keyword.PRIVATE)
            .addVariable(variableDeclarator);
}
 
Example #25
Source File: SpringControllerParser.java    From JApiDocs with Apache License 2.0 5 votes vote down vote up
private void setRequestBody(ParamNode paramNode, Type paramType) {
    if (ParseUtils.isModelType(paramType.asString())) {
        ClassNode classNode = new ClassNode();
        ParseUtils.parseClassNodeByType(getControllerFile(), classNode, paramType);
        paramNode.setJsonBody(true);
        classNode.setShowFieldNotNull(Boolean.TRUE);
        paramNode.setDescription(classNode.toJsonApi());
    }
}
 
Example #26
Source File: RuleUnitDTOSourceClass.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private Type toQueryType() {
    if (isSingletonStore) {
        genericType = ruleUnitVariable.getDataSourceParameterType().getCanonicalName();
        return new ClassOrInterfaceType(null, genericType);
    } else if (isDataSource) {
        genericType = ruleUnitVariable.getDataSourceParameterType().getCanonicalName();
        return new ClassOrInterfaceType(null, "java.util.List")
                .setTypeArguments(new ClassOrInterfaceType(null, genericType));
    } else {
        return new ClassOrInterfaceType(null, ruleUnitVariable.getType().getCanonicalName());
    }
}
 
Example #27
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
private void printTypeArgs(final NodeWithTypeArguments<?> nodeWithTypeArguments, final Void arg) {
    NodeList<Type> typeArguments = nodeWithTypeArguments.getTypeArguments().orElse(null);
    if (!isNullOrEmpty(typeArguments)) {
        printer.print("<");
        for (final Iterator<Type> i = typeArguments.iterator(); i.hasNext(); ) {
            final Type t = i.next();
            t.accept(this, arg);
            if (i.hasNext()) {
                printer.print(", ");
            }
        }
        printer.print(">");
    }
}
 
Example #28
Source File: SpringComponentResolver.java    From apigcc with MIT License 5 votes vote down vote up
@Override
public TypeDescription resolve(Type type) {
    if (type.isClassOrInterfaceType()) {
        Optional<NodeList<Type>> optional = type.asClassOrInterfaceType().getTypeArguments();
        if (optional.isPresent() && optional.get().size() > 0) {
            Type typeArgument = optional.get().get(0);
            return Apigcc.getInstance().getTypeResolvers().resolve(typeArgument);
        }

    }
    return new UnAvailableTypeDescription();
}
 
Example #29
Source File: TypeResolvers.java    From apigcc with MIT License 5 votes vote down vote up
/**
 * 通过名称解析类型信息
 *
 * @param type
 * @return
 */
public TypeDescription resolveByName(Type type) {
    String id = ClassHelper.getId(type);
    for (NameResolver nameResolver : nameResolvers) {
        if (nameResolver.accept(id)) {
            return nameResolver.resolve(type);
        }
    }
    log.warn("type({}) resolve failed", id);
    return new UnAvailableTypeDescription();
}
 
Example #30
Source File: ClassHelper.java    From apigcc with MIT License 5 votes vote down vote up
/**
 * 获取类型名称
 * @param type
 * @return
 */
public static String getId(Type type){
    String name;
    if(type.isClassOrInterfaceType()){
        name = type.asClassOrInterfaceType().getNameAsString();
    }else{
        name = type.toString();
    }
    Optional<CompilationUnit> optional = CompilationUnitHelper.getCompilationUnit(type);
    if(optional.isPresent()){
        CompilationUnit compilationUnit = optional.get();
        return getNameFromImport(name, compilationUnit);
    }
    return name;
}