io.micronaut.core.convert.ConversionService Java Examples
The following examples show how to use
io.micronaut.core.convert.ConversionService.
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: DefaultFindAllAsyncInterceptor.java From micronaut-data with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public CompletionStage<Iterable<Object>> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Iterable<Object>>> context) { CompletionStage<? extends Iterable<?>> future; if (context.hasAnnotation(Query.class)) { PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context); future = asyncDatastoreOperations.findAll(preparedQuery); } else { future = asyncDatastoreOperations.findAll(getPagedQuery(context)); } return future.thenApply((Function<Iterable<?>, Iterable<Object>>) iterable -> { Argument<CompletionStage<Iterable<Object>>> targetType = context.getReturnType().asArgument(); Argument<?> argument = targetType.getFirstTypeVariable().orElse(Argument.listOf(Object.class)); Iterable<Object> result = (Iterable<Object>) ConversionService.SHARED.convert( iterable, argument ).orElse(null); return result == null ? Collections.emptyList() : result; }); }
Example #2
Source File: AbstractQueryInterceptor.java From micronaut-data with Apache License 2.0 | 6 votes |
/** * Retrieve a parameter in the given role for the given type. * @param context The context * @param role The role * @param type The type * @param <RT> The generic type * @return An optional result */ private <RT> Optional<RT> getParameterInRole(MethodInvocationContext<?, ?> context, @NonNull String role, @NonNull Class<RT> type) { return context.stringValue(PREDATOR_ANN_NAME, role).flatMap(name -> { RT parameterValue = null; Map<String, MutableArgumentValue<?>> params = context.getParameters(); MutableArgumentValue<?> arg = params.get(name); if (arg != null) { Object o = arg.getValue(); if (o != null) { if (type.isInstance(o)) { //noinspection unchecked parameterValue = (RT) o; } else { parameterValue = ConversionService.SHARED .convert(o, type).orElse(null); } } } return Optional.ofNullable(parameterValue); }); }
Example #3
Source File: AbstractQueryInterceptor.java From micronaut-data with Apache License 2.0 | 6 votes |
/** * Convert a number argument if necessary. * @param number The number * @param argument The argument * @return The result */ protected @Nullable Number convertNumberArgumentIfNecessary(Number number, Argument<?> argument) { Argument<?> firstTypeVar = argument.getFirstTypeVariable().orElse(Argument.of(Long.class)); Class<?> type = firstTypeVar.getType(); if (type == Object.class || type == Void.class) { return null; } if (number == null) { number = 0; } if (!type.isInstance(number)) { return (Number) ConversionService.SHARED.convert(number, firstTypeVar) .orElseThrow(() -> new IllegalStateException("Unsupported number type for return type: " + firstTypeVar)); } else { return number; } }
Example #4
Source File: DefaultUpdateInterceptor.java From micronaut-data with Apache License 2.0 | 6 votes |
@Override public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Object> context) { PreparedQuery<?, Number> preparedQuery = (PreparedQuery<?, Number>) prepareQuery(methodKey, context); Number number = operations.executeUpdate(preparedQuery).orElse(null); final Argument<Object> returnType = context.getReturnType().asArgument(); final Class<Object> type = ReflectionUtils.getWrapperType(returnType.getType()); if (Number.class.isAssignableFrom(type)) { if (type.isInstance(number)) { return number; } else { return ConversionService.SHARED. convert(number, returnType) .orElse(0); } } else if (Boolean.class.isAssignableFrom(type)) { return number == null || number.longValue() < 0; } else { return null; } }
Example #5
Source File: DefaultCountInterceptor.java From micronaut-data with Apache License 2.0 | 6 votes |
@Override public Number intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Number> context) { long result; if (context.hasAnnotation(Query.class)) { PreparedQuery<?, Long> preparedQuery = prepareQuery(methodKey, context, Long.class); Iterable<Long> iterable = operations.findAll(preparedQuery); Iterator<Long> i = iterable.iterator(); result = i.hasNext() ? i.next() : 0; } else { result = operations.count(getPagedQuery(context)); } return ConversionService.SHARED.convert( result, context.getReturnType().asArgument() ).orElseThrow(() -> new IllegalStateException("Unsupported number type: " + context.getReturnType().getType())); }
Example #6
Source File: KafkaHeaderBinder.java From micronaut-kafka with Apache License 2.0 | 6 votes |
@Override public BindingResult<T> bind(ArgumentConversionContext<T> context, ConsumerRecord<?, ?> source) { Headers headers = source.headers(); AnnotationMetadata annotationMetadata = context.getAnnotationMetadata(); String name = annotationMetadata.getValue(Header.class, "name", String.class) .orElseGet(() -> annotationMetadata.getValue(Header.class, String.class) .orElse(context.getArgument().getName())); Iterable<org.apache.kafka.common.header.Header> value = headers.headers(name); if (value.iterator().hasNext()) { Optional<T> converted = ConversionService.SHARED.convert(value, context); return () -> converted; } else if (context.getArgument().getType() == Optional.class) { //noinspection unchecked return () -> (Optional<T>) Optional.of(Optional.empty()); } else { //noinspection unchecked return BindingResult.EMPTY; } }
Example #7
Source File: KafkaDefaultConfiguration.java From micronaut-kafka with Apache License 2.0 | 6 votes |
private static Properties resolveDefaultConfiguration(Environment environment) { Map<String, Object> values = environment.containsProperties(PREFIX) ? environment.getProperties(PREFIX, StringConvention.RAW) : Collections.emptyMap(); Properties properties = new Properties(); values.entrySet().stream().filter(entry -> { String key = entry.getKey(); return Stream.of("embedded", "consumers", "producers", "streams").noneMatch(key::startsWith); }).forEach(entry -> { Object value = entry.getValue(); if (ConversionService.SHARED.canConvert(entry.getValue().getClass(), String.class)) { Optional<?> converted = ConversionService.SHARED.convert(entry.getValue(), String.class); if (converted.isPresent()) { value = converted.get(); } } properties.setProperty(entry.getKey(), value.toString()); }); return properties; }
Example #8
Source File: DefaultFindOneInterceptor.java From micronaut-data with Apache License 2.0 | 6 votes |
@Override public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Object> context) { PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context, null); Object result = operations.findOne(preparedQuery); if (result != null) { ReturnType<Object> returnType = context.getReturnType(); if (!returnType.getType().isInstance(result)) { return ConversionService.SHARED.convert(result, returnType.asArgument()) .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + result)); } else { return result; } } else { if (!isNullable(context.getAnnotationMetadata())) { throw new EmptyResultException(); } } return result; }
Example #9
Source File: DefaultSaveAllInterceptor.java From micronaut-data with Apache License 2.0 | 6 votes |
@Override public Iterable<R> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, Iterable<R>> context) { Object[] parameterValues = context.getParameterValues(); if (ArrayUtils.isNotEmpty(parameterValues) && parameterValues[0] instanceof Iterable) { //noinspection unchecked Iterable<R> iterable = (Iterable<R>) parameterValues[0]; Iterable<R> rs = operations.persistAll(getBatchOperation(context, iterable)); ReturnType<Iterable<R>> rt = context.getReturnType(); if (!rt.getType().isInstance(rs)) { return ConversionService.SHARED.convert(rs, rt.asArgument()) .orElseThrow(() -> new IllegalStateException("Unsupported iterable return type: " + rs.getClass())); } return rs; } else { throw new IllegalArgumentException("First argument should be an iterable"); } }
Example #10
Source File: MicronautAwsProxyRequest.java From micronaut-aws with Apache License 2.0 | 6 votes |
@Override @Nonnull public Cookies getCookies() { if (cookies == null) { SimpleCookies simpleCookies = new SimpleCookies(ConversionService.SHARED); getHeaders().getAll(HttpHeaders.COOKIE).forEach(cookieValue -> { List<HeaderValue> parsedHeaders = parseHeaderValue(cookieValue, ";", ","); parsedHeaders.stream() .filter(e -> e.getKey() != null) .map(e -> new SimpleCookie(SecurityUtils.crlf(e.getKey()), SecurityUtils.crlf(e.getValue()))) .forEach(simpleCookie -> simpleCookies.put(simpleCookie.getName(), simpleCookie)); }); cookies = simpleCookies; } return cookies; }
Example #11
Source File: QueryStatement.java From micronaut-data with Apache License 2.0 | 5 votes |
/** * Convert the value to the given type. * @param value The value * @param type The type * @param <T> The generic type * @return The converted value * @throws DataAccessException if the value cannot be converted */ default @Nullable <T> T convertRequired(@Nullable Object value, Class<T> type) { if (value == null) { return null; } return ConversionService.SHARED.convert( value, type ).orElseThrow(() -> new DataAccessException("Cannot convert type [" + value.getClass() + "] to target type: " + type + ". Consider defining a TypeConverter bean to handle this case.") ); }
Example #12
Source File: DefaultFindOneAsyncInterceptor.java From micronaut-data with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public CompletionStage<Object> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Object>> context) { PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context); CompletionStage<Object> future = asyncDatastoreOperations.findOne(preparedQuery); Argument<?> type = context.getReturnType().asArgument().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT); return future.thenApply(o -> { if (!type.getType().isInstance(o)) { return ConversionService.SHARED.convert(o, type) .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o)); } return o; }); }
Example #13
Source File: SchedulerLockInterceptor.java From ShedLock with Apache License 2.0 | 5 votes |
public SchedulerLockInterceptor( LockProvider lockProvider, Optional<ConversionService<?>> conversionService, @Value("${shedlock.defaults.lock-at-most-for}") String defaultLockAtMostFor, @Value("${shedlock.defaults.lock-at-least-for:PT0S}") String defaultLockAtLeastFor ) { ConversionService<?> resolvedConversionService = conversionService.orElse(ConversionService.SHARED); lockingTaskExecutor = new DefaultLockingTaskExecutor(lockProvider); micronautLockConfigurationExtractor = new MicronautLockConfigurationExtractor( resolvedConversionService.convert(defaultLockAtMostFor, Duration.class).orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtMostFor' value")), resolvedConversionService.convert(defaultLockAtLeastFor, Duration.class).orElseThrow(() -> new IllegalArgumentException("Invalid 'defaultLockAtLeastFor' value")), resolvedConversionService); }
Example #14
Source File: DefaultDeleteAllInterceptor.java From micronaut-data with Apache License 2.0 | 5 votes |
private Number convertIfNecessary(Argument<Number> resultType, Number result) { if (!resultType.getType().isInstance(result)) { return ConversionService.SHARED.convert(result, resultType).orElse(0); } else { return result; } }
Example #15
Source File: ResultReader.java From micronaut-data with Apache License 2.0 | 5 votes |
/** * Convert the value to the given type. * @param value The value * @param type The type * @param <T> The generic type * @return The converted value * @throws DataAccessException if the value cannot be converted */ default <T> T convertRequired(Object value, Class<T> type) { return ConversionService.SHARED.convert( value, type ).orElseThrow(() -> new DataAccessException("Cannot convert type [" + value.getClass() + "] with value [" + value + "] to target type: " + type + ". Consider defining a TypeConverter bean to handle this case.") ); }
Example #16
Source File: DefaultFindOneReactiveInterceptor.java From micronaut-data with Apache License 2.0 | 5 votes |
@Override public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) { PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context); Publisher<Object> publisher = reactiveOperations.findOptional(preparedQuery); Argument<Object> returnType = context.getReturnType().asArgument(); Argument<?> type = returnType.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT); Publisher<Object> mappedPublisher = Publishers.map(publisher, o -> { if (!type.getType().isInstance(o)) { return ConversionService.SHARED.convert(o, type) .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o)); } return o; }); return Publishers.convertPublisher(mappedPublisher, returnType.getType()); }
Example #17
Source File: ResultReader.java From micronaut-data with Apache License 2.0 | 5 votes |
/** * Convert the value to the given type. * @param value The value * @param type The type * @param <T> The generic type * @return The converted value * @throws DataAccessException if the value cannot be converted */ default <T> T convertRequired(Object value, Argument<T> type) { return ConversionService.SHARED.convert( value, type ).orElseThrow(() -> new DataAccessException("Cannot convert type [" + value.getClass() + "] with value [" + value + "] to target type: " + type + ". Consider defining a TypeConverter bean to handle this case.") ); }
Example #18
Source File: DefaultFindSliceInterceptor.java From micronaut-data with Apache License 2.0 | 5 votes |
private R convertOrFail(MethodInvocationContext<T, R> context, Slice<R> slice) { ReturnType<R> returnType = context.getReturnType(); if (returnType.getType().isInstance(slice)) { return (R) slice; } else { return ConversionService.SHARED.convert( slice, returnType.asArgument() ).orElseThrow(() -> new IllegalStateException("Unsupported slice interface: " + returnType.getType())); } }
Example #19
Source File: CountSpecificationInterceptor.java From micronaut-data with Apache License 2.0 | 5 votes |
@Override public Number intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Number> context) { final Object parameterValue = context.getParameterValues()[0]; if (parameterValue instanceof Specification) { Specification specification = (Specification) parameterValue; final EntityManager entityManager = jpaOperations.getCurrentEntityManager(); final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class); final Root<?> root = query.from(getRequiredRootEntity(context)); final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder); query.where(predicate); if (query.isDistinct()) { query.select(criteriaBuilder.countDistinct(root)); } else { query.select(criteriaBuilder.count(root)); } query.orderBy(Collections.emptyList()); final TypedQuery<Long> typedQuery = entityManager.createQuery(query); final Long result = typedQuery.getSingleResult(); final ReturnType<Number> rt = context.getReturnType(); final Class<Number> returnType = rt.getType(); if (returnType.isInstance(result)) { return result; } else { return ConversionService.SHARED.convertRequired( result, rt.asArgument() ); } } else { throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class); } }
Example #20
Source File: FindOneSpecificationInterceptor.java From micronaut-data with Apache License 2.0 | 5 votes |
@Override public Object intercept(RepositoryMethodKey methodKey, MethodInvocationContext<Object, Object> context) { final Object parameterValue = context.getParameterValues()[0]; if (parameterValue instanceof Specification) { Specification specification = (Specification) parameterValue; final EntityManager entityManager = jpaOperations.getCurrentEntityManager(); final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); final CriteriaQuery<Object> query = criteriaBuilder.createQuery((Class<Object>) getRequiredRootEntity(context)); final Root<Object> root = query.from((Class<Object>) getRequiredRootEntity(context)); final Predicate predicate = specification.toPredicate(root, query, criteriaBuilder); query.where(predicate); query.select(root); final TypedQuery<?> typedQuery = entityManager.createQuery(query); try { final Object result = typedQuery.getSingleResult(); final ReturnType<?> rt = context.getReturnType(); final Class<?> returnType = rt.getType(); if (returnType.isInstance(result)) { return result; } else { return ConversionService.SHARED.convertRequired( result, rt.asArgument() ); } } catch (NoResultException e) { if (context.isNullable()) { return null; } else { throw new EmptyResultDataAccessException(1); } } } else { throw new IllegalArgumentException("Argument must be an instance of: " + Specification.class); } }
Example #21
Source File: GraphiQLController.java From micronaut-graphql with Apache License 2.0 | 5 votes |
/** * Default constructor. * * @param graphQLConfiguration the {@link GraphQLConfiguration} instance * @param graphQLWsConfiguration the {@link GraphQLWsConfiguration} instance * @param resourceResolver the {@link ResourceResolver} instance * @param conversionService the {@link ConversionService} instance */ public GraphiQLController(GraphQLConfiguration graphQLConfiguration, GraphQLWsConfiguration graphQLWsConfiguration, ResourceResolver resourceResolver, ConversionService conversionService) { this.graphQLConfiguration = graphQLConfiguration; this.graphiQLConfiguration = graphQLConfiguration.getGraphiql(); this.graphQLWsConfiguration = graphQLWsConfiguration; this.resourceResolver = resourceResolver; this.conversionService = conversionService; // Load the raw template (variables are not yet resolved). // This means we fail fast if the template cannot be loaded resulting in a ConfigurationException at startup. this.rawTemplate = loadTemplate(graphiQLConfiguration.getTemplatePath()); this.resolvedTemplate = SupplierUtil.memoized(this::resolvedTemplate); }
Example #22
Source File: GrpcClientTypeConverterRegistrar.java From micronaut-grpc with Apache License 2.0 | 5 votes |
@Override public void register(ConversionService<?> conversionService) { conversionService.addConverter(CharSequence.class, SocketAddress.class, charSequence -> { String[] parts = charSequence.toString().split(":"); if (parts.length == 2) { int port = Integer.parseInt(parts[1]); return new InetSocketAddress(parts[0], port); } else { return null; } }); }
Example #23
Source File: GoogleMethodRouteBuilder.java From micronaut-gcp with Apache License 2.0 | 5 votes |
/** * @param executionHandleLocator The execution handler locator * @param uriNamingStrategy The URI naming strategy * @param conversionService The conversion service * @param contextPathProvider The context path provider */ public GoogleMethodRouteBuilder( ExecutionHandleLocator executionHandleLocator, UriNamingStrategy uriNamingStrategy, ConversionService<?> conversionService, ServerContextPathProvider contextPathProvider) { super(executionHandleLocator, uriNamingStrategy, conversionService); this.contextPathProvider = contextPathProvider; }
Example #24
Source File: MicronautAwsProxyRequest.java From micronaut-aws with Apache License 2.0 | 5 votes |
@Override public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) { final String v = get(name); if (v != null) { return ConversionService.SHARED.convert(v, conversionContext); } return Optional.empty(); }
Example #25
Source File: GoogleBinderRegistry.java From micronaut-gcp with Apache License 2.0 | 5 votes |
/** * Defautl constructor. * * @param mediaTypeCodecRegistry The media type codec registry * @param conversionService The conversion service * @param binders The binders */ GoogleBinderRegistry( MediaTypeCodecRegistry mediaTypeCodecRegistry, ConversionService conversionService, List<RequestArgumentBinder> binders) { super(mediaTypeCodecRegistry, conversionService, binders); this.byType.put(com.google.cloud.functions.HttpRequest.class, new GoogleRequestBinder()); this.byType.put(com.google.cloud.functions.HttpResponse.class, new GoogleResponseBinder()); this.byAnnotation.put(Part.class, new GooglePartBinder(mediaTypeCodecRegistry)); }
Example #26
Source File: GoogleFunctionHttpRequest.java From micronaut-gcp with Apache License 2.0 | 5 votes |
@Nonnull @Override public Cookies getCookies() { ServletCookies cookies = this.cookies; if (cookies == null) { synchronized (this) { // double check cookies = this.cookies; if (cookies == null) { cookies = new ServletCookies(getPath(), getHeaders(), ConversionService.SHARED); this.cookies = cookies; } } } return cookies; }
Example #27
Source File: HttpFunction.java From micronaut-gcp with Apache License 2.0 | 5 votes |
@Override public <T> Optional<T> getBody(Argument<T> type) { return ConversionService.SHARED.convert( outputStream.toByteArray(), Objects.requireNonNull(type, "Type cannot be null") ); }
Example #28
Source File: GoogleMultiValueMap.java From micronaut-gcp with Apache License 2.0 | 5 votes |
@Override public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) { final String v = get(name); if (v != null) { return ConversionService.SHARED.convert(v, conversionContext); } return Optional.empty(); }
Example #29
Source File: MicronautAwsProxyRequest.java From micronaut-aws with Apache License 2.0 | 5 votes |
/** * Default constructor. * * @param path The path * @param awsProxyRequest The underlying request * @param securityContext The {@link SecurityContext} * @param lambdaContext The lambda context * @param config The container configuration */ MicronautAwsProxyRequest( String path, AwsProxyRequest awsProxyRequest, SecurityContext securityContext, Context lambdaContext, ContainerConfig config) { this.config = config; this.awsProxyRequest = awsProxyRequest; this.path = path; final String httpMethod = awsProxyRequest.getHttpMethod(); this.httpMethod = StringUtils.isNotEmpty(httpMethod) ? HttpMethod.valueOf(httpMethod) : HttpMethod.GET; final Headers multiValueHeaders = awsProxyRequest.getMultiValueHeaders(); this.headers = multiValueHeaders != null ? new AwsHeaders() : new SimpleHttpHeaders(ConversionService.SHARED); final MultiValuedTreeMap<String, String> params = awsProxyRequest.getMultiValueQueryStringParameters(); this.parameters = params != null ? new AwsParameters() : new SimpleHttpParameters(ConversionService.SHARED); final AwsProxyRequestContext requestContext = awsProxyRequest.getRequestContext(); setAttribute(API_GATEWAY_CONTEXT_PROPERTY, requestContext); setAttribute(API_GATEWAY_STAGE_VARS_PROPERTY, awsProxyRequest.getStageVariables()); setAttribute(API_GATEWAY_EVENT_PROPERTY, awsProxyRequest); if (requestContext != null) { setAttribute(ALB_CONTEXT_PROPERTY, requestContext.getElb()); } setAttribute(LAMBDA_CONTEXT_PROPERTY, lambdaContext); setAttribute(JAX_SECURITY_CONTEXT_PROPERTY, config); if (securityContext != null && requestContext != null) { setAttribute("micronaut.AUTHENTICATION", securityContext.getUserPrincipal()); } }
Example #30
Source File: MicronautAwsProxyRequest.java From micronaut-aws with Apache License 2.0 | 5 votes |
@Override public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) { final String v = get(name); if (v != null) { return ConversionService.SHARED.convert(v, conversionContext); } return Optional.empty(); }