@ConfigurationPropertiesBinding @Bean public Converter<String, List<Class<? extends Throwable>>> commaSeparatedStringToThrowablesCollection() { return new Converter<String, List<Class<? extends Throwable>>>() { @Override public List<Class<? extends Throwable>> convert(final String source) { try { final List<Class<? extends Throwable>> classes = new ArrayList<>(); for (final String className : StringUtils.commaDelimitedListToStringArray(source)) { classes.add((Class<? extends Throwable>) ClassUtils.forName(className.trim(), getClass().getClassLoader())); } return classes; } catch (final Exception e) { throw new IllegalStateException(e); } } }; }
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); } })); }
public DocumentConversionService(final DocumentFactory docFactory) { super(); internalService.addConverter(IData.class, Document.class, new Converter<IData, Document>() { @Override public Document convert(IData idata) { return docFactory.wrap((IData) idata); } }); internalService.addConverter(Document.class, IData.class, new Converter<Document, IData>() { @Override public IData convert(Document document) { return ((Document) document).getIData(); } }); }
@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"); }
/** * Register the given Converter objects with the given target ConverterRegistry. * @param converters the converter objects: implementing {@link Converter}, * {@link ConverterFactory}, or {@link GenericConverter} * @param registry the target registry */ public static void registerConverters(Set<?> converters, ConverterRegistry registry) { if (converters != null) { for (Object converter : converters) { if (converter instanceof GenericConverter) { registry.addConverter((GenericConverter) converter); } else if (converter instanceof Converter<?, ?>) { registry.addConverter((Converter<?, ?>) converter); } else if (converter instanceof ConverterFactory<?, ?>) { registry.addConverterFactory((ConverterFactory<?, ?>) converter); } else { throw new IllegalArgumentException("Each converter object must implement one of the " + "Converter, ConverterFactory, or GenericConverter interfaces"); } } } }
@Test @SuppressWarnings("resource") public void convertFromArrayToStream() throws NoSuchFieldException { Integer[] stream = new Integer[] {1, 0, 1}; this.conversionService.addConverter(new Converter<Integer, Boolean>() { @Override public Boolean convert(Integer source) { return source == 1; } }); TypeDescriptor streamOfBoolean = new TypeDescriptor(Types.class.getField("streamOfBooleans")); ; Object result = this.conversionService.convert(stream, streamOfBoolean); assertNotNull("converted object must not be null", result); assertTrue("Converted object must be a stream", result instanceof Stream); @SuppressWarnings("unchecked") Stream<Boolean> content = (Stream<Boolean>) result; assertEquals(2, content.filter(x -> x).count()); }
@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); }
@Override public Cursor<V> scan(K key, final ScanOptions options) { final byte[] rawKey = rawKey(key); return execute(new RedisCallback<Cursor<V>>() { @Override public Cursor<V> doInRedis(RedisConnection connection) throws DataAccessException { return new ConvertingCursor<byte[], V>(connection.sScan(rawKey, options), new Converter<byte[], V>() { @Override public V convert(byte[] source) { return deserializeValue(source); } }); } }, true); }
@Override public Cursor<TypedTuple<V>> scan(K key, final ScanOptions options) { final byte[] rawKey = rawKey(key); Cursor<Tuple> cursor = execute(new RedisCallback<Cursor<Tuple>>() { @Override public Cursor<Tuple> doInRedis(RedisConnection connection) throws DataAccessException { connection.select(dbIndex); return connection.zScan(rawKey, options); } }, true); return new ConvertingCursor<Tuple, TypedTuple<V>>(cursor, new Converter<Tuple, TypedTuple<V>>() { @Override public TypedTuple<V> convert(Tuple source) { return deserializeTuple(source); } }); }
private ConversionService conversionService(ApplicationContext applicationContext) { // TODO should be also able to resolve a url to a bean/method BeanFactoryResolver beanResolver = new BeanFactoryResolver(applicationContext) { @Override public Object resolve(EvaluationContext context, String beanName) throws AccessException { return super.resolve(context, (beanName.startsWith("bean:") ? beanName.substring("bean:".length()) : beanName)); } }; ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean(); Set<Converter<?, ?>> cons = new HashSet<Converter<?, ?>>(); cons.add(new DtoCheckConverter(beanResolver)); cons.add(new DtoOperationConverter(beanResolver)); factoryBean.setConverters(cons); factoryBean.afterPropertiesSet(); return factoryBean.getObject(); }
/** * 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!"); } } }
private void registerConversion(Object converter) { Class<?> type = converter.getClass(); boolean isWriting = type.isAnnotationPresent(WritingConverter.class); boolean isReading = type.isAnnotationPresent(ReadingConverter.class); if (!isReading && !isWriting) { isReading = true; isWriting = true; } if (converter instanceof GenericConverter) { GenericConverter genericConverter = (GenericConverter) converter; for (ConvertiblePair pair : genericConverter.getConvertibleTypes()) { register(new ConvertibleContext(pair, isReading, isWriting)); } } else if (converter instanceof Converter) { Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class); register(new ConvertibleContext(arguments[0], arguments[1], isReading, isWriting)); } else { throw new IllegalArgumentException("Unsupported Converter type! Expected either GenericConverter if Converter."); } }
/** * Returns the converters to be registered. Will only return converters in case we're running on Java 8. * * @return */ public static Collection<Converter<?, ?>> getConvertersToRegister() { if (!JAVA_8_IS_PRESENT) { return Collections.emptySet(); } List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>(); converters.add(DateToLocalDateTimeConverter.INSTANCE); converters.add(LocalDateTimeToDateConverter.INSTANCE); converters.add(DateToLocalDateConverter.INSTANCE); converters.add(LocalDateToDateConverter.INSTANCE); converters.add(DateToLocalTimeConverter.INSTANCE); converters.add(LocalTimeToDateConverter.INSTANCE); converters.add(DateToInstantConverter.INSTANCE); converters.add(InstantToDateConverter.INSTANCE); return converters; }
/** * 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!"); } } }
/** * Registers a conversion for the given converter. Inspects either generics or the convertible pairs returned * by a {@link GenericConverter}. * * @param converter the converter to register. */ private void registerConversion(final Object converter) { Class<?> type = converter.getClass(); boolean isWriting = type.isAnnotationPresent(WritingConverter.class); boolean isReading = type.isAnnotationPresent(ReadingConverter.class); if (converter instanceof GenericConverter) { GenericConverter genericConverter = (GenericConverter) converter; for (GenericConverter.ConvertiblePair pair : genericConverter.getConvertibleTypes()) { register(new ConverterRegistration(pair, isReading, isWriting)); } } else if (converter instanceof Converter) { Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class); register(new ConverterRegistration(arguments[0], arguments[1], isReading, isWriting)); } else { throw new IllegalArgumentException("Unsupported Converter type!"); } }
@Bean public Converter<String, ErrorCode> errorCodeConverter() { // Don't convert to lambda -> cause issue for Spring to infer source and target types. return new Converter<String, ErrorCode>() { @Override public ErrorCode convert(String source) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.readerFor(JsonErrorCode.class).readValue(source); } catch (Exception e) { LOGGER.trace("Unable to read error code from '{}'", source, e); // Build a JSON error code out of "source" (mostly likely a error code as string). final ErrorCodeDto errorCodeDto = new ErrorCodeDto(); errorCodeDto.setCode(source); errorCodeDto.setHttpStatus(CommonErrorCodes.UNEXPECTED_EXCEPTION.getHttpStatus()); errorCodeDto.setGroup(CommonErrorCodes.UNEXPECTED_EXCEPTION.getGroup()); errorCodeDto.setProduct(CommonErrorCodes.UNEXPECTED_EXCEPTION.getProduct()); return errorCodeDto; } } }; }
/** * Converter for the format yyyy-MM-dd HH:mm:ss * * Currently needed for the approval revoke form that needs to bind the expiresAt and lastUpdatedAt * dates of an approval. */ @Bean public Converter<String, Date> stringDateConverter() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // We can not use a lambda here since Spring can't detect the generic types that way. return new Converter<String, Date>() { @Override public Date convert(String source) { if (source == null) { throw new IllegalArgumentException("Date string may not be null"); } try { return sdf.parse(source); } catch (ParseException e) { throw new IllegalArgumentException(e); } } }; }
/** * 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!"); } } }
@Bean public CustomConversions customConversions() { List<Converter<?, ?>> converterList = new ArrayList<>(); converterList.add(DateToZonedDateTimeConverter.INSTANCE); converterList.add(ZonedDateTimeToDateConverter.INSTANCE); return new CustomConversions(converterList); }
@Bean public CustomConversions customConversions() { List<Converter<?, ?>> converters = new ArrayList<>(); converters.add(DateToZonedDateTimeConverter.INSTANCE); converters.add(ZonedDateTimeToDateConverter.INSTANCE); return new CustomConversions(converters); }
/** * Initialize default ConversionService * * @return */ private ConfigurableConversionService getDefaultConversionService() { if (this.defaultConversionService == null) { DefaultConversionService conversionService = new DefaultConversionService(); this.applicationContext.getAutowireCapableBeanFactory().autowireBean(this); for (Converter<?, ?> converter : this.converters) { conversionService.addConverter(converter); } for (GenericConverter genericConverter : this.genericConverters) { conversionService.addConverter(genericConverter); } this.defaultConversionService = conversionService; } return this.defaultConversionService; }
@Override @Bean public CustomConversions customConversions() { List<Converter<?, ?>> converterList = new ArrayList<>(); AuthenticationReadConverter authenticationReadConverter = new AuthenticationReadConverter(); converterList.add(authenticationReadConverter); return new CustomConversions(converterList); }
@Override public CustomConversions customConversions() { List<Converter<?, ?>> converters = new ArrayList<>(); converters.add(new PersonWriteConverter()); converters.add(new PersonReadConverter()); converters.add(new CustomAddressbookReadConverter()); return new CustomConversions(converters); }
@Bean(name="conversionService") public ConversionServiceFactoryBean getConversionService() { ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); Set<Converter> converters = new HashSet<>(); converters.add(new DurationConverter()); converters.add(new AddressConverter()); bean.setConverters(converters); return bean; }
public JdkTarantoolSerializer(Converter<Object, byte[]> serializer, Converter<byte[], Object> deserializer) { Assert.notNull("Serializer must not be null"); Assert.notNull("Deserializer must not be null"); this.serializer = serializer; this.deserializer = deserializer; }
public PlainTarantoolSerializer(Class<T> desiredClass, ConfigurableConversionService conversionService) { this.desiredClass = desiredClass; this.conversionService = conversionService; conversionService.addConverter(Date.class, Number.class, (Converter<Date, Number>) Date::getTime); conversionService.addConverter(Number.class, Date.class, (Converter<Number, Date>) it -> new Date(it.longValue())); }
/** * 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!"); } } }
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T extends Enum<?>> Converter<String, T> getConverter(Class<T> targetType) { Class<?> enumType = targetType; while (enumType != null && !enumType.isEnum()) { enumType = enumType.getSuperclass(); } if (enumType == null) { throw new IllegalArgumentException("The target type " + targetType.getName() + " does not refer to an enum"); } return new StringToEnum(enumType); }
public JdkMongoSessionConverter(Converter<Object, byte[]> serializer, Converter<byte[], Object> deserializer, Duration maxInactiveInterval) { Assert.notNull(serializer, "serializer cannot be null"); Assert.notNull(deserializer, "deserializer cannot be null"); Assert.notNull(maxInactiveInterval, "maxInactiveInterval cannot be null"); this.serializer = serializer; this.deserializer = deserializer; this.maxInactiveInterval = maxInactiveInterval; }