Looking for an alternative of retryWhen which is now Deprecated

Issue I’m facing an issue with WebClient and reactor-extra. Indeed, I have the following method : public Employee getEmployee(String employeeId) { return webClient.get() .uri(FIND_EMPLOYEE_BY_ID_URL, employeeId) .retrieve() .onStatus(HttpStatus.NOT_FOUND::equals, clientResponse -> Mono.empty()) .onStatus(HttpStatus::is5xxServerError, clientResponse -> Mono.error(new MyCustomException(“Something went wrong calling getEmployeeById”))) .bodyToMono(Employee.class)

Continue reading

Return the complete response using Spring WebClient

Issue I have the following code public ClientResponse doGet(HttpServletRequest request, URI uri) { return webClient.get() .uri(uri.toASCIIString()) .headers(headers -> headers.putAll(processRequest(request)) .exchange() .block(); } But when I try to return this ClientResponse through the RestController as follows, @GetMapping @ResponseBody public ClientResponse doGet(HttpServletRequest

Continue reading

How to use WebClient to execute synchronous request?

Issue Spring documentation states that we have to switch from RestTemplate to WebClient even if we want to execute synchronous http call. For now I have following code: Mono<ResponseEntity<PdResponseDto>> responseEntityMono = webClient.post() .bodyValue(myDto) .retrieve() .toEntity(MyDto.class); responseEntityMono.subscribe(resp -> log.info(“Response is {}”,

Continue reading

Table 'DBNAME.hibernate_sequence' doesn't exist

Issue I have a SpringBoot 2.0.1.RELEASE application using spring data / jpa <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> But when I do an update in the Amazon Aurora DB, I got this error: 2018-04-13 09:20 [pool-1-thread-1] ERROR o.h.id.enhanced.TableStructure.execute(148) – could not read

Continue reading

Spring boot – Not a managed type

Issue I use Spring boot+JPA and having a problem while starting the service. Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.nervytech.dialer.domain.PhoneSettings at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219) at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68) at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:89) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69) at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:177) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)

Continue reading

I have a problem with testing adding user with password encoder

Issue I have a problem when testing a method with using passwordencoder: Cannot invoke "org.springframework.security.crypto.password.PasswordEncoder.encode(java.lang.CharSequence)" because the return value of "com.store.restAPI.user.UserConfig.passwordEncoder()" is null` Thats my test class method: @ExtendWith(MockitoExtension.class) class UserServiceTest { private UserService underTest; @Mock private UserRepository userRepository; @Mock

Continue reading

Spring Boot – WebClient – multipart response – How to get the binary data

Issue Here is my code to call a REST-Service String result = webClient.post() .body(BodyInserters.fromMultipartData(bodyBuilder.build())) .exchangeToMono(clientResponse -> clientResponse.bodyToMono(String.class)) .block(); This works fine. I get a HTTP-Status 200. Response Header Content-Type: multipart/form-data; boundary="n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu." Body –n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu. Content-Disposition: form-data; name="lastname" smith –n1OnMVB:z)VeTRs)kd9:h8Hz9H+_kywMV2mb)MWu. Content-Disposition: form-data;

Continue reading

What would be the proper way to pass custom exception from Kotlin Webclient awaitExchange Lambda function to web controller?

Issue Working on a new microservice that’s using reactive WebClient to call another microservice. Here is what I have: Controller.kts @GetMapping(["/books/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE]) suspend fun getBook(…): ResponseEntity<Any> { val book = service.getBook(id) return Response.ok().body(book) } Service.kts suspend fun getBook(id:

Continue reading

Spring WebClient header from ReactiveSecurityContext

Issue I’m trying to set WebClient header value accordingly to the authenticated user, something like this: webClient.post().header(HttpHeaders.AUTHORIZATION, getUserIdFromSession())… and public String getUserIdFromSession() { Mono<Authentication> authentication = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication); //do something here to get user credentials and return them } Should I

Continue reading

java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory

Issue Spring boot version 2.4.4 Java version 15 @Bean public WebClient webClient() { return WebClient.builder().baseUrl(BASE_URL) .defaultHeaders(header -> header.setBasicAuth("test", "testpwd")) .clientConnector(new ReactorClientHttpConnector(HttpClient.newConnection())) .exchangeStrategies(ExchangeStrategies.builder().codecs(configurer -> { configurer.defaultCodecs().jaxb2Encoder(new Jaxb2XmlEncoder()); configurer.defaultCodecs().jaxb2Decoder(new Jaxb2XmlDecoder()); }).build()).build(); } Using Spring boot 2.4.4 webclient and trying to consume the

Continue reading

How to use Flux to write Json Pojo to a CSV

Issue The following function will retrieve a List of String. During the merge process, rather then print the output I would like to write the output to a CSV file. List<Mono<Device>> list1 = page.get().map(device -> webClient.post() .uri(uri) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(HttpHeaders.ACCEPT,

Continue reading

Getting some httpHeader in spring webclient call

Issue In my spring boot 2.4.1 application, I’m using WebClient for invoking some external rest services. In reqular scenario it’s pretty straightforward and works fine as I expected: InquiryChequeResponse response=webClient.post() .uri(inquiryChequeUrl) .body(Mono.just(requestDto), InquiryChequeReq.class) .exchangeToMono(res -> { return res.bodyToMono(InquiryChequeResponse.class); }).block(); But

Continue reading

Get status code of Spring WebClient request

Issue My goal is to get the HttpStatus from a Spring WebClient request. All other information of the request is irrelevant. My old way of doing this was: WebClient.builder().baseUrl("url").build() .get().exchange().map(ClientResponse::statusCode).block(); With Spring Boot 2.4.x/Spring 5.3, the exchange method of WebClient

Continue reading

WebClient ExchangeFilterFunction JUnit

Issue How do I get code coverage for ClientResponseErrorService.genericClientFilter? @PostConstruct public void init() throws SSLException { SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); HttpClient httpClient = HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); ClientHttpConnector restConnector = new ReactorClientHttpConnector(httpClient); webClient = WebClient.builder() .baseUrl(basePath) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)

Continue reading

replacing an OAuth2 WebClient in a test

Issue I have a small Spring Boot 2.2 batch that writes to an OAuth2 REST API. I have been able to configure the WebClient following https://medium.com/@asce4s/oauth2-with-spring-webclient-761d16f89cdd and it works as expected. @Configuration public class MyRemoteServiceClientOauth2Config { @Bean(“myRemoteService”) WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations)

Continue reading

adding JWT token in request in reactive way in webflux

Issue I am using WebClient to call Rest API Which are secured by JWT token. //To get Token JwtToken token = client.post() .uri(“”) .body(BodyInserters.fromFormData(“username”, “XXX”) .with(“password”, “XXXXX”)) .retrieve() .bodyToFlux(JwtToken.class) .onErrorMap(e -> new Exception(“Error While getting Token”, e)) .blockLast(); //Call secure

Continue reading

failing to add client credentials (clientid/clientsecret) at Spring Webclient: Request processing failed … 401 UNAUTHORIZED

Issue I am trying to use WebClient to consume an endpoint which provides a token. Using Postman it works as expected. Exported curl from postman is: curl –location –request POST ‘https://mycomp.url/api/oauth/token’ \ –header ‘Content-Type: application/x-www-form-urlencoded’ \ –data-urlencode ‘client_id=xxx’ \ –data-urlencode

Continue reading

How to post request with spring boot web-client for Form data for content type application/x-www-form-urlencoded

Issue How To use spring boot webclient for posting request with content type application/x-www-form-urlencoded sample curl request with content type `application/x-www-form-urlencoded’ –header ‘Content-Type: application/x-www-form-urlencoded’ \ –data-urlencode ‘username=XXXX’ \ –data-urlencode ‘password=XXXX’ How Can i send same request using webclient? Solution We

Continue reading

Using BodyInserters to pass parameter with webClient

Issue There is my code. public Mono<RespDto> function(TransReqDto1 reqDto1, TransReqDto2 reqDto2, String token) { MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("TransReqDto1", reqDto1); builder.part("TransReqDto2", reqDto2); MultiValueMap<String, HttpEntity<?>> parts = builder.build(); LinkedMultiValueMap map = new LinkedMultiValueMap(); map.add("TransReqDto1", reqDto1); map.add("TransReqDto2", reqDto2); return client.post() .uri("/api")

Continue reading

How to build URI with UriBuilder without specifying scheme, host separately?

Issue Ref: org.springframework.web.util.UriBuilder I am using UriBuilder to build a URI for an endpoint final String response = myWebClient.get() .uri(uriBuilder -> uriBuilder.scheme("https").path("example.com/mypage").path("/{id}.xml").build(id)) .header(AUTHORIZATION, getAuthorizationHeaderValue(username, password)) .accept(MediaType.TEXT_XML) .retrieve() .bodyToMono(String.class) .block(); However, I already have the value https://example.com/mypage in a string variable(fetched

Continue reading

Re-direct requests to SideEffect Utility Classes

Issue for a spring boot application that needs to be tested below is my query. @CustomLog @RestController @RequestMapping("/my_path") public class MyController { @GetMapping(path = "**", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<JsonNode> fetchData(HttpServletRequest request){ … some code…..which also calls external apis….. }

Continue reading

Where do I place "doOnError" in my webclient call?

Issue I have a webclient call that looks like :- return this.webClient.post() .uri(url) .accept(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(request)) .retrieve() .bodyToMono(Reponse.class) .doOnError(err -> { throw new UserDefinedException(); }) .block(); Would it make a difference if i placed "doOnError()" before bodyToMono/retreive/ and so on.. Solution

Continue reading