com.fasterxml.classmate.ResolvedType Java Examples

The following examples show how to use com.fasterxml.classmate.ResolvedType. 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: DefaultParamPlugin.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
private void resolveApiParam(ParameterContext context) {
	ResolvedType resolvedType = context.resolvedMethodParameter().getParameterType();
	Class<?> parameterClass = resolveParamType(resolvedType);
	if (parameterClass == null) {
		log.warn(StrUtil.concat(resolvedType.getBriefDescription(), "的类型无法被DefaultParamPlugin解析"));
		@SuppressWarnings("unused") int a = 1;
		return;
	}
	ApiModel apiModel = parameterClass.getAnnotation(ApiModel.class);
	if (apiModel == null) {
		if (!BeanUtils.isSimpleProperty(parameterClass)) {
			warn(context, parameterClass);
		}
		return;
	}
	ParameterBuilder builder = context.parameterBuilder();
	builder.name(apiModel.description());
	builder.description(descriptions.resolve(apiModel.description()));
	builder.allowMultiple(false);
	builder.allowEmptyValue(false);
	builder.hidden(false);
	builder.collectionFormat("");
	builder.order(SWAGGER_PLUGIN_ORDER);
}
 
Example #2
Source File: SchemaGeneratorSubtypesTest.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
@Override
public List<ResolvedType> findSubtypes(ResolvedType declaredType, SchemaGenerationContext context) {
    if (declaredType.getErasedType() == TestSuperClass.class) {
        return subtypes.stream()
                .map(subtype -> {
                    try {
                        return context.getTypeContext().resolveSubtype(declaredType, subtype);
                    } catch (IllegalArgumentException ex) {
                        // possible reasons are mainly:
                        // 1. Conflicting type parameters between declared super type and this particular subtype
                        // 2. Extra generic introduced in subtype that is not present in supertype, i.e. which cannot be resolved
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
    return null;
}
 
Example #3
Source File: ConstructorParameterModelProperty.java    From chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a ConstructorParameterModelProperty which provides a ModelProperty
 * for constructor parameters.
 *
 * @param resolvedParameterType the parameter type
 * @param alternateTypeProvider provider for resolving alternatives for the given param type
 * @param annotationMap map of annotations for the given parameter. it must contain a @JsonProperty annotation.
 */
public ConstructorParameterModelProperty(
        ResolvedType resolvedParameterType,
        AlternateTypeProvider alternateTypeProvider,
        AnnotationMap annotationMap) {

    this.resolvedParameterType = alternateTypeProvider.alternateFor(resolvedParameterType);

    if (this.resolvedParameterType == null) {
        this.resolvedParameterType = resolvedParameterType;
    }

    setJsonProperty(annotationMap.get(JsonProperty.class));
    setTypeName();
    setAllowableValues();
    setQualifiedTypeName();
}
 
Example #4
Source File: ApiMethodReader.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
private void readReturnDescription(OperationContext context, ApiMethod apiMethod) {
    ResolvedType returnType = context.alternateFor(context.getReturnType());
    String message = StringUtils.isEmpty(apiMethod.returnDescription()) ? "成功" : apiMethod.returnDescription();
    ModelReference modelRef = null;
    if (!isVoid(returnType)) {
        ModelContext modelContext = ModelContext.returnValue(
                context.getGroupName(), returnType,
                context.getDocumentationType(),
                context.getAlternateTypeProvider(),
                context.getGenericsNamingStrategy(),
                context.getIgnorableParameterTypes());
        modelRef = modelRefFactory(modelContext, typeNameExtractor).apply(returnType);
    }
    ResponseMessage built = new ResponseMessageBuilder()
            .code(HttpStatus.OK.value())
            .message(message)
            .responseModel(modelRef)
            .build();
    context.operationBuilder().responseMessages(newHashSet(built));
}
 
Example #5
Source File: JsonSubTypesResolver.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Determine the appropriate type identifier according to {@link JsonTypeInfo#use()}.
 *
 * @param javaType specific subtype to identify
 * @param typeInfoAnnotation annotation for determining what kind of identifier to use
 * @return type identifier (or {@code null} if no supported value could be found)
 */
private String getTypeIdentifier(ResolvedType javaType, JsonTypeInfo typeInfoAnnotation) {
    Class<?> erasedTargetType = javaType.getErasedType();
    final String typeIdentifier;
    switch (typeInfoAnnotation.use()) {
    case NAME:
        typeIdentifier = Optional.ofNullable(erasedTargetType.getAnnotation(JsonTypeName.class))
                .map(JsonTypeName::value)
                .filter(name -> !name.isEmpty())
                .orElseGet(() -> getUnqualifiedClassName(erasedTargetType));
        break;
    case CLASS:
        typeIdentifier = erasedTargetType.getName();
        break;
    default:
        typeIdentifier = null;
    }
    return typeIdentifier;
}
 
Example #6
Source File: AbstractTypeAwareTest.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Override generation context mock methods that are version dependent.
 *
 * @param schemaVersion designated JSON Schema version
 */
protected void prepareContextForVersion(SchemaVersion schemaVersion) {
    TypeContext typeContext = TypeContextFactory.createDefaultTypeContext();
    ResolvedType resolvedTestClass = typeContext.resolve(this.testClass);
    this.testClassMembers = typeContext.resolveWithMembers(resolvedTestClass);
    this.context = Mockito.mock(SchemaGenerationContext.class, Mockito.RETURNS_DEEP_STUBS);
    Mockito.when(this.context.getTypeContext()).thenReturn(typeContext);
    ObjectMapper objectMapper = new ObjectMapper();
    Mockito.when(this.context.getGeneratorConfig().getObjectMapper()).thenReturn(objectMapper);
    Mockito.when(this.context.getGeneratorConfig().createArrayNode()).thenAnswer(_invocation -> objectMapper.createArrayNode());
    Mockito.when(this.context.getGeneratorConfig().createObjectNode()).thenAnswer(_invocation -> objectMapper.createObjectNode());
    Mockito.when(this.context.getGeneratorConfig().getSchemaVersion()).thenReturn(schemaVersion);

    Answer<String> keywordLookup = invocation -> ((SchemaKeyword) invocation.getArgument(0)).forVersion(schemaVersion);
    Mockito.when(this.context.getGeneratorConfig().getKeyword(Mockito.any())).thenAnswer(keywordLookup);
    Mockito.when(this.context.getKeyword(Mockito.any())).thenAnswer(keywordLookup);
}
 
Example #7
Source File: SchemaGeneratorCustomDefinitionsTest.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
@Test
@Parameters(source = SchemaVersion.class)
public void testGenerateSchema_CircularCustomStandardDefinition(SchemaVersion schemaVersion) throws Exception {
    String accessProperty = "get(0)";
    CustomDefinitionProviderV2 customDefinitionProvider = (javaType, context) -> {
        if (!javaType.isInstanceOf(List.class)) {
            return null;
        }
        ResolvedType generic = context.getTypeContext().getContainerItemType(javaType);
        SchemaGeneratorConfig config = context.getGeneratorConfig();
        return new CustomDefinition(config.createObjectNode()
                .put(config.getKeyword(SchemaKeyword.TAG_TYPE), config.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT))
                .set(config.getKeyword(SchemaKeyword.TAG_PROPERTIES), config.createObjectNode()
                        .set(accessProperty, context.createDefinitionReference(generic))));
    };
    SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
    configBuilder.forTypesInGeneral()
            .withCustomDefinitionProvider(customDefinitionProvider);
    SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
    JsonNode result = generator.generateSchema(TestCircularClass1.class);
    JSONAssert.assertEquals('\n' + result.toString() + '\n',
            TestUtils.loadResource(this.getClass(), "circular-custom-definition-" + schemaVersion.name() + ".json"),
            result.toString(), JSONCompareMode.STRICT);
}
 
Example #8
Source File: ApiParamReader.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(ParameterContext context) {
    ResolvedType resolvedType = context.resolvedMethodParameter().getParameterType();
    Class erasedType = resolvedType.getErasedType();
    if (isGeneratedType(erasedType)) {
        context.parameterBuilder()
                .parameterType("body").name(erasedType.getSimpleName())
                .description("Not a real parameter, it is a parameter generated after assembly.");
        return;
    }
    Optional<ApiParam> optional = readApiParam(context);
    if (optional.isPresent()) {
        ApiParam apiParam = optional.get();
        List<VendorExtension> extensions = buildExtensions(resolvedType);
        context.parameterBuilder().name(emptyToNull(apiParam.name()))
                .description(emptyToNull(resolver.resolve(apiParam.value())))
                .parameterType(TypeUtils.isComplexObjectType(erasedType) ? "body" : "query")
                .order(SWAGGER_PLUGIN_ORDER)
                .hidden(false)
                .parameterAccess(emptyToNull(apiParam.access()))
                .defaultValue(emptyToNull(apiParam.defaultValue()))
                .allowMultiple(apiParam.allowMultiple())
                .allowEmptyValue(apiParam.allowEmptyValue())
                .required(apiParam.required())
                .scalarExample(new Example(apiParam.example()))
                .complexExamples(examples(apiParam.examples()))
                .collectionFormat(apiParam.collectionFormat())
                .vendorExtensions(extensions);
    }
}
 
Example #9
Source File: DefaultModelPlugin.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
private String recursiveResolveList(ResolvedType resolvedType) {
	if (TypeUtil.isSimpleType(resolvedType)) {
		ApiModel apiModel = resolvedType.getErasedType().getAnnotation(ApiModel.class);
		if (apiModel != null) {
			return apiModel.description();
		} else {
			return "";
		}
	} else if (TypeUtil.belongToComplexType(Collection.class, resolvedType)) {
		resolvedType = TypeUtil.resolveGenericType(Collection.class, resolvedType).get(0);
		String result = recursiveResolveList(resolvedType);
		if (result == null) {
			return null;
		} else {
			return StrUtil.concat(result, "的列表");
		}
	} else {
		return null;
	}
}
 
Example #10
Source File: CustomEnumDefinitionProvider.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the given type is an enum with at least one constant value and a single {@link JsonValue} annotated method with
 * {@code value = true} and no expected arguments.
 *
 * @param javaType encountered type during schema generation
 * @param enumConstants non-empty array of enum constants
 * @param context current generation context
 * @return results from invoking the {@link JsonValue} annotated method for each enum constant (or {@code null} if the criteria are not met)
 */
protected List<Object> getSerializedValuesFromJsonValue(ResolvedType javaType, Object[] enumConstants, SchemaGenerationContext context) {
    ResolvedMethod jsonValueAnnotatedEnumMethod = this.getJsonValueAnnotatedMethod(javaType, context);
    if (jsonValueAnnotatedEnumMethod == null) {
        return null;
    }
    try {
        List<Object> serializedJsonValues = new ArrayList<>(enumConstants.length);
        for (Object enumConstant : enumConstants) {
            serializedJsonValues.add(jsonValueAnnotatedEnumMethod.getRawMember().invoke(enumConstant));
        }
        return serializedJsonValues;
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        return null;
    }
}
 
Example #11
Source File: SchemaDefinitionNamingStrategyTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
@Parameters
@TestCaseName(value = "{method}({0}, {3} | {4}) [{index}]")
public void testExampleStrategy(String caseTitle, SchemaDefinitionNamingStrategy strategy, ResolvedType type,
        String expectedUriCompatibleName, String expectedPlainName) {
    Mockito.when(this.key.getType()).thenReturn(type);
    String result = strategy.getDefinitionNameForKey(this.key, this.generationContext);
    // before the produced name is used in an actual schema, the SchemaCleanUpUtils come into play one way or another
    SchemaCleanUpUtils cleanUpUtils = new SchemaCleanUpUtils(null);
    Assert.assertEquals(expectedUriCompatibleName, cleanUpUtils.ensureDefinitionKeyIsUriCompatible(result));
    Assert.assertEquals(expectedPlainName, cleanUpUtils.ensureDefinitionKeyIsPlain(result));
}
 
Example #12
Source File: SchemaGenerationContextImplTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReference_SameType() {
    ResolvedType javaType = Mockito.mock(ResolvedType.class);
    DefinitionKey key = new DefinitionKey(javaType, null);

    // initially, all lists are empty
    Assert.assertEquals(Collections.<ObjectNode>emptyList(), this.contextImpl.getReferences(key));
    Assert.assertEquals(Collections.<ObjectNode>emptyList(), this.contextImpl.getNullableReferences(key));

    // adding a not-nullable entry creates the "references" list
    ObjectNode referenceInputOne = Mockito.mock(ObjectNode.class);
    SchemaGenerationContextImpl returnValue = this.contextImpl.addReference(javaType, referenceInputOne, null, false);
    Assert.assertSame(this.contextImpl, returnValue);
    Assert.assertEquals(Collections.singletonList(referenceInputOne), this.contextImpl.getReferences(key));
    Assert.assertEquals(Collections.<ObjectNode>emptyList(), this.contextImpl.getNullableReferences(key));

    // adding another not-nullable entry adds it to the existing "references" list
    ObjectNode referenceInputTwo = Mockito.mock(ObjectNode.class);
    returnValue = this.contextImpl.addReference(javaType, referenceInputTwo, null, false);
    Assert.assertSame(this.contextImpl, returnValue);
    Assert.assertEquals(Arrays.asList(referenceInputOne, referenceInputTwo), this.contextImpl.getReferences(key));
    Assert.assertEquals(Collections.<ObjectNode>emptyList(), this.contextImpl.getNullableReferences(key));

    // adding a nullable entry creates the "nullableReferences" list
    ObjectNode referenceInputThree = Mockito.mock(ObjectNode.class);
    returnValue = this.contextImpl.addReference(javaType, referenceInputThree, null, true);
    Assert.assertSame(this.contextImpl, returnValue);
    Assert.assertEquals(Arrays.asList(referenceInputOne, referenceInputTwo), this.contextImpl.getReferences(key));
    Assert.assertEquals(Collections.singletonList(referenceInputThree), this.contextImpl.getNullableReferences(key));
}
 
Example #13
Source File: HandlerMethodResolverWrapper.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private static Function<ResolvedMethod, ResolvedType> toReturnType(final TypeResolver resolver) {
    return new Function<ResolvedMethod, ResolvedType>() {
        @Override
        public ResolvedType apply(ResolvedMethod input) {
            return Optional.fromNullable(input.getReturnType()).or(resolver.resolve(Void.TYPE));
        }
    };
}
 
Example #14
Source File: SchemaGeneratorConfigImpl.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Override
public CustomDefinition getCustomDefinition(ResolvedType javaType, SchemaGenerationContext context,
        CustomDefinitionProviderV2 ignoredDefinitionProvider) {
    final List<CustomDefinitionProviderV2> providers = this.typesInGeneralConfigPart.getCustomDefinitionProviders();
    int firstRelevantProviderIndex = 1 + providers.indexOf(ignoredDefinitionProvider);
    return providers.subList(firstRelevantProviderIndex, providers.size())
            .stream()
            .map(provider -> provider.provideCustomSchemaDefinition(javaType, context))
            .filter(Objects::nonNull)
            .findFirst()
            .orElse(null);
}
 
Example #15
Source File: AutoApplicableConverterDescriptorStandardImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ConverterDescriptor getAutoAppliedConverterDescriptorForAttribute(
		XProperty xProperty,
		MetadataBuildingContext context) {
	final ResolvedType attributeType = resolveAttributeType( xProperty, context );

	return typesMatch( linkedConverterDescriptor.getDomainValueResolvedType(), attributeType )
			? linkedConverterDescriptor
			: null;
}
 
Example #16
Source File: AbstractConverterDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public AbstractConverterDescriptor(
		Class<? extends AttributeConverter> converterClass,
		Boolean forceAutoApply,
		ClassmateContext classmateContext) {
	this.converterClass = converterClass;

	final ResolvedType converterType = classmateContext.getTypeResolver().resolve( converterClass );
	final List<ResolvedType> converterParamTypes = converterType.typeParametersFor( AttributeConverter.class );
	if ( converterParamTypes == null ) {
		throw new AnnotationException(
				"Could not extract type parameter information from AttributeConverter implementation ["
						+ converterClass.getName() + "]"
		);
	}
	else if ( converterParamTypes.size() != 2 ) {
		throw new AnnotationException(
				"Unexpected type parameter information for AttributeConverter implementation [" +
						converterClass.getName() + "]; expected 2 parameter types, but found " + converterParamTypes.size()
		);
	}

	this.domainType = converterParamTypes.get( 0 );
	this.jdbcType = converterParamTypes.get( 1 );

	this.autoApplicableDescriptor = resolveAutoApplicableDescriptor( converterClass, forceAutoApply );
}
 
Example #17
Source File: TypeUtil.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 获得具有泛型参数的类型的泛型参数具体类型
 * @return 泛型类型中泛型参数具体类型
 * @author Frodez
 * @date 2020-01-02
 */
public List<ResolvedType> resolveGenericType(Class<?> complexClass, ResolvedType type) {
	if (type instanceof ResolvedObjectType) {
		return null;
	} else if (type instanceof ResolvedInterfaceType) {
		if (complexClass.isAssignableFrom(type.getErasedType())) {
			return type.getTypeBindings().getTypeParameters();
		} else {
			return null;
		}
	} else {
		return null;
	}
}
 
Example #18
Source File: SchemaGenerationContextImpl.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Recursively collect all properties of the given object type and add them to the respective maps.
 *
 * @param targetType the type for which to collect fields and methods
 * @param targetProperties map of named fields and methods
 * @param requiredProperties set of properties value required
 */
private void collectObjectProperties(ResolvedType targetType, Map<String, MemberScope<?, ?>> targetProperties, Set<String> requiredProperties) {
    logger.debug("collecting non-static fields and methods from {}", targetType);
    final ResolvedTypeWithMembers targetTypeWithMembers = this.typeContext.resolveWithMembers(targetType);
    // member fields and methods are being collected from the targeted type as well as its super types
    this.collectFields(targetTypeWithMembers, ResolvedTypeWithMembers::getMemberFields, targetProperties, requiredProperties);
    this.collectMethods(targetTypeWithMembers, ResolvedTypeWithMembers::getMemberMethods, targetProperties, requiredProperties);

    final boolean includeStaticFields = this.generatorConfig.shouldIncludeStaticFields();
    final boolean includeStaticMethods = this.generatorConfig.shouldIncludeStaticMethods();
    if (includeStaticFields || includeStaticMethods) {
        // static fields and methods are being collected only for the targeted type itself, i.e. need to iterate over super types specifically
        for (HierarchicType singleHierarchy : targetTypeWithMembers.allTypesAndOverrides()) {
            ResolvedType hierachyType = singleHierarchy.getType();
            logger.debug("collecting static fields and methods from {}", hierachyType);
            if ((!includeStaticFields || hierachyType.getStaticFields().isEmpty())
                    && (!includeStaticMethods || hierachyType.getStaticMethods().isEmpty())) {
                // no static members to look-up for this (super) type
                continue;
            }
            final ResolvedTypeWithMembers hierarchyTypeMembers;
            if (hierachyType == targetType) {
                // avoid looking up the main type again
                hierarchyTypeMembers = targetTypeWithMembers;
            } else {
                hierarchyTypeMembers = this.typeContext.resolveWithMembers(hierachyType);
            }
            if (includeStaticFields) {
                this.collectFields(hierarchyTypeMembers, ResolvedTypeWithMembers::getStaticFields, targetProperties, requiredProperties);
            }
            if (includeStaticMethods) {
                this.collectMethods(hierarchyTypeMembers, ResolvedTypeWithMembers::getStaticMethods, targetProperties, requiredProperties);
            }
        }
    }
}
 
Example #19
Source File: SchemaGeneratorCustomDefinitionsTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
@Parameters(source = SchemaVersion.class)
public void testGenerateSchema_CustomCollectionDefinition(SchemaVersion schemaVersion) throws Exception {
    String accessProperty = "stream().findFirst().orElse(null)";
    CustomDefinitionProviderV2 customDefinitionProvider = (javaType, context) -> {
        if (!javaType.isInstanceOf(Collection.class)) {
            return null;
        }
        ResolvedType generic = context.getTypeContext().getContainerItemType(javaType);
        SchemaGeneratorConfig config = context.getGeneratorConfig();
        return new CustomDefinition(context.getGeneratorConfig().createObjectNode()
                .put(config.getKeyword(SchemaKeyword.TAG_TYPE), config.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT))
                .set(config.getKeyword(SchemaKeyword.TAG_PROPERTIES), config.createObjectNode()
                        .set(accessProperty, context.makeNullable(context.createDefinition(generic)))));
    };
    SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
    configBuilder.forTypesInGeneral().withCustomDefinitionProvider(customDefinitionProvider);
    SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
    JsonNode result = generator.generateSchema(ArrayList.class, String.class);
    Assert.assertEquals(2, result.size());
    Assert.assertEquals(SchemaKeyword.TAG_TYPE_OBJECT.forVersion(schemaVersion),
            result.get(SchemaKeyword.TAG_TYPE.forVersion(schemaVersion)).asText());
    Assert.assertNotNull(result.get(SchemaKeyword.TAG_PROPERTIES.forVersion(schemaVersion)));
    Assert.assertNotNull(result.get(SchemaKeyword.TAG_PROPERTIES.forVersion(schemaVersion)).get(accessProperty));
    JsonNode accessPropertyType = result.get(SchemaKeyword.TAG_PROPERTIES.forVersion(schemaVersion))
            .get(accessProperty).get(SchemaKeyword.TAG_TYPE.forVersion(schemaVersion));
    Assert.assertNotNull(accessPropertyType);
    Assert.assertEquals(SchemaKeyword.TAG_TYPE_STRING.forVersion(schemaVersion), accessPropertyType.get(0).asText());
    Assert.assertEquals(SchemaKeyword.TAG_TYPE_NULL.forVersion(schemaVersion), accessPropertyType.get(1).asText());
}
 
Example #20
Source File: TypeContext.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Constructing a string that fully represents the given type (including possible type parameters and their actual types).
 *
 * @param type the type to represent
 * @param simpleClassNames whether simple class names should be used (otherwise: full package names are included)
 * @return resulting string
 */
private String getTypeDescription(ResolvedType type, boolean simpleClassNames) {
    Class<?> erasedType = type.getErasedType();
    String result = simpleClassNames ? erasedType.getSimpleName() : erasedType.getTypeName();
    List<ResolvedType> typeParameters = type.getTypeParameters();
    if (!typeParameters.isEmpty()) {
        result += typeParameters.stream()
                .map(parameterType -> this.getTypeDescription(parameterType, simpleClassNames))
                .collect(Collectors.joining(", ", "<", ">"));
    }
    return result;
}
 
Example #21
Source File: EnumModuleTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
@Parameters
public void testCustomSchemaDefinition_asStrings(SchemaVersion schemaVersion, EnumModule instance,
        String value1, String value2, String value3) {
    this.initConfigBuilder(schemaVersion);
    instance.applyToConfigBuilder(this.builder);
    ArgumentCaptor<CustomDefinitionProviderV2> captor = ArgumentCaptor.forClass(CustomDefinitionProviderV2.class);
    Mockito.verify(this.typeConfigPart).withCustomDefinitionProvider(captor.capture());

    ResolvedType testEnumType = this.getContext().getTypeContext().resolve(TestEnum.class);
    CustomDefinition schemaDefinition = captor.getValue().provideCustomSchemaDefinition(testEnumType, this.getContext());
    Assert.assertFalse(schemaDefinition.isMeantToBeInline());
    ObjectNode node = schemaDefinition.getValue();
    Assert.assertEquals(2, node.size());

    JsonNode typeNode = node.get(SchemaKeyword.TAG_TYPE.forVersion(schemaVersion));
    Assert.assertEquals(JsonNodeType.STRING, typeNode.getNodeType());
    Assert.assertEquals(SchemaKeyword.TAG_TYPE_STRING.forVersion(schemaVersion), typeNode.textValue());

    JsonNode enumNode = node.get(SchemaKeyword.TAG_ENUM.forVersion(schemaVersion));
    Assert.assertEquals(JsonNodeType.ARRAY, enumNode.getNodeType());
    Assert.assertEquals(3, ((ArrayNode) enumNode).size());
    Assert.assertEquals(JsonNodeType.STRING, enumNode.get(0).getNodeType());
    Assert.assertEquals(value1, enumNode.get(0).textValue());
    Assert.assertEquals(JsonNodeType.STRING, enumNode.get(1).getNodeType());
    Assert.assertEquals(value2, enumNode.get(1).textValue());
    Assert.assertEquals(JsonNodeType.STRING, enumNode.get(2).getNodeType());
    Assert.assertEquals(value3, enumNode.get(2).textValue());
}
 
Example #22
Source File: TypeContext.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Identify the element/item type of the given {@link SchemaKeyword#TAG_TYPE_ARRAY}.
 *
 * @param containerType type to extract type of element/item from
 * @return type of elements/items
 * @see #isContainerType(ResolvedType)
 */
public ResolvedType getContainerItemType(ResolvedType containerType) {
    ResolvedType itemType = containerType.getArrayElementType();
    if (itemType == null && this.isContainerType(containerType)) {
        itemType = this.getTypeParameterFor(containerType, Iterable.class, 0);
    }
    return itemType;
}
 
Example #23
Source File: RequestToPoOperationBuilder.java    From jframework with Apache License 2.0 5 votes vote down vote up
private List<Parameter> readParameters(final OperationContext context) {

        List<ResolvedMethodParameter> methodParameters = context.getParameters();
        final List<Parameter> parameterList = new ArrayList<>();

        for (ResolvedMethodParameter methodParameter : methodParameters) {
            ResolvedType alternate = context.alternateFor(methodParameter.getParameterType());

            if (!shouldIgnore(methodParameter, alternate, context.getIgnorableParameterTypes()) && isRequestFormToPojo(methodParameter)) {
                readRequestFormToPojo(context, methodParameter);
            }
        }
        return parameterList.stream().filter(((Predicate<Parameter>) Parameter::isHidden).negate()).collect(Collectors.toList());
    }
 
Example #24
Source File: TypeContext.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Find type parameterization for the specified (super) type at return the type parameter at the given index.
 *
 * @param type type to find type parameter for
 * @param erasedSuperType (super) type to find declared type parameter for
 * @param parameterIndex index of the single type parameter's declared type to return
 * @return declared parameter type; or Object.class if no parameters are defined; or null if the given type or index are invalid
 * @see ResolvedType#typeParametersFor(Class)
 */
public ResolvedType getTypeParameterFor(ResolvedType type, Class<?> erasedSuperType, int parameterIndex) {
    List<ResolvedType> typeParameters = type.typeParametersFor(erasedSuperType);
    if (typeParameters == null
            || (!typeParameters.isEmpty() && typeParameters.size() <= parameterIndex)
            || (typeParameters.isEmpty() && erasedSuperType.getTypeParameters().length <= parameterIndex)) {
        // given type is not a super type of the type in scope or given index is out of bounds
        return null;
    }
    if (typeParameters.isEmpty()) {
        // no type parameters are defined, for simplicity's sake not trying to resolve declared boundaries
        return this.resolve(Object.class);
    }
    return typeParameters.get(parameterIndex);
}
 
Example #25
Source File: SchemaGeneratorConfigImpl.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Override
public List<ResolvedType> resolveSubtypes(ResolvedType javaType, SchemaGenerationContext context) {
    return this.typesInGeneralConfigPart.getSubtypeResolvers().stream()
            .map(resolver -> resolver.findSubtypes(javaType, context))
            .filter(Objects::nonNull)
            .findFirst()
            .orElseGet(Collections::emptyList);
}
 
Example #26
Source File: SchemaGeneratorSubtypesTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
private List<ResolvedType> determineTargetTypeOverrides(FieldScope field) {
    ResolvedType declaredType = field.getType();
    if (declaredType.getErasedType() == Object.class && field.getName().startsWith("numberOrString")) {
        // TypeContext::resolve() would have been sufficient here, but in advanced scenarios TypeContext::resolveSubType() is more appropriate
        return Stream.of(Number.class, String.class)
                .map(specificSubtype -> field.getContext().resolveSubtype(declaredType, specificSubtype))
                .collect(Collectors.toList());
    }
    return null;
}
 
Example #27
Source File: ApiMethodModelsProvider.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
private List<ResolvedType> collectAllTypes(RequestMappingContext context, ResolvedMethodParameter parameter) {
    List<ResolvedType> allTypes = newArrayList();
    for (ResolvedType type : collectBindingTypes(context.alternateFor(parameter.getParameterType()), newArrayList())) {
        ApiModel apiModel = AnnotationUtils.getAnnotation(type.getErasedType(), ApiModel.class);
        allTypes.add(type);
        if (apiModel != null) {
            allTypes.addAll(Arrays.stream(apiModel.subTypes())
                    .filter(subType -> subType.getAnnotation(ApiModel.class) != type.getErasedType().getAnnotation(ApiModel.class))
                    .map(typeResolver::resolve).collect(Collectors.toList()));
        }
    }
    return allTypes;
}
 
Example #28
Source File: SchemaGenerationContextImplTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateStandardDefinitionReferenceForField_withCustomTypeDefinition() {
    Mockito.doReturn(new CustomDefinition(this.contextImpl.getGeneratorConfig().createObjectNode().put("$comment", "custom type"), true))
            .when(this.contextImpl.getGeneratorConfig())
            .getCustomDefinition(Mockito.any(ResolvedType.class), Mockito.any(), Mockito.any());
    FieldScope targetField = this.getTestClassField("booleanField");
    ObjectNode result = this.contextImpl.createStandardDefinitionReference(targetField, null);
    Assert.assertEquals("{\"allOf\":[{\"$comment\":\"custom type\",\"description\":\"Type Description\"},{\"title\":\"Field Title\"}]}",
            result.toString());
}
 
Example #29
Source File: ParametersReader.java    From Resource with GNU General Public License v3.0 5 votes vote down vote up
private Function<ResolvedType, ? extends ModelReference> createModelRefFactory(ParameterContext context)
{
    ModelContext modelContext = inputParam(
        context.getGroupName(),
        context.resolvedMethodParameter().getParameterType(),
        context.getDocumentationType(),
        context.getAlternateTypeProvider(),
        context.getGenericNamingStrategy(),
        context.getIgnorableParameterTypes());
    return ResolvedTypes.modelRefFactory(modelContext, nameExtractor);
}
 
Example #30
Source File: EnumModule.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Look-up the given enum type's constant values.
 *
 * @param method targeted method
 * @return collection containing constant enum values
 */
private static List<String> extractEnumValues(MethodScope method) {
    ResolvedType declaringType = method.getDeclaringType();
    if (EnumModule.isEnum(declaringType)) {
        return EnumModule.extractEnumValues(declaringType.getTypeParameters().get(0), Enum::name);
    }
    return null;
}