List of usage examples for org.springframework.core.convert ConversionService canConvert
boolean canConvert(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType);
From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java
/** * Converts an object into the appropriate type defined by the model field being queried. * * @param param/*from w ww .j a v a 2 s. c o m*/ * @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; } }
From source file:com._4dconcept.springframework.data.marklogic.core.convert.MappingMarklogicConverter.java
@Override public <R> R read(Class<R> returnType, MarklogicContentHolder holder) { ResultItem resultItem = (ResultItem) holder.getContent(); if (String.class.equals(returnType)) { return returnType.cast(resultItem.asString()); }// w w w . j av a2 s.com R result = null; if (returnType.isPrimitive()) { try { Method method = MarklogicTypeUtils.primitiveMap.get(returnType).getMethod("valueOf", String.class); @SuppressWarnings("unchecked") R obj = (R) method.invoke(null, resultItem.asString()); result = obj; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { LOGGER.debug("Unable to generate primitive value for type " + returnType.getName()); } } if (result != null) { return result; } ConversionService conversionService = getConversionService(); if (conversionService.canConvert(resultItem.getClass(), returnType)) { R convert = conversionService.convert(resultItem, returnType); if (convert == null) { throw new ConversionFailedException(TypeDescriptor.forObject(resultItem), TypeDescriptor.valueOf(returnType), resultItem, new NullPointerException()); } return convert; } else { throw new ConverterNotFoundException(TypeDescriptor.forObject(resultItem), TypeDescriptor.valueOf(returnType)); } }
From source file:org.springframework.data.web.config.EnableSpringDataWebSupportIntegrationTests.java
@Test // DATACMNS-626 public void registersFormatters() { ApplicationContext context = WebTestUtils.createApplicationContext(SampleConfig.class); ConversionService conversionService = context.getBean(ConversionService.class); assertThat(conversionService.canConvert(String.class, Distance.class)).isTrue(); assertThat(conversionService.canConvert(Distance.class, String.class)).isTrue(); assertThat(conversionService.canConvert(String.class, Point.class)).isTrue(); assertThat(conversionService.canConvert(Point.class, String.class)).isTrue(); }
From source file:org.focusns.common.web.widget.mvc.method.WidgetMethodArgumentResolver.java
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { ///*w ww . j av a2 s . c o m*/ Object value = null; if (parameter.hasParameterAnnotation(WidgetAttribute.class)) { value = getWidgetAttributeValue(parameter, webRequest); } else if (parameter.hasParameterAnnotation(WidgetPref.class)) { value = getWidgetPrefValue(parameter, webRequest); } // if (value != null) { ConversionService conversionService = (ConversionService) webRequest .getAttribute(ConversionService.class.getName(), WebRequest.SCOPE_REQUEST); if (conversionService.canConvert(value.getClass(), parameter.getParameterType())) { value = conversionService.convert(value, parameter.getParameterType()); } else { throw new ConverterNotFoundException(TypeDescriptor.forObject(value), TypeDescriptor.valueOf(parameter.getParameterType())); } } // return value; }
From source file:org.springframework.data.rest.webmvc.config.RepositoryRestMvConfigurationIntegrationTests.java
/** * @see DATAREST-431, DATACMNS-626//from w w w . j a va 2s . co m */ @Test public void hasConvertersForPointAndDistance() { ConversionService service = context.getBean("defaultConversionService", ConversionService.class); assertThat(service.canConvert(String.class, Point.class), is(true)); assertThat(service.canConvert(Point.class, String.class), is(true)); assertThat(service.canConvert(String.class, Distance.class), is(true)); assertThat(service.canConvert(Distance.class, String.class), is(true)); }
From source file:org.grails.datastore.gorm.neo4j.Neo4jMappingContext.java
/** * Obtain the native type to use for the given value * * @param value The value//from w w w . j av a 2s. c om * @return The value converted to a native Neo4j type */ public Object convertToNative(Object value) { if (value != null) { final Class<?> type = value.getClass(); if (type.equals(byte[].class)) { // workaround for https://github.com/neo4j/neo4j-java-driver/issues/182, remove when fixed byte[] bytes = (byte[]) value; int[] intArray = new int[bytes.length]; for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; intArray[i] = b; } return intArray; } else if (BASIC_TYPES.contains(type)) { return value; } else if (value instanceof CharSequence) { return value.toString(); } else if (value instanceof Collection) { return value; } else if (value instanceof BigDecimal) { return ((BigDecimal) value).doubleValue(); } else { final ConversionService conversionService = getConversionService(); if (byte[].class.isInstance(value)) { return conversionService.convert(value, String.class); } else { if (conversionService.canConvert(type, LONG_TYPE)) { return conversionService.convert(value, LONG_TYPE); } else if (conversionService.canConvert(type, DOUBLE_TYPE)) { return conversionService.convert(value, DOUBLE_TYPE); } else if (conversionService.canConvert(type, STRING_TYPE)) { return conversionService.convert(value, STRING_TYPE); } else { return value.toString(); } } } } else { return value; } }
From source file:org.gvnix.datatables.tags.RooTableTag.java
/** * Gets Id content//w w w. j av a 2 s. c o m * * @return * @throws JspException */ protected String getIdContent() throws JspException { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(this.rowIdBase); EvaluationContext context = new StandardEvaluationContext(currentObject); Object value = exp.getValue(context); String result = ""; if (value == null) { // Use AbstractTablaTag standard behavior try { value = PropertyUtils.getNestedProperty(this.currentObject, this.rowIdBase); } catch (IllegalAccessException e) { LOGGER.error("Unable to get the value for the given rowIdBase {}", this.rowIdBase); throw new JspException(e); } catch (InvocationTargetException e) { LOGGER.error("Unable to get the value for the given rowIdBase {}", this.rowIdBase); throw new JspException(e); } catch (NoSuchMethodException e) { LOGGER.error("Unable to get the value for the given rowIdBase {}", this.rowIdBase); throw new JspException(e); } } if (value != null) { // TODO manage exceptions to log it ConversionService conversionService = (ConversionService) helper.getBean(this.pageContext, getConversionServiceId()); if (conversionService != null && conversionService.canConvert(value.getClass(), String.class)) { result = conversionService.convert(value, String.class); } else { result = ObjectUtils.getDisplayString(value); } result = HtmlUtils.htmlEscape(result); } return result; }
From source file:org.gvnix.datatables.tags.RooColumnTag.java
@Override protected String getColumnContent() throws JspException { // Try to do the same as the roo table.tagx tag to get the value for the // column/*from ww w . jav a 2s . co m*/ // <c:choose> // <c:when test="${columnType eq 'date'}"> // <spring:escapeBody> // <fmt:formatDate value="${item[column]}" // pattern="${fn:escapeXml(columnDatePattern)}" var="colTxt" /> // </spring:escapeBody> // </c:when> // <c:when test="${columnType eq 'calendar'}"> // <spring:escapeBody> // <fmt:formatDate value="${item[column].time}" // pattern="${fn:escapeXml(columnDatePattern)}" var="colTxt"/> // </spring:escapeBody> // </c:when> // <c:otherwise> // <c:set var="colTxt"> // <spring:eval expression="item[column]" htmlEscape="false" /> // </c:set> // </c:otherwise> // </c:choose> // <c:if test="${columnMaxLength ge 0}"> // <c:set value="${fn:substring(colTxt, 0, columnMaxLength)}" // var="colTxt" /> // </c:if> // <c:out value="${colTxt}" /> // TODO log problem resolving column content if (StringUtils.isBlank(this.property)) { return ""; } TableTag parent = (TableTag) getParent(); ExpressionParser parser = new SpelExpressionParser(); String unescapedProperty = this.property.replace(SEPARATOR_FIELDS_ESCAPED, SEPARATOR_FIELDS); Expression exp = parser.parseExpression(unescapedProperty); EvaluationContext context = new StandardEvaluationContext(parent.getCurrentObject()); Object value = exp.getValue(context); String result = ""; if (value != null) { if (Date.class.isAssignableFrom(value.getClass())) { result = dateTimePattern.format(value); } else if (value instanceof Calendar) { result = dateTimePattern.format(((Calendar) value).getTime()); } else { ConversionService conversionService = (ConversionService) helper.getBean(this.pageContext, getConversionServiceId()); if (conversionService != null && conversionService.canConvert(value.getClass(), String.class)) { result = conversionService.convert(value, String.class); } else { result = ObjectUtils.getDisplayString(value); } // result = (isHtmlEscape() ? HtmlUtils.htmlEscape(result) : // result); // result = (this.javaScriptEscape ? // JavaScriptUtils.javaScriptEscape(result) : result); } } else { result = super.getColumnContent(); } if (maxLength >= 0 && result.length() > maxLength) { result = result.substring(0, maxLength); } return result; }
From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java
/** * Create a model attribute from a String request value (e.g. URI template variable, request parameter) using type * conversion.//from www . j a v a2 s . com * <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; }
From source file:com._4dconcept.springframework.data.marklogic.core.MarklogicTemplate.java
private MarklogicIdentifier resolveMarklogicIdentifier(Object id, MarklogicPersistentProperty idProperty) { if (MarklogicTypeUtils.isSimpleType(idProperty.getType())) { return new MarklogicIdentifier() { @Override//ww w.j a v a 2s . c o m public QName qname() { return idProperty.getQName(); } @Override public String value() { return id.toString(); } }; } ConversionService conversionService = marklogicConverter.getConversionService(); if (conversionService.canConvert(idProperty.getType(), MarklogicIdentifier.class)) { MarklogicIdentifier convert = conversionService.convert(id, MarklogicIdentifier.class); if (convert == null) { throw new ConversionFailedException(TypeDescriptor.forObject(id), TypeDescriptor.valueOf(MarklogicIdentifier.class), id, new NullPointerException("Conversion result is not expected to be null")); } return convert; } throw new MappingException("Unexpected identifier type " + idProperty.getClass()); }