ExternalObjectRepositoryDefault.java

package org.linkedopenactors.rdfpub.adapter.driven;

import java.time.Duration;
import java.util.Optional;

import org.apache.commons.rdf.api.IRI;
import org.linkedopenactors.rdfpub.app.ExternalObjectRepository;
import org.linkedopenactors.rdfpub.domain.commonsrdf.ActivityPubObjectFactory;
import org.linkedopenactors.rdfpub.domain.commonsrdf.RdfFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ResponseStatusException;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;

@Service
@Slf4j
public class ExternalObjectRepositoryDefault implements ExternalObjectRepository {

//	@Autowired
//	private ToActivityPubObject stringToActivityPubObject;
	@Autowired
	private ActivityPubObjectFactory activityPubObjectFactory; 
	
	@Override
	public Optional<org.linkedopenactors.rdfpub.domain.commonsrdf.ActivityPubObject> read(IRI subject) {
    	WebClient webClient = WebClient.builder().build();
        var request =
                webClient
                        .get()
                        .uri(subject.toString())
                        .accept(MediaType.APPLICATION_JSON) // Hä ?? why json ??
//                        .header("Signature", signature)
                        ;
        String responseString;
		try {
			responseString = request
//        		.body(BodyInserters.fromValue(body))
			        .retrieve()
			        .onStatus(HttpStatus::is5xxServerError,
			                response -> Mono.error(new ResponseStatusException(response.statusCode())))
			        .onStatus(HttpStatus::is4xxClientError, ClientResponse::createException)
			        .bodyToMono(String.class)
			        .retryWhen(Retry.backoff(3, Duration.ofSeconds(2))
			                .filter(throwable -> throwable instanceof ResponseStatusException))
			        .block();
			
			return Optional.ofNullable(activityPubObjectFactory.create(RdfFormat.JSONLD, responseString));
//	        ActivityPubObject ao = stringToActivityPubObject.convert("application/ld+json", responseString);
//	        return Optional.ofNullable(ao);
		} catch (Exception e) {
			log.error("error reading '"+subject+"'", e);
			return Optional.empty();
		}        
	}
}