@Test public void testDefaultFormattersOff() throws Exception { FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean(); factory.setRegisterDefaultFormatters(false); factory.afterPropertiesSet(); FormattingConversionService fcs = factory.getObject(); TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern")); try { fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor); fail("This format should not be parseable"); } catch (ConversionFailedException ex) { assertTrue(ex.getCause() instanceof NumberFormatException); } }
@Test public void scalarMap() throws Exception { Map<String, String> map = new HashMap<String, String>(); map.put("1", "9"); map.put("2", "37"); TypeDescriptor sourceType = TypeDescriptor.forObject(map); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget")); assertTrue(conversionService.canConvert(sourceType, targetType)); try { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException e) { assertTrue(e.getCause() instanceof ConverterNotFoundException); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); assertTrue(conversionService.canConvert(sourceType, targetType)); @SuppressWarnings("unchecked") Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType); assertFalse(map.equals(result)); assertEquals((Integer) 9, result.get(1)); assertEquals((Integer) 37, result.get(2)); }
@Test public void scalarMapNotGenericSourceField() throws Exception { Map<String, String> map = new HashMap<String, String>(); map.put("1", "9"); map.put("2", "37"); TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("notGenericMapSource")); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget")); assertTrue(conversionService.canConvert(sourceType, targetType)); try { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException e) { assertTrue(e.getCause() instanceof ConverterNotFoundException); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); assertTrue(conversionService.canConvert(sourceType, targetType)); @SuppressWarnings("unchecked") Map<Integer, Integer> result = (Map<Integer, Integer>) conversionService.convert(map, sourceType, targetType); assertFalse(map.equals(result)); assertEquals((Integer) 9, result.get(1)); assertEquals((Integer) 37, result.get(2)); }
@Test public void collectionMap() throws Exception { Map<String, List<String>> map = new HashMap<String, List<String>>(); map.put("1", Arrays.asList("9", "12")); map.put("2", Arrays.asList("37", "23")); TypeDescriptor sourceType = TypeDescriptor.forObject(map); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget")); assertTrue(conversionService.canConvert(sourceType, targetType)); try { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException e) { assertTrue(e.getCause() instanceof ConverterNotFoundException); } conversionService.addConverter(new CollectionToCollectionConverter(conversionService)); conversionService.addConverterFactory(new StringToNumberConverterFactory()); assertTrue(conversionService.canConvert(sourceType, targetType)); @SuppressWarnings("unchecked") Map<Integer, List<Integer>> result = (Map<Integer, List<Integer>>) conversionService.convert(map, sourceType, targetType); assertFalse(map.equals(result)); assertEquals(Arrays.asList(9, 12), result.get(1)); assertEquals(Arrays.asList(37, 23), result.get(2)); }
@Nullable @Override public Object convert(Object src, TypeDescriptor srcType, TypeDescriptor targetType) { if (!this.matches(srcType, targetType)) { return null; } boolean srcArr = srcType.isArray(), resolveAll = (srcArr || targetType.isArray()); String strSrc = (!srcArr ? ((String) src) : null); String[] strSrcs = (srcArr ? SdcctStringUtils.splitTokens(((String[]) src)) : SdcctStringUtils.splitTokens(strSrc)); if (!resolveAll && (strSrcs.length > 1)) { resolveAll = true; } try { return (resolveAll ? this.resourceSrcResolver.resolveAll(strSrcs) : this.resourceSrcResolver.resolve(strSrc)); } catch (IOException e) { throw new ConversionFailedException(srcType, targetType, src, e); } }
@Test public void scalarList() throws Exception { List<String> list = new ArrayList<String>(); list.add("9"); list.add("37"); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarListTarget")); assertTrue(conversionService.canConvert(sourceType, targetType)); try { conversionService.convert(list, sourceType, targetType); } catch (ConversionFailedException ex) { assertTrue(ex.getCause() instanceof ConverterNotFoundException); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); assertTrue(conversionService.canConvert(sourceType, targetType)); @SuppressWarnings("unchecked") List<String> result = (List<String>) conversionService.convert(list, sourceType, targetType); assertFalse(list.equals(result)); assertEquals(9, result.get(0)); assertEquals(37, result.get(1)); }
/** * TypeMismatchException中获取到参数错误类型 * * @param e */ private ModelAndView getParamErrors(TypeMismatchException e) { Throwable t = e.getCause(); if (t instanceof ConversionFailedException) { ConversionFailedException x = (ConversionFailedException) t; TypeDescriptor type = x.getTargetType(); Annotation[] annotations = type != null ? type.getAnnotations() : new Annotation[0]; Map<String, String> errors = new HashMap<String, String>(); for (Annotation a : annotations) { if (a instanceof RequestParam) { errors.put(((RequestParam) a).value(), "parameter type error!"); } } if (errors.size() > 0) { return paramError(errors, ErrorCode.TYPE_MIS_MATCH); } } JsonObjectBase jsonObject = JsonObjectUtils.buildGlobalError("parameter type error!", ErrorCode.TYPE_MIS_MATCH); return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject); }
@Override public PrometheusAlert convert(PrometheusAlertRequest source) { PrometheusAlert alert = new PrometheusAlert(); alert.setName(source.getAlertName()); alert.setDescription(source.getDescription()); alert.setPeriod(source.getPeriod()); alert.setAlertState(source.getAlertState() != null ? source.getAlertState() : CRITICAL); double threshold = source.getThreshold(); String alertRuleName = source.getAlertRuleName(); try { AlertOperator alertOperator = source.getAlertOperator() != null ? source.getAlertOperator() : AlertOperator.MORE_THAN; String operator = alertOperator.getOperator(); String alertRule = templateService.createAlert(alertRuleName, alert.getName(), String.valueOf(threshold), alert.getPeriod(), operator); alert.setAlertRule(alertRule); alert.setParameters(createParametersFrom(threshold, alertOperator)); } catch (Exception e) { throw new ConversionFailedException( TypeDescriptor.valueOf(PrometheusAlertRequest.class), TypeDescriptor.valueOf(PrometheusAlert.class), source.toString(), e); } return alert; }
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; }
@Override public <V> V get(String k, Class<V> vClass) { if (conversionService.canConvert(String.class, vClass)) { Object val = environment.getProperty("management.metrics.filter." + k); try { return conversionService.convert(val, vClass); } catch (ConversionFailedException e) { throw new ConfigurationException("Invalid configuration for '" + k + "' value '" + val + "' as " + vClass, e); } } return null; }
@Test(expected = ConversionFailedException.class) public void testToBigDecimalException() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("BigDecimalParam", BigDecimal.class); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.invocableHandlerMethod.convert(param, "str")).isEqualTo("str"); }
@Test public void receiveAndConvertFailed() { Message<?> expected = new GenericMessage<Object>("not a number test"); this.template.setReceiveMessage(expected); this.template.setMessageConverter(new GenericMessageConverter()); thrown.expect(MessageConversionException.class); thrown.expectCause(isA(ConversionFailedException.class)); this.template.receiveAndConvert("somewhere", Integer.class); }
@Test(expected = ConversionFailedException.class) public void nothingInCommon() throws Exception { List<Object> resources = new ArrayList<Object>(); resources.add(new ClassPathResource("test")); resources.add(3); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); }
@Test public void convertFromStreamToArrayNoConverter() throws NoSuchFieldException { Stream<Integer> stream = Arrays.asList(1, 2, 3).stream(); TypeDescriptor arrayOfLongs = new TypeDescriptor(Types.class.getField("arrayOfLongs")); ; thrown.expect(ConversionFailedException.class); thrown.expectCause(is(instanceOf(ConverterNotFoundException.class))); this.conversionService.convert(stream, arrayOfLongs); }
@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")); }
@Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (this.conversionService != null) { try { return this.conversionService.convert(source, sourceType, targetType); } catch (ConversionFailedException ex) { // Ignore and try the additional converters } } return this.additionalConverters.convert(source, sourceType, targetType); }
private <T> T get(String propertyName, Class<T> type, Properties props) throws IllegalArgumentException { Validate.notEmpty(propertyName); Validate.notNull(type); String value = props.getProperty(propertyName); if(value == null) { throw new IllegalArgumentException(); } try { return converter.convert(value, type); } catch (IllegalArgumentException | ConversionFailedException | ConverterNotFoundException ex) { LOGGER.warn("Invalid type for property: {}, value: {}, reason: {}", propertyName, value, ex.getMessage()); throw new IllegalArgumentException(); } }
@Override public SortedSet<?> convertToEntityAttribute(byte[] dbData) { try { return mapper.readValue(dbData, new TypeReference<TreeSet<FieldGroupConfig>>() {}); } catch (IOException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(dbData), TypeDescriptor.valueOf(TreeSet.class), "Could not convert value to json", ex); } }
@Override public SortedSet<?> convertToEntityAttribute(byte[] dbData) { try { return mapper.readValue(dbData, new TypeReference<TreeSet<FieldConfig>>() {}); } catch (IOException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(dbData), TypeDescriptor.valueOf(TreeSet.class), "Could not convert value to json", ex); } }
@Override public byte[] convertToDatabaseColumn(SortedSet<?> attribute) { try { return mapper.writeValueAsBytes(attribute); } catch (JsonProcessingException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(attribute), TypeDescriptor.valueOf(byte[].class), "Could not convert value to json", ex); } }
@Override public SortedSet<?> convertToEntityAttribute(byte[] dbData) { try { return mapper.readValue(dbData, TreeSet.class); } catch (IOException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(dbData), TypeDescriptor.valueOf(TreeSet.class), "Could not convert value to json", ex); } }
/** * Converts a hashmap to a smile json byte array * * @param attribute the hashmap to be converted * @return a byte array json representation of the hashmap */ @Override public byte[] convertToDatabaseColumn(Map<?, ?> attribute) { SmileFactory factory = new SmileFactory(); ObjectMapper mapper = new ObjectMapper(factory); try { return mapper.writeValueAsBytes(attribute); } catch (JsonProcessingException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(attribute), TypeDescriptor.valueOf(byte[].class), "Could not convert value to json", ex); } }
/** * Converts a byte array back into a hashmap * * @param dbData the json byte array * @return a HashMap */ @Override public Map<?, ?> convertToEntityAttribute(byte[] dbData) { SmileFactory factory = new SmileFactory(); ObjectMapper mapper = new ObjectMapper(factory); try { return mapper.readValue(dbData, HashMap.class); } catch (IOException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(dbData), TypeDescriptor.valueOf(HashMap.class), "Could not convert value to json", ex); } }
@Override public byte[] convertToDatabaseColumn(Set<?> attribute) { try { return mapper.writeValueAsBytes(attribute); } catch (JsonProcessingException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(attribute), TypeDescriptor.valueOf(byte[].class), "Could not convert value to json", ex); } }
@Override public Set<?> convertToEntityAttribute(byte[] dbData) { try { return mapper.readValue(dbData, LinkedHashSet.class); } catch (IOException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(dbData), TypeDescriptor.valueOf(Set.class), "Could not convert value to json", ex); } }
@Override public byte[] convertToDatabaseColumn(Set<SimpleGrantedAuthority> attribute) { try { return mapper.writeValueAsBytes(attribute.stream().map(a -> a.getAuthority()).collect(Collectors.toSet())); } catch (JsonProcessingException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(attribute), TypeDescriptor.valueOf(LinkedHashSet.class), "Could not convert value to json", ex); } }
@Override public Set<SimpleGrantedAuthority> convertToEntityAttribute(byte[] dbData) { try { Set<String> authorities = mapper.readValue(dbData, new TypeReference<LinkedHashSet<String>>() {}); return authorities.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toSet()); } catch (IOException ex) { throw new ConversionFailedException(TypeDescriptor.forObject(dbData), TypeDescriptor.valueOf(TreeSet.class), "Could not convert value from json", ex); } }
/** * @param text Set the value * @return a file */ public final File convert(final String text) { editor.setAsText(text); try { return ((Resource) editor.getValue()).getFile(); } catch (IOException e) { throw new ConversionFailedException( TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(File.class), text, e); } }
/** * Converts an object into the appropriate type defined by the model field being queried. * * @param param * @param type * @return */ public static Object convertParameter(Object param, Class<?> type, ConversionService conversionService){ logger.debug(String.format("Attempting to convert parameter: from=%s to=%s", param.getClass().getName(), type.getName())); if (conversionService.canConvert(param.getClass(), type)){ try { return conversionService.convert(param, type); } catch (ConversionFailedException e){ e.printStackTrace(); throw new InvalidParameterException("Unable to convert String to " + type.getName()); } } else { return param; } }
@Nullable @Override public Object convert(Object src, TypeDescriptor srcType, TypeDescriptor targetType) { if (!this.matches(srcType, targetType)) { return null; } try { return this.resourceSrcResolver.resolve(((String) src)); } catch (IOException e) { throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(ResourceSource.class), src, e); } }
@Test(expected = ConversionFailedException.class) public void testToBigDecimalException() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("BigDecimalParam", BigDecimal.class); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.converter.convert(param, "str")).isEqualTo("str"); }
@Test public void testDefaultFormattersOff() throws Exception { FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean(); factory.setRegisterDefaultFormatters(false); factory.afterPropertiesSet(); FormattingConversionService fcs = factory.getObject(); TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("percent")); try { fcs.convert("5%", TypeDescriptor.valueOf(String.class), descriptor); fail("This format should not be parseable"); } catch (ConversionFailedException ex) { assertTrue(ex.getCause() instanceof NumberFormatException); } }
@Test(expected=ConversionFailedException.class) public void nothingInCommon() throws Exception { List<Object> resources = new ArrayList<Object>(); resources.add(new ClassPathResource("test")); resources.add(3); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); assertEquals(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); }