org.springframework.core.convert.ConversionService Java Examples
The following examples show how to use
org.springframework.core.convert.ConversionService.
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: WxApiParamContributor.java From FastBootWeixin with Apache License 2.0 | 6 votes |
@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 #2
Source File: ConversionServiceResolver.java From spring-context-support with Apache License 2.0 | 6 votes |
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 #3
Source File: RequestParamMethodArgumentResolver.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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 #4
Source File: ConfigurationUtils.java From spring-cloud-gray with Apache License 2.0 | 6 votes |
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 #5
Source File: DefaultConversionService.java From spring-analysis-note with MIT License | 6 votes |
/** * 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 #6
Source File: ServletModelAttributeMethodProcessor.java From java-technology-stack with MIT License | 6 votes |
/** * 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 #7
Source File: EntityExpressionSupport.java From springlets with Apache License 2.0 | 5 votes |
public EntityExpressionSupport(ExpressionParser parser, TemplateParserContext templateParserContext, ConversionService conversionService, String defaultExpression) { this.parser = parser; this.templateParserContext = templateParserContext; this.defaultExpression = defaultExpression; this.conversionService = conversionService; }
Example #8
Source File: ConversionServiceResolverTest.java From spring-context-support with Apache License 2.0 | 5 votes |
@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 #9
Source File: DataBinder.java From java-technology-stack with MIT License | 5 votes |
/** * 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 #10
Source File: ConfigurationService.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
public ConfigurationService(BeanFactory beanFactory, Supplier<ConversionService> conversionService, Supplier<Validator> validator) { this.beanFactory = beanFactory; this.conversionService = conversionService; this.validator = validator; }
Example #11
Source File: WebFluxConfigurationSupportTests.java From java-technology-stack with MIT License | 5 votes |
@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 #12
Source File: ConversionServiceDeducer.java From spring-cloud-gray with Apache License 2.0 | 5 votes |
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 #13
Source File: TypeConversionConfiguration.java From camel-spring-boot with Apache License 2.0 | 5 votes |
@ConditionalOnMissingBean @Bean ConversionService defaultCamelConversionService(ApplicationContext applicationContext) { DefaultConversionService service = new DefaultConversionService(); for (Converter converter : applicationContext.getBeansOfType(Converter.class).values()) { service.addConverter(converter); } return service; }
Example #14
Source File: InitBinderBindingContextTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #15
Source File: UserGroupController.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
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 #16
Source File: BounceFilterController.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
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 #17
Source File: SpringTypeConverter.java From camel-spring-boot with Apache License 2.0 | 5 votes |
@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 #18
Source File: DefaultJpaStoreImpl.java From spring-content with Apache License 2.0 | 5 votes |
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 #19
Source File: ObjectToStringHttpMessageConverterTests.java From java-technology-stack with MIT License | 5 votes |
@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
Source File: ObjectToStringHttpMessageConverter.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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 File: MimeTypeTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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
Source File: ConvertingPropertyEditorAdapter.java From lams with GNU General Public License v2.0 | 5 votes |
/** * 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 File: EvalTag.java From spring-analysis-note with MIT License | 5 votes |
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
Source File: ObjectToStringHttpMessageConverterTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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
Source File: DefaultConversionService.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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
Source File: ConversionServiceFactoryBeanTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void createDefaultConversionService() { ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean(); factory.afterPropertiesSet(); ConversionService service = factory.getObject(); assertTrue(service.canConvert(String.class, Integer.class)); }
Example #27
Source File: VenusFeignAutoConfig.java From venus-cloud-feign with Apache License 2.0 | 5 votes |
@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
Source File: ConvertingEncoderDecoderSupportTests.java From spring-analysis-note with MIT License | 5 votes |
@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
Source File: ObjectToStringHttpMessageConverterTests.java From spring-analysis-note with MIT License | 5 votes |
@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
Source File: WebMvcConfigurationSupportTests.java From java-technology-stack with MIT License | 5 votes |
@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()); }