Java Code Examples for org.springframework.core.convert.ConversionService

The following examples show how to use org.springframework.core.convert.ConversionService. These examples are extracted from open source projects. 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
public ConversionService resolve(boolean requireToRegister) {

        ConversionService conversionService = getResolvedBeanIfAvailable();

        if (conversionService == null) { // If not resolved, try to get from ConfigurableBeanFactory
            conversionService = getFromBeanFactory();
        }

        if (conversionService == null) { // If not found, try to get the bean from BeanFactory
            debug("The conversionService instance can't be found in Spring ConfigurableBeanFactory.getConversionService()");
            conversionService = getIfAvailable();
        }
        if (conversionService == null) { // If not found, will create an instance of ConversionService as default
            conversionService = createDefaultConversionService();
        }

        if (!isBeanPresent(beanFactory, RESOLVED_CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)
                && requireToRegister) { // To register a singleton into SingletonBeanRegistry(ConfigurableBeanFactory)
            beanFactory.registerSingleton(RESOLVED_CONVERSION_SERVICE_BEAN_NAME, conversionService);
        }

        return conversionService;
    }
 
Example 2
Source Project: spring-cloud-gray   Source File: ConfigurationUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void bind(Object o, Map<String, Object> properties,
                        String configurationPropertyName, String bindingName, Validator validator,
                        ConversionService conversionService) {
    Object toBind = getTargetObject(o);

    new Binder(
            Collections.singletonList(new MapConfigurationPropertySource(properties)),
            null, conversionService).bind(configurationPropertyName,
            Bindable.ofInstance(toBind));

    if (validator != null) {
        BindingResult errors = new BeanPropertyBindingResult(toBind, bindingName);
        validator.validate(toBind, errors);
        if (errors.hasErrors()) {
            throw new RuntimeException(new BindException(errors));
        }
    }
}
 
Example 3
/**
 * Create a model attribute from a String request value (e.g. URI template
 * variable, request parameter) using type conversion.
 * <p>The default implementation converts only if there a registered
 * {@link Converter} that can perform the conversion.
 * @param sourceValue the source value to create the model attribute from
 * @param attributeName the name of the attribute (never {@code null})
 * @param parameter the method parameter
 * @param binderFactory for creating WebDataBinder instance
 * @param request the current request
 * @return the created model attribute, or {@code null} if no suitable
 * conversion found
 */
@Nullable
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName,
		MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request)
		throws Exception {

	DataBinder binder = binderFactory.createBinder(request, null, attributeName);
	ConversionService conversionService = binder.getConversionService();
	if (conversionService != null) {
		TypeDescriptor source = TypeDescriptor.valueOf(String.class);
		TypeDescriptor target = new TypeDescriptor(parameter);
		if (conversionService.canConvert(source, target)) {
			return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
		}
	}
	return null;
}
 
Example 4
Source Project: spring-analysis-note   Source File: DefaultConversionService.java    License: MIT License 6 votes vote down vote up
/**
 * Add common collection converters.
 * @param converterRegistry the registry of converters to add to
 * (must also be castable to ConversionService, e.g. being a {@link ConfigurableConversionService})
 * @throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService
 * @since 4.2.3
 */
public static void addCollectionConverters(ConverterRegistry converterRegistry) {
	ConversionService conversionService = (ConversionService) converterRegistry;

	converterRegistry.addConverter(new ArrayToCollectionConverter(conversionService));
	converterRegistry.addConverter(new CollectionToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToArrayConverter(conversionService));
	converterRegistry.addConverter(new CollectionToCollectionConverter(conversionService));
	converterRegistry.addConverter(new MapToMapConverter(conversionService));

	converterRegistry.addConverter(new ArrayToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToArrayConverter(conversionService));

	converterRegistry.addConverter(new CollectionToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToCollectionConverter(conversionService));

	converterRegistry.addConverter(new CollectionToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));

	converterRegistry.addConverter(new StreamConverter(conversionService));
}
 
Example 5
Source Project: FastBootWeixin   Source File: WxApiParamContributor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {
    Class<?> paramType = parameter.getNestedParameterType();
    if (Map.class.isAssignableFrom(paramType)) {
        return;
    }
    WxApiParam wxApiParam = parameter.getParameterAnnotation(WxApiParam.class);
    String name = (wxApiParam == null || StringUtils.isEmpty(wxApiParam.name()) ? parameter.getParameterName() : wxApiParam.name());
    WxAppAssert.notNull(name, "请添加编译器的-parameter或者为参数添加注解名称");
    if (value == null) {
        if (wxApiParam != null) {
            if (!wxApiParam.required() || !wxApiParam.defaultValue().equals(ValueConstants.DEFAULT_NONE)) {
                return;
            }
        }
        builder.queryParam(name);
    } else if (value instanceof Collection) {
        for (Object element : (Collection<?>) value) {
            element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
            builder.queryParam(name, element);
        }
    } else {
        builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
    }
}
 
Example 6
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
		UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

	Class<?> paramType = parameter.getParameterType();
	if (Map.class.isAssignableFrom(paramType) || MultipartFile.class == paramType ||
			"javax.servlet.http.Part".equals(paramType.getName())) {
		return;
	}

	RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
	String name = (requestParam == null || StringUtils.isEmpty(requestParam.name()) ? parameter.getParameterName() : requestParam.name());

	if (value == null) {
		builder.queryParam(name);
	}
	else if (value instanceof Collection) {
		for (Object element : (Collection<?>) value) {
			element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
			builder.queryParam(name, element);
		}
	}
	else {
		builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
	}
}
 
Example 7
Source Project: spring-content   Source File: DefaultJpaStoreImpl.java    License: Apache License 2.0 5 votes vote down vote up
protected Object convertToExternalContentIdType(S property, Object contentId) {
	ConversionService converter = new DefaultConversionService();
	if (converter.canConvert(TypeDescriptor.forObject(contentId),
			TypeDescriptor.valueOf(BeanUtils.getFieldWithAnnotationType(property,
					ContentId.class)))) {
		contentId = converter.convert(contentId, TypeDescriptor.forObject(contentId),
				TypeDescriptor.valueOf(BeanUtils.getFieldWithAnnotationType(property,
						ContentId.class)));
		return contentId;
	}
	return contentId.toString();
}
 
Example 8
public BounceFilterController(@Qualifier("BounceFilterService") BounceFilterService bounceFilterService, @Qualifier("MailingBaseService") ComMailingBaseService mailingService,
                              final MailinglistApprovalService mailinglistApprovalService,
                              ComUserformService userFormService, ConversionService conversionService,
                              WebStorage webStorage,
                              UserActivityLogService userActivityLogService) {
    this.bounceFilterService = bounceFilterService;
    this.mailingService = mailingService;
    this.userFormService = userFormService;
    this.conversionService = conversionService;
    this.webStorage = webStorage;
    this.userActivityLogService = userActivityLogService;
    this.mailinglistApprovalService = mailinglistApprovalService;
}
 
Example 9
public UserGroupController(UserGroupService userGroupService, WebStorage webStorage, ConfigService configService, UserActivityLogService userActivityLogService, ConversionService conversionService) {
    this.userGroupService = userGroupService;
    this.webStorage = webStorage;
    this.configService = configService;
    this.userActivityLogService = userActivityLogService;
    this.conversionService = conversionService;
}
 
Example 10
Source Project: camel-spring-boot   Source File: SpringTypeConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
    // do not attempt to convert Camel types
    if (type.getCanonicalName().startsWith("org.apache")) {
        return null;
    }
    
    // do not attempt to convert List -> Map. Ognl expression may use this converter as a fallback expecting null
    if (type.isAssignableFrom(Map.class) && isArrayOrCollection(value)) {
        return null;
    }

    TypeDescriptor sourceType = types.computeIfAbsent(value.getClass(), TypeDescriptor::valueOf);
    TypeDescriptor targetType = types.computeIfAbsent(type, TypeDescriptor::valueOf);

    for (ConversionService conversionService : conversionServices) {
        if (conversionService.canConvert(sourceType, targetType)) {
            try {
                return (T)conversionService.convert(value, sourceType, targetType);
            } catch (ConversionFailedException e) {
                // if value is a collection or an array the check ConversionService::canConvert
                // may return true but then the conversion of specific objects may fail
                //
                // https://issues.apache.org/jira/browse/CAMEL-10548
                // https://jira.spring.io/browse/SPR-14971
                //
                if (e.getCause() instanceof ConverterNotFoundException && isArrayOrCollection(value)) {
                    return null;
                } else {
                    throw new TypeConversionException(value, type, e);
                }
            }
        }
    }

    return null;
}
 
Example 11
@Test
public void createBinderWithGlobalInitialization() throws Exception {
	ConversionService conversionService = new DefaultFormattingConversionService();
	bindingInitializer.setConversionService(conversionService);

	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
	BindingContext context = createBindingContext("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);

	assertSame(conversionService, dataBinder.getConversionService());
}
 
Example 12
@ConditionalOnMissingBean
@Bean
ConversionService defaultCamelConversionService(ApplicationContext applicationContext) {
    DefaultConversionService service = new DefaultConversionService();
    for (Converter converter : applicationContext.getBeansOfType(Converter.class).values()) {
        service.addConverter(converter);
    }
    return service;
}
 
Example 13
Source Project: springlets   Source File: EntityExpressionSupport.java    License: Apache License 2.0 5 votes vote down vote up
public EntityExpressionSupport(ExpressionParser parser,
    TemplateParserContext templateParserContext, ConversionService conversionService,
    String defaultExpression) {
  this.parser = parser;
  this.templateParserContext = templateParserContext;
  this.defaultExpression = defaultExpression;
  this.conversionService = conversionService;
}
 
Example 14
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);

	String name = "requestMappingHandlerAdapter";
	RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	List<HttpMessageReader<?>> readers = adapter.getMessageReaders();
	assertEquals(13, readers.size());

	ResolvableType multiValueMapType = forClassWithGenerics(MultiValueMap.class, String.class, String.class);

	assertHasMessageReader(readers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(String.class), TEXT_PLAIN);
	assertHasMessageReader(readers, forClass(Resource.class), IMAGE_PNG);
	assertHasMessageReader(readers, forClass(Message.class), new MediaType("application", "x-protobuf"));
	assertHasMessageReader(readers, multiValueMapType, APPLICATION_FORM_URLENCODED);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_XML);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_JSON);
	assertHasMessageReader(readers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
	assertHasMessageReader(readers, forClass(TestBean.class), null);

	WebBindingInitializer bindingInitializer = adapter.getWebBindingInitializer();
	assertNotNull(bindingInitializer);
	WebExchangeDataBinder binder = new WebExchangeDataBinder(new Object());
	bindingInitializer.initBinder(binder);

	name = "webFluxConversionService";
	ConversionService service = context.getBean(name, ConversionService.class);
	assertSame(service, binder.getConversionService());

	name = "webFluxValidator";
	Validator validator = context.getBean(name, Validator.class);
	assertSame(validator, binder.getValidator());
}
 
Example 15
Source Project: spring-cloud-gateway   Source File: ConfigurationService.java    License: Apache License 2.0 5 votes vote down vote up
public ConfigurationService(BeanFactory beanFactory,
		Supplier<ConversionService> conversionService,
		Supplier<Validator> validator) {
	this.beanFactory = beanFactory;
	this.conversionService = conversionService;
	this.validator = validator;
}
 
Example 16
Source Project: java-technology-stack   Source File: DataBinder.java    License: MIT License 5 votes vote down vote up
/**
 * Specify a Spring 3.0 ConversionService to use for converting
 * property values, as an alternative to JavaBeans PropertyEditors.
 */
public void setConversionService(@Nullable ConversionService conversionService) {
	Assert.state(this.conversionService == null, "DataBinder is already initialized with ConversionService");
	this.conversionService = conversionService;
	if (this.bindingResult != null && conversionService != null) {
		this.bindingResult.initConversion(conversionService);
	}
}
 
Example 17
@Test
public void testCreateDefaultConversionService() {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    ConversionServiceResolver resolver = new ConversionServiceResolver(beanFactory);
    ConversionService conversionService = resolver.resolve(false);
    assertTrue(isAssignable(DefaultFormattingConversionService.class, conversionService.getClass()));

    conversionService = resolver.resolve(true);
    assertTrue(isAssignable(DefaultFormattingConversionService.class, conversionService.getClass()));

    conversionService = resolver.resolve();
    assertTrue(isAssignable(DefaultFormattingConversionService.class, conversionService.getClass()));
}
 
Example 18
public ConversionService getConversionService() {
    try {
        return this.applicationContext.getBean(
                ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME,
                ConversionService.class);
    } catch (NoSuchBeanDefinitionException ex) {
        return new Factory(this.applicationContext.getAutowireCapableBeanFactory())
                .create();
    }
}
 
Example 19
@Before
public void setup() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
Example 20
/**
 * A constructor accepting a {@code ConversionService} as well as a default
 * charset.
 *
 * @param conversionService the conversion service
 * @param defaultCharset the default charset
 */
public ObjectToStringHttpMessageConverter(ConversionService conversionService, Charset defaultCharset) {
	super(new MediaType("text", "plain", defaultCharset));

	Assert.notNull(conversionService, "conversionService is required");
	this.conversionService = conversionService;
	this.stringHttpMessageConverter = new StringHttpMessageConverter(defaultCharset);
}
 
Example 21
Source Project: spring4-understanding   Source File: MimeTypeTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void withConversionService() {
	ConversionService conversionService = new DefaultConversionService();
	assertTrue(conversionService.canConvert(String.class, MimeType.class));
	MimeType mimeType = MimeType.valueOf("application/xml");
	assertEquals(mimeType, conversionService.convert("application/xml", MimeType.class));
}
 
Example 22
/**
 * Create a new ConvertingPropertyEditorAdapter for a given
 * {@link org.springframework.core.convert.ConversionService}
 * and the given target type.
 * @param conversionService the ConversionService to delegate to
 * @param targetDescriptor the target type to convert to
 */
public ConvertingPropertyEditorAdapter(ConversionService conversionService, TypeDescriptor targetDescriptor) {
	Assert.notNull(conversionService, "ConversionService must not be null");
	Assert.notNull(targetDescriptor, "TypeDescriptor must not be null");
	this.conversionService = conversionService;
	this.targetDescriptor = targetDescriptor;
	this.canConvertToString = conversionService.canConvert(this.targetDescriptor, TypeDescriptor.valueOf(String.class));
}
 
Example 23
Source Project: spring-analysis-note   Source File: EvalTag.java    License: MIT License 5 votes vote down vote up
private EvaluationContext createEvaluationContext(PageContext pageContext) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new JspPropertyAccessor(pageContext));
	context.addPropertyAccessor(new MapAccessor());
	context.addPropertyAccessor(new EnvironmentAccessor());
	context.setBeanResolver(new BeanFactoryResolver(getRequestContext().getWebApplicationContext()));
	ConversionService conversionService = getConversionService(pageContext);
	if (conversionService != null) {
		context.setTypeConverter(new StandardTypeConverter(conversionService));
	}
	return context;
}
 
Example 24
@Before
public void setUp() {
	ConversionService conversionService = new DefaultConversionService();
	this.converter = new ObjectToStringHttpMessageConverter(conversionService);

	this.servletResponse = new MockHttpServletResponse();
	this.response = new ServletServerHttpResponse(this.servletResponse);
}
 
Example 25
/**
 * Add collection converters.
 * @param converterRegistry the registry of converters to add to (must also be castable to ConversionService,
 * e.g. being a {@link ConfigurableConversionService})
 * @throws ClassCastException if the given ConverterRegistry could not be cast to a ConversionService
 * @since 4.2.3
 */
public static void addCollectionConverters(ConverterRegistry converterRegistry) {
	ConversionService conversionService = (ConversionService) converterRegistry;

	converterRegistry.addConverter(new ArrayToCollectionConverter(conversionService));
	converterRegistry.addConverter(new CollectionToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToArrayConverter(conversionService));
	converterRegistry.addConverter(new CollectionToCollectionConverter(conversionService));
	converterRegistry.addConverter(new MapToMapConverter(conversionService));

	converterRegistry.addConverter(new ArrayToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToArrayConverter(conversionService));

	converterRegistry.addConverter(new ArrayToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToArrayConverter(conversionService));

	converterRegistry.addConverter(new CollectionToStringConverter(conversionService));
	converterRegistry.addConverter(new StringToCollectionConverter(conversionService));

	converterRegistry.addConverter(new CollectionToObjectConverter(conversionService));
	converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));

	if (streamAvailable) {
		converterRegistry.addConverter(new StreamConverter(conversionService));
	}
}
 
Example 26
@Test
public void createDefaultConversionService() {
	ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
	factory.afterPropertiesSet();
	ConversionService service = factory.getObject();
	assertTrue(service.canConvert(String.class, Integer.class));
}
 
Example 27
Source Project: venus-cloud-feign   Source File: VenusFeignAutoConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public VenusSpringMvcContract feignSpringMvcContract(@Autowired(required = false) List<AnnotatedParameterProcessor> parameterProcessors,
                                                     ConversionService conversionService) {
    if (null == parameterProcessors) {
        parameterProcessors = new ArrayList<>();
    }
    return new VenusSpringMvcContract(parameterProcessors, conversionService);
}
 
Example 28
@Bean
public ConversionService webSocketConversionService() {
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new MyTypeToStringConverter());
	conversionService.addConverter(new MyTypeToBytesConverter());
	conversionService.addConverter(new StringToMyTypeConverter());
	conversionService.addConverter(new BytesToMyTypeConverter());
	return conversionService;
}
 
Example 29
@Test
public void defaultCharsetModified() throws IOException {
	ConversionService cs = new DefaultConversionService();
	ObjectToStringHttpMessageConverter converter = new ObjectToStringHttpMessageConverter(cs, StandardCharsets.UTF_16);
	converter.write((byte) 31, null, this.response);

	assertEquals("UTF-16", this.servletResponse.getCharacterEncoding());
}
 
Example 30
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(12, converters.size());
	converters.stream()
			.filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter)
			.forEach(converter -> {
				ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
				assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
				if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
					assertEquals(XmlMapper.class, mapper.getClass());
				}
			});

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}