SparqlExecutor.java

package org.linkedopenactors.rdfpub.adapter.driven;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.rdf4j.http.server.readonly.sparql.EvaluateResult;
import org.eclipse.rdf4j.http.server.readonly.sparql.SparqlQueryEvaluator;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.repository.Repository;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
class SparqlExecutor  {

	private Repository repo;
	private SparqlQueryEvaluator sparqlQueryEvaluator;
	private RdfTypeRepository rdfTypeRepository;
	
	public SparqlExecutor(Repository repo, SparqlQueryEvaluator sparqlQueryEvaluator, RdfTypeRepository rdfTypeRepository) {
		this.repo = repo;
		this.sparqlQueryEvaluator = sparqlQueryEvaluator;
		this.rdfTypeRepository = rdfTypeRepository;
	}

	public OutputStream executeSparql(String[] contexts, String query, String acceptHeader) throws IOException {
		contexts = addContextsOfAddedTypeDefinitions(contexts);
		log.trace("executeSparql(contexts: "+toString(contexts)+", query: "+query+", acceptHeader: "+acceptHeader+")");
		EvaluateResult evaluateResult = new EvaluateResultDefault(new ByteArrayOutputStream());
		if(!StringUtils.hasText(query)) {
			throw new IllegalStateException("query is mandatory!");
		}
		sparqlQueryEvaluator.evaluate(evaluateResult, repo, query, acceptHeader, contexts, null);
		return evaluateResult.getOutputstream();
	}

	private String[] addContextsOfAddedTypeDefinitions(String[] contexts) {
		String[] types = rdfTypeRepository.getContextsOfAddedTypeDefinitions()
				.stream()
				.map(IRI::stringValue)
				.collect(Collectors.toSet())
				.toArray(new String[]{});
		return ArrayUtils.addAll(contexts, types);
	}
	
	private String toString(String[] contexts) {
		return Optional.ofNullable(contexts)
				.map(Arrays::stream)
				.map(s->s.collect(Collectors.joining(",")))
				.orElse(null);
	}
}