public HandlerMethodService(ConversionService conversionService, List<HandlerMethodArgumentResolver> customArgumentResolvers, ObjectMapper objectMapper, ApplicationContext applicationContext) { this.conversionService = conversionService; this.parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); this.argumentResolvers = new HandlerMethodArgumentResolverComposite(); ConfigurableBeanFactory beanFactory = ClassUtils.isAssignableValue( ConfigurableApplicationContext.class, applicationContext) ? ((ConfigurableApplicationContext) applicationContext) .getBeanFactory() : null; this.argumentResolvers.addResolver( new HeaderMethodArgumentResolver(this.conversionService, beanFactory)); this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver()); this.argumentResolvers.addResolver(new WampMessageMethodArgumentResolver()); this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver()); this.argumentResolvers.addResolver(new WampSessionIdMethodArgumentResolver()); this.argumentResolvers.addResolvers(customArgumentResolvers); this.objectMapper = objectMapper; }
protected Object[] getArguments(Step step, StepImplementation implementation) { Method method = implementation.getMethod(); Parameter[] parameters = method.getParameters(); Object[] arguments = new Object[parameters.length]; if (parameters.length > 0) { String text = step.getText(); Pattern pattern = implementation.getPattern(); Matcher matcher = pattern.matcher(text); checkState(matcher.find(), "unable to locate substitution parameters for pattern %s with input %s", pattern.pattern(), text); int groupCount = matcher.groupCount(); ConversionService conversionService = SpringPreProcessor.getBean(ConversionService.class); for (int i = 0; i < groupCount; i++) { String parameterAsString = matcher.group(i + 1); Parameter parameter = parameters[i]; Class<?> parameterType = parameter.getType(); Object converted = conversionService.convert(parameterAsString, parameterType); arguments[i] = converted; } } return arguments; }
@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.equals(paramType) || "javax.servlet.http.Part".equals(paramType.getName())) { return; } RequestParam annot = parameter.getParameterAnnotation(RequestParam.class); String name = StringUtils.isEmpty(annot.value()) ? parameter.getParameterName() : annot.value(); 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)); } }
/** * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } // Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes. beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. beanFactory.preInstantiateSingletons(); }
public static Object normaliseValueForPut(Object value, ConversionService conversionService) { if (value instanceof Document) { return conversionService.convert(value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(IData.class)); } else if (value instanceof Document[]) { return conversionService.convert(value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(IData[].class)); } else if (value instanceof Iterable<?>) { if (CollectionUtil.areAllElementsOfType((Collection<?>) value, Document.class)) { return conversionService.convert(value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(IData[].class)); } else { return value; } } else { return value; } }
@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)); } }
@Override protected void setEntryValue(Map nativeEntry, String key, Object value) { if (value == null || !shouldConvert(value)) { return; } Class type = value.getClass(); if(value != null && type.isArray() && byte.class.isAssignableFrom(type.getComponentType())) { nativeEntry.put(key, SafeEncoder.encode((byte[])value)); } else { final ConversionService conversionService = getMappingContext().getConversionService(); nativeEntry.put(key, conversionService.convert(value, String.class)); } }
/** * Add converters appropriate for most environments. * @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 */ public static void addDefaultConverters(ConverterRegistry converterRegistry) { addScalarConverters(converterRegistry); addCollectionConverters(converterRegistry); converterRegistry.addConverter(new ByteBufferConverter((ConversionService) converterRegistry)); if (jsr310Available) { Jsr310ConverterRegistrar.registerJsr310Converters(converterRegistry); } converterRegistry.addConverter(new ObjectToObjectConverter()); converterRegistry.addConverter(new IdToEntityConverter((ConversionService) converterRegistry)); converterRegistry.addConverter(new FallbackObjectToStringConverter()); if (javaUtilOptionalClassAvailable) { converterRegistry.addConverter(new ObjectToOptionalConverter((ConversionService) converterRegistry)); } }
public static boolean canConvertElements(TypeDescriptor sourceElementType, TypeDescriptor targetElementType, ConversionService conversionService) { if (targetElementType == null) { // yes return true; } if (sourceElementType == null) { // maybe return true; } if (conversionService.canConvert(sourceElementType, targetElementType)) { // yes return true; } else if (sourceElementType.getType().isAssignableFrom(targetElementType.getType())) { // maybe; return true; } else { // no; return false; } }
private static Object convertProperty(BeanWrapper parentBean, String property, ConversionService conversionService, Map<String, Object> parentValue) { TypeDescriptor source = parentBean.getPropertyTypeDescriptor(property); Object propertyValue = parentBean.getPropertyValue(property); int dotIndex = property.indexOf('.'); if (dotIndex > 0) { String baseProperty = property.substring(0, dotIndex); String childProperty = property.substring(dotIndex + 1); Map<String, Object> childValue = getChildValue(parentValue, baseProperty, childProperty); BeanWrapper childBean = new BeanWrapperImpl(parentBean.getPropertyValue(baseProperty)); Object convertedProperty = convertProperty(childBean, childProperty, conversionService, childValue); childValue.put(childProperty, convertedProperty); return childValue; } else { String convertedPropertyValue = (String) conversionService.convert(propertyValue, source, TYPE_STRING); return convertedPropertyValue; } }
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; }
@Test public void requestMappingHandlerAdapter() throws Exception { delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter(); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); ConversionService initializerConversionService = initializer.getConversionService(); assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean); verify(webMvcConfigurer).configureMessageConverters(converters.capture()); verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture()); verify(webMvcConfigurer).addFormatters(conversionService.capture()); verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture()); verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture()); verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture()); assertSame(conversionService.getValue(), initializerConversionService); assertEquals(0, resolvers.getValue().size()); assertEquals(0, handlers.getValue().size()); assertEquals(converters.getValue(), adapter.getMessageConverters()); assertNotNull(asyncConfigurer); }
@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)); } }
/** * 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} * @throws Exception */ 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; }
/** * 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 org.springframework.core.convert.converter.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} * @throws Exception */ 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; }
private String convertValueToDurationIfPossible(final String value) { try { final ConversionService service = applicationContext.getEnvironment().getConversionService(); final Duration dur = service.convert(value, Duration.class); if (dur != null) { return String.valueOf(dur.toMillis()); } } catch (final ConversionFailedException e) { LOGGER.trace(e.getMessage()); } return null; }
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (beanFactory instanceof AbstractBeanFactory) { AbstractBeanFactory bf = ((AbstractBeanFactory) beanFactory); ConversionService cs = bf.getConversionService(); if (cs instanceof SpringBlueprintConverterService) { cs = null; } SpringBlueprintConverterService sbc = new SpringBlueprintConverterService(cs, bf); sbc.add(converters); bf.setConversionService(sbc); } }
public void initConversion(ConversionService conversionService) { Assert.notNull(conversionService, "ConversionService must not be null"); this.conversionService = conversionService; if (getTarget() != null) { getPropertyAccessor().setConversionService(conversionService); } }
/** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. */ public void setConversionService(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); } }
@Override public void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) { for (UriComponentsContributor contributor : this.contributors) { if (contributor.supportsParameter(parameter)) { contributor.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService); break; } } }
/** * 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); }
public PrinterConverter(Class<?> fieldType, Printer<?> printer, ConversionService conversionService) { this.fieldType = fieldType; this.printerObjectType = TypeDescriptor.valueOf(resolvePrinterObjectType(printer)); this.printer = printer; this.conversionService = conversionService; }
/** * Create a new instance. * * @param searchMetadata Search metadata. * @param conversionService Conversion service. */ public SearchServiceImpl(SearchMetadata searchMetadata, ConversionService conversionService) { this.searchMetadata = searchMetadata; this.conversionService = conversionService; documentBuilder = new DocumentBuilder(searchMetadata, conversionService); queryCompiler = new QueryCompiler(searchMetadata, conversionService); }
/** * Configures and registers the search service. * Also configures the {@link org.springframework.core.convert.ConversionService} used by the search API. * * @return Search service bean. */ @Bean public SearchService searchService() { ConversionService conversionService = createConversionService(); return new SearchServiceImpl(searchMetadata(), conversionService); }
/** * @param environment Spring Environment * @param beanName name of Conversion Service bean Martini should utilize * @return specified, or Environment default, conversion service. */ @Lazy @Bean ConversionService getConversionService( AbstractEnvironment environment, @Value("${conversion.service.bean.name:#{null}}") String beanName ) { return null == beanName ? environment.getConversionService() : beanFactory.getBean(beanName, ConversionService.class); }
private ConversionService createInternalConversionService(ConversionService baseConversionService) { List<ConversionService> conversionServices = new ArrayList<ConversionService>(); conversionServices.add(createIDataResourceConversionService()); conversionServices.add(baseConversionService); return new OverlayedConversionService(conversionServices); }
public OverlayedConversionService(List<ConversionService> conversionServices) { super(); this.conversionServices = Preconditions.checkNotEmpty(conversionServices); this.last = conversionServices.get(conversionServices.size() - 1); this.allButLast = new ArrayList<ConversionService>(conversionServices.size() - 1); for (int i = 0; i < conversionServices.size() - 1; i++) { allButLast.add(conversionServices.get(i)); } }
@Override public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) { for (ConversionService conversionService : conversionServices) { if (conversionService.canConvert(sourceType, targetType)) { return true; } } return false; }
@Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { for (ConversionService conversionService : allButLast) { if (conversionService.canConvert(sourceType, targetType)) { return conversionService.convert(source, sourceType, targetType); } } return last.convert(source, sourceType, targetType); }
@Override public void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) { if (Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) { return; } WxApiPath wx = parameter.getParameterAnnotation(WxApiPath.class); String name = (wx != null && !StringUtils.isEmpty(wx.value()) ? wx.value() : parameter.getParameterName()); WxAppAssert.notNull(name, "请添加编译器的-parameter或者为参数添加注解名称"); value = formatUriValue(conversionService, new TypeDescriptor(parameter.nestedIfOptional()), value); uriVariables.put(name, value); }
/** * 把参数格式化成字符串用于拼接url * * @param cs * @param sourceType * @param value * @return dummy */ protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) { if (value == null) { return null; } else if (value instanceof String) { return (String) value; } else if (cs != null) { return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR); } else { return value.toString(); } }
public ConversionServicePropertySerializer( ConversionService conversionService, TypeDescriptor sourceType, TypeDescriptor targetType) { super(Object.class); this.conversionService = conversionService; this.sourceType = sourceType; this.targetType = targetType; }
/** * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } // Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { return getEnvironment().resolvePlaceholders(strVal); } }); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } // Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes. beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. beanFactory.preInstantiateSingletons(); // 实例化所有剩下的非延迟初始化的单例 }
@Test public void createDefaultConversionService() { ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean(); factory.afterPropertiesSet(); ConversionService service = factory.getObject(); assertTrue(service.canConvert(String.class, Integer.class)); }
public ConversionServiceConverter(ConversionService conversionService, Class<? extends T> targetType) { Assert.notNull(conversionService, "ConversionService must not be null"); Assert.notNull(targetType, "TargetType must not be null"); this.conversionService = conversionService; this.targetType = targetType; }