if else condition with Java Lamba – Howto

//lambda Predicate
private static Predicate<HttpStatus> isErrorCode = (HttpStatus statusCode) -> (statusCode.is5xxServerError() || statusCode.is4xxClientError());

//your method
public static Mono<ClientResponse> getResponse(ClientResponse clientResponse) {
        if (isErrorCode.test(clientResponse.statusCode())) {

Do not forget to checkout the BiPredicate as well 😉

Why Spring Webflux is better than HttpClient – HowTo in Java

A lot of Boilerplate Code can be avoided.

AND: it is reactive, non-blocking.

Example (really, an example) – the ‚old way‘:

        HttpPost request = new HttpPost("http://www.someurl.de");
        request.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        request.setHeader(HttpHeaders.CONTENT_TYPE, 
                                              ContentType.APPLICATION_JSON.getMimeType());

        String json = someJsonConverter.toJson(someRequestDto);
        HttpEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        request.setEntity(stringEntity);

        try {
            CloseableHttpResponse response2 = httpclient.execute(request);

            if (HttpStatus.SC_CREATED != response2.getStatusLine().getStatusCode()) {
                //TODO eventually handle http statuus additionally
                return returnHandleAndDoNotThrow();
            }
            SomeResponseDto responseDto = (SomeResponseDto) 
                someJsonConverter.toDto(EntityUtils.toString(response.getEntity()), 
                                                               SomerResponseDto.class);
            return Optional.ofNullable(responseDto);
        } catch (IOException e) {
            return Optional.empty();;
        }

The new way:

        Function<UriBuilder, URI> function = uriBuilder ->  
                                                  uriBuilder.path("/somePath").build();
        return client.post()
                .uri(function)
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(someDtoInstance), SomeDto.class)
                .exchange()
                .block()
                .bodyToFlux(someResponseDto.class);
//any errors, status codes are handled by a filter which you can define as follows:

Howto:

I am using Spring Boot for this, so I do have a Config class.

import ...
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.context.annotation.Configuration;


@Configuration
public class WebClientConfig {

    //Create the Bean for Autowiring
    @Bean
    public WebClient webClient() {
        return WebClient.builder().filter(someStatusHandlingFilter()).build();
    }
    
    //Handle status codes
    public static ExchangeFilterFunction someStatusHandlingFilter() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            if ((clientResponse.statusCode().is4xxServerError() 
                || clientResponse.statusCode().is5xxClientError())) {
                return clientResponse                        
                        .bodyToMono(SomeException.class)
                        .flatMap(errorBody -> {
                            return Mono.error(someExceptionToLog);
                        });
            } else {
                return Mono.just(clientResponse);
            }
        });
    }
}

Maven:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
            <version>your latest version goes here</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <version>your latest version goes here</version>
        </dependency>

Java Stream Custom Collector – Howto

Sometimes the commonly available Collectors are not what we need.
Here is one example for a Singleton Custom Collector:

public static <T> Collector<T, ?, T> singleton() {
    return Collectors.collectingAndThen(
            Collectors.toList(), list -> {
                if (list.size() != 1) {
                    // or log and return nil
                    throw new CustomException();
                }
                return list.get(0);
            }
    );
}

//and use it:
        myObjectToStream.stream()
        .filter(elem -> elem.getExampleAttribute() == 0).collect(singleton());

Howto generate a new SSH key pair

ssh-keygen -t ed25519 -C "email@example.com"

Note that in this example we use an ed25519 key.

The -c is providing a comment to divide the key amongst others.

I alwas use the suggested path and just klick enter 😉

JUnit Test String contained / contains String

With the Hamcrest Matchers, do this:

//imports
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;

//assert
assertThat(actualData, containsString(expectedData));

How to test Websites with Java

A very good way of testing a website is Selenium: http://seleniumhq.org/
The Groovy driven alternative is Tellurium which provides an easier entry but is not as good as Selenium for more complex Use Cases: http://code.google.com/p/aost/

Code driven (JUnit-like):

  • Java Tests for Selenium
  • Selenium will start to interact with your WebBrowser, as guided by the Tests.
  • Bears strong resemblance to normal UNIT Tests

Browser-driven:

  • Create a Selenium Test Suite by recording your clicks and website navigation in your browser.
  • Replay in your browser