org.springframework.core.convert.support.GenericConversionService Java Examples

The following examples show how to use org.springframework.core.convert.support.GenericConversionService. 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: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomConverter() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new Converter<String, Float>() {
		@Override
		public Float convert(String source) {
			try {
				NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
				return nf.parse(source).floatValue();
			}
			catch (ParseException ex) {
				throw new IllegalArgumentException(ex);
			}
		}
	});
	lbf.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,1");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("testBean", bd);
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
Example #2
Source File: BooleanExpressionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testConvertAndHandleNull() { // SPR-9445
	// without null conversion
	evaluateAndCheckError("null or true", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");
	evaluateAndCheckError("null and true", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");
	evaluateAndCheckError("!null", SpelMessage.TYPE_CONVERSION_ERROR, 1, "null", "boolean");
	evaluateAndCheckError("null ? 'foo' : 'bar'", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");

	// with null conversion (null -> false)
	GenericConversionService conversionService = new GenericConversionService() {
		@Override
		protected Object convertNullSource(TypeDescriptor sourceType, TypeDescriptor targetType) {
			return targetType.getType() == Boolean.class ? false : null;
		}
	};
	context.setTypeConverter(new StandardTypeConverter(conversionService));

	evaluate("null or true", Boolean.TRUE, Boolean.class, false);
	evaluate("null and true", Boolean.FALSE, Boolean.class, false);
	evaluate("!null", Boolean.TRUE, Boolean.class, false);
	evaluate("null ? 'foo' : 'bar'", "bar", String.class, false);
}
 
Example #3
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCustomConverter() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new Converter<String, Float>() {
		@Override
		public Float convert(String source) {
			try {
				NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
				return nf.parse(source).floatValue();
			}
			catch (ParseException ex) {
				throw new IllegalArgumentException(ex);
			}
		}
	});
	lbf.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,1");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("testBean", bd);
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
Example #4
Source File: DefaultMessageHandlerMethodFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void customConversion() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
		@Override
		public String convert(SampleBean source) {
			return "foo bar";
		}
	});
	instance.setConversionService(conversionService);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
	assertMethodInvocation(sample, "simpleString");
}
 
Example #5
Source File: OpPlusTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void test_binaryPlusWithTimeConverted() {
	SimpleDateFormat format = new SimpleDateFormat("hh :--: mm :--: ss", Locale.ENGLISH);

	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(Time.class, String.class, format::format);

	StandardEvaluationContext evaluationContextConverter = new StandardEvaluationContext();
	evaluationContextConverter.setTypeConverter(new StandardTypeConverter(conversionService));

	ExpressionState expressionState = new ExpressionState(evaluationContextConverter);
	Time time = new Time(new Date().getTime());

	VariableReference var = new VariableReference("timeVar", -1, -1);
	var.setValue(expressionState, time);

	StringLiteral n2 = new StringLiteral("\" is now\"", -1, -1, "\" is now\"");
	OpPlus o = new OpPlus(-1, -1, var, n2);
	TypedValue value = o.getValueInternal(expressionState);

	assertEquals(String.class, value.getTypeDescriptor().getObjectType());
	assertEquals(String.class, value.getTypeDescriptor().getType());
	assertEquals(format.format(time) + " is now", value.getValue());
}
 
Example #6
Source File: ProjectImportDataServiceImpl.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
protected GenericConversionService getConversionService(Workbook workbook,
		Map<String, Map<String, GenericEntity<Long, ?>>> idsMapping) {
	GenericConversionService service = new GenericConversionService();

	GenericEntityConverter genericEntityConverter = new GenericEntityConverter(importDataDao, workbook,
			new HashMap<Class<?>, Class<?>>(0), idsMapping);
	genericEntityConverter.setConversionService(service);
	service.addConverter(genericEntityConverter);

	service.addConverter(new ProjectConverter());
	service.addConverter(new ArtifactConverter());
	service.addConverter(new ExternalLinkWrapperConverter());

	DefaultConversionService.addDefaultConverters(service);

	return service;
}
 
Example #7
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCustomConverter() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	GenericConversionService conversionService = new DefaultConversionService();
	conversionService.addConverter(new Converter<String, Float>() {
		@Override
		public Float convert(String source) {
			try {
				NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
				return nf.parse(source).floatValue();
			}
			catch (ParseException ex) {
				throw new IllegalArgumentException(ex);
			}
		}
	});
	lbf.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,1");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("testBean", bd);
	TestBean testBean = (TestBean) lbf.getBean("testBean");
	assertTrue(testBean.getMyFloat().floatValue() == 1.1f);
}
 
Example #8
Source File: DefaultMessageHandlerMethodFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void customConversion() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
		@Override
		public String convert(SampleBean source) {
			return "foo bar";
		}
	});
	instance.setConversionService(conversionService);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
	assertMethodInvocation(sample, "simpleString");
}
 
Example #9
Source File: BooleanExpressionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testConvertAndHandleNull() { // SPR-9445
	// without null conversion
	evaluateAndCheckError("null or true", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");
	evaluateAndCheckError("null and true", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");
	evaluateAndCheckError("!null", SpelMessage.TYPE_CONVERSION_ERROR, 1, "null", "boolean");
	evaluateAndCheckError("null ? 'foo' : 'bar'", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");

	// with null conversion (null -> false)
	GenericConversionService conversionService = new GenericConversionService() {
		@Override
		protected Object convertNullSource(TypeDescriptor sourceType, TypeDescriptor targetType) {
			return targetType.getType() == Boolean.class ? false : null;
		}
	};
	context.setTypeConverter(new StandardTypeConverter(conversionService));

	evaluate("null or true", Boolean.TRUE, Boolean.class, false);
	evaluate("null and true", Boolean.FALSE, Boolean.class, false);
	evaluate("!null", Boolean.TRUE, Boolean.class, false);
	evaluate("null ? 'foo' : 'bar'", "bar", String.class, false);
}
 
Example #10
Source File: CustomConversions.java    From spring-data-crate with Apache License 2.0 6 votes vote down vote up
/**
 * Populates the given {@link GenericConversionService} with the converters registered.
 *
 * @param conversionService the service to register.
 */
public void registerConvertersIn(final GenericConversionService conversionService) {
  for (Object converter : converters) {
    boolean added = false;

    if (converter instanceof Converter) {
      conversionService.addConverter((Converter<?, ?>) converter);
      added = true;
    }

    if (converter instanceof ConverterFactory) {
      conversionService.addConverterFactory((ConverterFactory<?, ?>) converter);
      added = true;
    }

    if (converter instanceof GenericConverter) {
      conversionService.addConverter((GenericConverter) converter);
      added = true;
    }

    if (!added) {
      throw new IllegalArgumentException("Given set contains element that is neither Converter nor ConverterFactory!");
    }
  }
}
 
Example #11
Source File: CustomConversions.java    From dubbox with Apache License 2.0 6 votes vote down vote up
/**
 * Register custom converters within given
 * {@link org.springframework.core.convert.support.GenericConversionService}
 *
 * @param conversionService
 *            must not be null
 */
public void registerConvertersIn(GenericConversionService conversionService) {
	Assert.notNull(conversionService);

	for (Object converter : converters) {
		if (converter instanceof Converter) {
			conversionService.addConverter((Converter<?, ?>) converter);
		} else if (converter instanceof ConverterFactory) {
			conversionService.addConverterFactory((ConverterFactory<?, ?>) converter);
		} else if (converter instanceof GenericConverter) {
			conversionService.addConverter((GenericConverter) converter);
		} else {
			throw new IllegalArgumentException("Given object '" + converter
					+ "' expected to be a Converter, ConverterFactory or GenericeConverter!");
		}
	}
}
 
Example #12
Source File: DefaultMessageHandlerMethodFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void customConversion() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
		@Override
		public String convert(SampleBean source) {
			return "foo bar";
		}
	});
	instance.setConversionService(conversionService);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	invocableHandlerMethod.invoke(MessageBuilder.withPayload(sample).build());
	assertMethodInvocation(sample, "simpleString");
}
 
Example #13
Source File: GenericMapConverterTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void noDelegateMapConversion() {
	GenericConversionService conversionService = new GenericConversionService();
	GenericMapConverter mapConverter = new GenericMapConverter(conversionService);
	conversionService.addConverter(mapConverter);

	@SuppressWarnings("unchecked")
	Map<String, String> result = conversionService.convert("foo = bar, wizz = jogg", Map.class);
	assertThat(result, hasEntry("foo", "bar"));
	assertThat(result, hasEntry("wizz", "jogg"));

	assertThat(
			conversionService.canConvert(TypeDescriptor.valueOf(String.class), TypeDescriptor.map(Map.class,
					TypeDescriptor.valueOf(GenericMapConverterTests.class), TypeDescriptor.valueOf(Integer.class))),
			is(false));
}
 
Example #14
Source File: Spr7766Tests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@Deprecated
public void test() throws Exception {
	AnnotationMethodHandlerAdapter adapter = new AnnotationMethodHandlerAdapter();
	ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer();
	GenericConversionService service = new DefaultConversionService();
	service.addConverter(new ColorConverter());
	binder.setConversionService(service);
	adapter.setWebBindingInitializer(binder);
	Spr7766Controller controller = new Spr7766Controller();
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setRequestURI("/colors");
	request.setPathInfo("/colors");
	request.addParameter("colors", "#ffffff,000000");
	MockHttpServletResponse response = new MockHttpServletResponse();
	adapter.handle(request, response, controller);
}
 
Example #15
Source File: BooleanExpressionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertAndHandleNull() { // SPR-9445
	// without null conversion
	evaluateAndCheckError("null or true", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");
	evaluateAndCheckError("null and true", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");
	evaluateAndCheckError("!null", SpelMessage.TYPE_CONVERSION_ERROR, 1, "null", "boolean");
	evaluateAndCheckError("null ? 'foo' : 'bar'", SpelMessage.TYPE_CONVERSION_ERROR, 0, "null", "boolean");

	// with null conversion (null -> false)
	GenericConversionService conversionService = new GenericConversionService() {
		@Override
		protected Object convertNullSource(TypeDescriptor sourceType, TypeDescriptor targetType) {
			return targetType.getType() == Boolean.class ? false : null;
		}
	};
	eContext.setTypeConverter(new StandardTypeConverter(conversionService));

	evaluate("null or true", Boolean.TRUE, Boolean.class, false);
	evaluate("null and true", Boolean.FALSE, Boolean.class, false);
	evaluate("!null", Boolean.TRUE, Boolean.class, false);
	evaluate("null ? 'foo' : 'bar'", "bar", String.class, false);
}
 
Example #16
Source File: ApplicationContextExpressionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void prototypeCreationReevaluatesExpressions() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
	GenericConversionService cs = new GenericConversionService();
	cs.addConverter(String.class, String.class, new Converter<String, String>() {
		@Override
		public String convert(String source) {
			return source.trim();
		}
	});
	ac.getBeanFactory().registerSingleton(GenericApplicationContext.CONVERSION_SERVICE_BEAN_NAME, cs);
	RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.getPropertyValues().add("country", "#{systemProperties.country}");
	rbd.getPropertyValues().add("country2", new TypedStringValue("-#{systemProperties.country}-"));
	ac.registerBeanDefinition("test", rbd);
	ac.refresh();

	try {
		System.getProperties().put("name", "juergen1");
		System.getProperties().put("country", " UK1 ");
		PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen1", tb.getName());
		assertEquals("UK1", tb.getCountry());
		assertEquals("-UK1-", tb.getCountry2());

		System.getProperties().put("name", "juergen2");
		System.getProperties().put("country", "  UK2  ");
		tb = (PrototypeTestBean) ac.getBean("test");
		assertEquals("juergen2", tb.getName());
		assertEquals("UK2", tb.getCountry());
		assertEquals("-UK2-", tb.getCountry2());
	}
	finally {
		System.getProperties().remove("name");
		System.getProperties().remove("country");
	}
}
 
Example #17
Source File: MicaConversionService.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Return a shared default application {@code ConversionService} instance, lazily
 * building it once needed.
 * <p>
 * Note: This method actually returns an {@link MicaConversionService}
 * instance. However, the {@code ConversionService} signature has been preserved for
 * binary compatibility.
 *
 * @return the shared {@code MicaConversionService} instance (never{@code null})
 */
public static GenericConversionService getInstance() {
	MicaConversionService sharedInstance = MicaConversionService.SHARED_INSTANCE;
	if (sharedInstance == null) {
		synchronized (MicaConversionService.class) {
			sharedInstance = MicaConversionService.SHARED_INSTANCE;
			if (sharedInstance == null) {
				sharedInstance = new MicaConversionService();
				MicaConversionService.SHARED_INSTANCE = sharedInstance;
			}
		}
	}
	return sharedInstance;
}
 
Example #18
Source File: Spr7839Tests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer();
	GenericConversionService service = new DefaultConversionService();
	service.addConverter(new Converter<String, NestedBean>() {
		@Override
		public NestedBean convert(String source) {
			return new NestedBean(source);
		}
	});
	binder.setConversionService(service);
	adapter.setWebBindingInitializer(binder);
}
 
Example #19
Source File: OpPlusTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void test_binaryPlusWithTimeConverted() {

	final SimpleDateFormat format = new SimpleDateFormat("hh :--: mm :--: ss", Locale.ENGLISH);

	GenericConversionService conversionService = new GenericConversionService();
	conversionService.addConverter(new Converter<Time, String>() {
		@Override
		public String convert(Time source) {
			return format.format(source);
		}
	});

	StandardEvaluationContext evaluationContextConverter = new StandardEvaluationContext();
	evaluationContextConverter.setTypeConverter(new StandardTypeConverter(conversionService));

	ExpressionState expressionState = new ExpressionState(evaluationContextConverter);

	Time time = new Time(new Date().getTime());

	VariableReference var = new VariableReference("timeVar", -1);
	var.setValue(expressionState, time);

	StringLiteral n2 = new StringLiteral("\" is now\"", -1, "\" is now\"");
	OpPlus o = new OpPlus(-1, var, n2);
	TypedValue value = o.getValueInternal(expressionState);

	assertEquals(String.class, value.getTypeDescriptor().getObjectType());
	assertEquals(String.class, value.getTypeDescriptor().getType());
	assertEquals(format.format(time) + " is now", value.getValue());
}
 
Example #20
Source File: AbstractPropertyAccessorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void setPropertyIntermediateListIsNullWithBadConversionService() {
	Foo target = new Foo();
	AbstractPropertyAccessor accessor = createAccessor(target);
	accessor.setConversionService(new GenericConversionService() {
		@Override
		public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
			throw new ConversionFailedException(sourceType, targetType, source, null);
		}
	});
	accessor.setAutoGrowNestedPaths(true);
	accessor.setPropertyValue("listOfMaps[0]['luckyNumber']", "9");
	assertEquals("9", target.listOfMaps.get(0).get("luckyNumber"));
}
 
Example #21
Source File: DefaultMessageHandlerMethodFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void customConversionServiceFailure() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	GenericConversionService conversionService = new GenericConversionService();
	assertFalse("conversion service should fail to convert payload",
			conversionService.canConvert(Integer.class, String.class));
	instance.setConversionService(conversionService);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	thrown.expect(MessageConversionException.class);
	invocableHandlerMethod.invoke(MessageBuilder.withPayload(123).build());
}
 
Example #22
Source File: MappingCosmosConverter.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
public MappingCosmosConverter(
    MappingContext<? extends CosmosPersistentEntity<?>, CosmosPersistentProperty> mappingContext,
    @Qualifier(Constants.OBJECTMAPPER_BEAN_NAME) ObjectMapper objectMapper) {
    this.mappingContext = mappingContext;
    this.conversionService = new GenericConversionService();
    this.objectMapper = objectMapper == null ? ObjectMapperFactory.getObjectMapper() :
        objectMapper;
}
 
Example #23
Source File: DefaultMessageHandlerMethodFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void customConversionServiceFailure() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	GenericConversionService conversionService = new GenericConversionService();
	assertFalse("conversion service should fail to convert payload",
			conversionService.canConvert(Integer.class, String.class));
	instance.setConversionService(conversionService);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() ->
			invocableHandlerMethod.invoke(MessageBuilder.withPayload(123).build()));
}
 
Example #24
Source File: ConvertUtil.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Convenience operation for converting a source object to the specified targetType.
 * {@link TypeDescriptor#forObject(Object)}.
 * @param source the source object
 * @param targetType the target type
 * @param <T> 泛型标记
 * @return the converted value
 * @throws IllegalArgumentException if targetType is {@code null},
 * or sourceType is {@code null} but source is not {@code null}
 */
@Nullable
public static <T> T convert(@Nullable Object source, Class<T> targetType) {
	if (source == null) {
		return null;
	}
	if (ClassUtil.isAssignableValue(targetType, source)) {
		return (T) source;
	}
	GenericConversionService conversionService = MicaConversionService.getInstance();
	return conversionService.convert(source, targetType);
}
 
Example #25
Source File: DefaultBinderFactory.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void customizeParentChildContextRelationship(SpringApplicationBuilder applicationBuilder, ApplicationContext context) {
	if (context != null) {
		Map<String, ListenerContainerCustomizer> customizers = context.getBeansOfType(ListenerContainerCustomizer.class);
		applicationBuilder.initializers(childContext -> {
			if (!CollectionUtils.isEmpty(customizers)) {
				for (Entry<String, ListenerContainerCustomizer> customizerEntry : customizers.entrySet()) {
					ListenerContainerCustomizer customizerWrapper = new ListenerContainerCustomizer() {
						@Override
						public void configure(Object container, String destinationName, String group) {
							try {
								customizerEntry.getValue().configure(container, destinationName, group);
							}
							catch (Exception e) {
								logger.warn("Failed while applying ListenerContainerCustomizer. In situations when multiple "
										+ "binders are used this is expected, since a particular customizer may not be applicable"
										+ "to a particular binder. Customizer: " + customizerEntry.getValue()
										+ " Binder: " + childContext.getBean(AbstractMessageChannelBinder.class), e);
							}
						}
					};

					((GenericApplicationContext) childContext).registerBean(customizerEntry.getKey(),
							ListenerContainerCustomizer.class, () -> customizerWrapper);
				}
			}
			GenericConversionService cs = (GenericConversionService) ((GenericApplicationContext) childContext).getBeanFactory().getConversionService();
			SpelConverter spelConverter = new SpelConverter();
			cs.addConverter(spelConverter);
		});
	}
}
 
Example #26
Source File: String2DateConfig.java    From Guns with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 默认时间转化器
 */
@PostConstruct
public void addConversionConfig() {
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
    if ((initializer != null ? initializer.getConversionService() : null) != null) {
        GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
        genericConversionService.addConverter(new StringToDateConverter());
    }
}
 
Example #27
Source File: BindingServiceProperties.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext)
		throws BeansException {
	this.applicationContext = (ConfigurableApplicationContext) applicationContext;
	GenericConversionService cs = (GenericConversionService) IntegrationUtils
			.getConversionService(this.applicationContext.getBeanFactory());
	if (this.applicationContext.containsBean("spelConverter")) {
		Converter<?, ?> converter = (Converter<?, ?>) this.applicationContext
				.getBean("spelConverter");
		cs.addConverter(converter);
	}
}
 
Example #28
Source File: BladeConversionService.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Return a shared default application {@code ConversionService} instance, lazily
 * building it once needed.
 * <p>
 * Note: This method actually returns an {@link BladeConversionService}
 * instance. However, the {@code ConversionService} signature has been preserved for
 * binary compatibility.
 * @return the shared {@code BladeConversionService} instance (never{@code null})
 */
public static GenericConversionService getInstance() {
	BladeConversionService sharedInstance = BladeConversionService.SHARED_INSTANCE;
	if (sharedInstance == null) {
		synchronized (BladeConversionService.class) {
			sharedInstance = BladeConversionService.SHARED_INSTANCE;
			if (sharedInstance == null) {
				sharedInstance = new BladeConversionService();
				BladeConversionService.SHARED_INSTANCE = sharedInstance;
			}
		}
	}
	return sharedInstance;
}
 
Example #29
Source File: RelaxedConversionService.java    From canal with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link RelaxedConversionService} instance.
 *
 * @param conversionService and option root conversion service
 */
RelaxedConversionService(ConversionService conversionService){
    this.conversionService = conversionService;
    this.additionalConverters = new GenericConversionService();
    DefaultConversionService.addCollectionConverters(this.additionalConverters);
    this.additionalConverters
        .addConverterFactory(new RelaxedConversionService.StringToEnumIgnoringCaseConverterFactory());
    this.additionalConverters.addConverter(new StringToCharArrayConverter());
}
 
Example #30
Source File: SpannerCustomConverter.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param customConversions must not be null.
 * @param conversionService if null, then {@link DefaultConversionService} is used.
 */
SpannerCustomConverter(CustomConversions customConversions,
															GenericConversionService conversionService) {
	Assert.notNull(customConversions, "Valid custom conversions are required!");
	this.conversionService = (conversionService != null) ? conversionService : new DefaultConversionService();

	customConversions.registerConvertersIn(this.conversionService);
}