private static GenericConversionService safeConversionService() { final GenericConversionService converter = new GenericConversionService(); converter.addConverter(Object.class, byte[].class, new SerializingConverter()); final DeserializingConverter byteConverter = new DeserializingConverter(); converter.addConverter(byte[].class, Object.class, (byte[] bytes) -> { try { return byteConverter.convert(bytes); } catch (SerializationFailedException e) { LOG.error("Could not extract attribute: {}", e.getMessage()); return null; } }); return converter; }
private static void addDateConverters(GenericConversionService conversionService) { conversionService.addConverter(Date.class, String.class, new Converter<Date, String>() { @Override public String convert(Date dateVal) { return ValueConversionUtil.dateToIsoString(dateVal); } }); conversionService.addConverter(String.class, Date.class, blankConverter(new Converter<String, Date>() { @Override public Date convert(String stringVal) { return ValueConversionUtil.isoStringToDate(stringVal); } })); }
@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"); }
@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); }
@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); }
@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); }
@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)); }
/** * 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!"); } } }
@SuppressWarnings("resource") @Before public void setup() throws Exception { DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory(); dlbf.registerSingleton("mvcValidator", testValidator()); GenericApplicationContext ctx = new GenericApplicationContext(dlbf); ctx.refresh(); this.resolver = new PayloadArgumentResolver(ctx, new MethodParameterConverter( new ObjectMapper(), new GenericConversionService())); this.payloadMethod = getClass().getDeclaredMethod("handleMessage", String.class, String.class, String.class, String.class, String.class, String.class, String.class, Integer.class); this.paramAnnotated = getMethodParameter(this.payloadMethod, 0); this.paramAnnotatedNotRequired = getMethodParameter(this.payloadMethod, 1); this.paramAnnotatedRequired = getMethodParameter(this.payloadMethod, 2); this.paramWithSpelExpression = getMethodParameter(this.payloadMethod, 3); this.paramValidated = getMethodParameter(this.payloadMethod, 4); this.paramValidated.initParameterNameDiscovery( new LocalVariableTableParameterNameDiscoverer()); this.paramValidatedNotAnnotated = getMethodParameter(this.payloadMethod, 5); this.paramNotAnnotated = getMethodParameter(this.payloadMethod, 6); }
/** * 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!"); } } }
/** * Register custom converters within given {@link 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!"); } } }
/** * Sets up the bean post processor and conversion service * * @param beans - The bean factory for the the dictionary beans */ public static void setupProcessor(DefaultListableBeanFactory beans) { try { // UIF post processor that sets component ids BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance(); beans.addBeanPostProcessor(idPostProcessor); beans.setBeanExpressionResolver(new StandardBeanExpressionResolver() { @Override protected void customizeEvaluationContext(StandardEvaluationContext evalContext) { try { evalContext.registerFunction("getService", ExpressionFunctions.class.getDeclaredMethod("getService", new Class[]{String.class})); } catch(NoSuchMethodException me) { LOG.error("Unable to register custom expression to data dictionary bean factory", me); } } }); // special converters for shorthand map and list property syntax GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(new StringMapConverter()); conversionService.addConverter(new StringListConverter()); beans.setConversionService(conversionService); } catch (Exception e1) { throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(), e1); } }
/** * Sets up the bean post processor and conversion service * * @param beans - The bean factory for the the dictionary beans */ public static void setupProcessor(KualiDefaultListableBeanFactory beans) { try { // UIF post processor that sets component ids BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance(); beans.addBeanPostProcessor(idPostProcessor); beans.setBeanExpressionResolver(new StandardBeanExpressionResolver()); // special converters for shorthand map and list property syntax GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(new StringMapConverter()); conversionService.addConverter(new StringListConverter()); beans.setConversionService(conversionService); } catch (Exception e1) { throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(), e1); } }
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; }
@Before public void setUp() throws NoSuchFieldException { GenericConversionService genericConversionService = new GenericConversionService(); genericConversionService.addConverter(new Converter<String, Integer>() { @Override public Integer convert(String source) { if (0 == source.length()) { return null; } return NumberUtils.parseNumber(source, Integer.class); } }); Mockito.when(conversionServiceFactoryBean.getObject()).thenReturn(genericConversionService); mockCartEntry(); mockProduct(); }
/** * Populates the given {@link GenericConversionService} with the convertes registered. * * @param conversionService */ public void registerConvertersIn(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!"); } } }
@Test public void testCustomDocFactory() { final Values customIData = new Values(new Object[][] {{"key1", "Hello!"}}); GenericConversionService conversionService = new GenericConversionService(); Converter<String, MyClass> converter = new Converter<String, MyClass>() { public MyClass convert(String source) { return new MyClass(source); }; }; conversionService.addConverter(String.class, MyClass.class, converter ); DocumentFactoryBuilder docFactBuilder = new DocumentFactoryBuilder(); docFactBuilder.setConversionService(conversionService); docFactBuilder.setDirectIDataFactory(new DirectIDataFactory() { @Override public IData create() { return customIData; } }); DocumentFactory docFact = docFactBuilder.build(); Document document = docFact.create(); // Confirm custom IData is the one that has been created assertSame(document.getIData(), customIData); // Confirm the conversion service we created is used assertEquals("Hello!", document.entry("key1", MyClass.class).getVal().getText()); }
/** * 增加字符串转日期的功能 */ @PostConstruct public void initEditableValidation() { ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer(); if (initializer.getConversionService() != null) { GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService(); genericConversionService.addConverter(new StringToDateConverter()); genericConversionService.addConverter(new StringToSQLDateConverter()); } }
@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()); }
@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"); } }
@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); }
@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()); }
@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; }
@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")); }
/** * 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 StringToEnumIgnoringCaseConverterFactory()); this.additionalConverters.addConverter(new StringToCharArrayConverter()); }
/** * Sets up the bean post processor and conversion service * * @param beans - The bean factory for the the dictionary beans */ public static void setupProcessor(DefaultListableBeanFactory beans) { try { // UIF post processor that sets component ids BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance(); beans.addBeanPostProcessor(idPostProcessor); beans.setBeanExpressionResolver(new StandardBeanExpressionResolver() { @Override protected void customizeEvaluationContext(StandardEvaluationContext evalContext) { try { evalContext.registerFunction("getService", ExpressionFunctions.class.getDeclaredMethod("getService", String.class)); } catch(NoSuchMethodException me) { LOG.error("Unable to register custom expression to data dictionary bean factory", me); } } }); // special converters for shorthand map and list property syntax GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(new StringMapConverter()); conversionService.addConverter(new StringListConverter()); beans.setConversionService(conversionService); } catch (Exception e1) { throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(), e1); } }
private GenericConversionService getConversionService(GenericConverter... converters) { GenericConversionService service = new GenericConversionService(); for (GenericConverter converter : converters) { service.addConverter(converter); } DefaultConversionService.addDefaultConverters(service); return service; }
/** * Create a new {@link RelaxedConversionService} instance. * @param conversionService and option root conversion service */ RelaxedConversionService(ConversionService conversionService) { this.conversionService = conversionService; this.additionalConverters = new GenericConversionService(); this.additionalConverters .addConverterFactory(new StringToEnumIgnoringCaseConverterFactory()); this.additionalConverters.addConverter(new StringToCharArrayConverter()); }
@Override protected GenericConversionService createConversionService() { DefaultConversionService conversionService = new DefaultConversionService(); //removing appropriate converters removeConvertible.entrySet().stream().forEach(entry->conversionService.removeConvertible(entry.getKey(), entry.getValue())); return conversionService; }
protected AbstractCrateConverter(GenericConversionService conversionService) { super(); this.conversionService = conversionService == null ? new DefaultConversionService() : conversionService; this.instantiators = new EntityInstantiators(); this.conversions = new CustomConversions(); }
private GenericConversionService createConversionServiceWithBeanClassLoader() { GenericConversionService conversionService = new GenericConversionService(); conversionService.addConverter(Object.class, byte[].class, new SerializingConverter()); conversionService.addConverter(byte[].class, Object.class, new DeserializingConverter(this.classLoader)); return conversionService; }
private static GenericConversionService createDefaultConversionService() { GenericConversionService converter = new GenericConversionService(); converter.addConverter(Object.class, byte[].class, new SerializingConverter()); converter.addConverter(byte[].class, Object.class, new DeserializingConverter()); return converter; }
@Test public void testNullNestedTypeDescriptorWithBadConversionService() { Foo foo = new Foo(); BeanWrapperImpl wrapper = new BeanWrapperImpl(foo); wrapper.setConversionService(new GenericConversionService() { @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { throw new ConversionFailedException(sourceType, targetType, source, null); } }); wrapper.setAutoGrowNestedPaths(true); wrapper.setPropertyValue("listOfMaps[0]['luckyNumber']", "9"); assertEquals("9", foo.listOfMaps.get(0).get("luckyNumber")); }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { GenericConversionService gcs = (GenericConversionService) conversionService; for (Converter<?, ?> converter : converters) { gcs.addConverter(converter); } }