All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.linkedopenactors.rdfpub.domain.RdfObjectDefault Maven / Gradle / Ivy

The newest version!
package org.linkedopenactors.rdfpub.domain;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.util.Models;
import org.eclipse.rdf4j.model.util.Values;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.Rio;
import org.slf4j.Logger;

import de.naturzukunft.rdf4j.utils.ModelLogger;
import de.naturzukunft.rdf4j.vocabulary.AS;
import de.naturzukunft.rdf4j.vocabulary.SCHEMA_ORG;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
class RdfObjectDefault implements RdfObject {
	private Model model;
	private IRI subject;
	private Long version;
	private String identifier;
	private Set types;
	private IRI[] contexts;
	
	public RdfObjectDefault(@NonNull Model model, IRI... contexts) {
		this.model = model;
		this.contexts = contexts;		
        this.subject = extractSubject(model);        
        this.version = extractVersion();        
        this.identifier = extractIdentifier(model);
        this.types = extractTypes(model);
	}

	private Set extractTypes(Model model) {
		Set types = Models.getPropertyIRIs(model, subject, RDF.TYPE);
        if(types.isEmpty()) {
        	throw new IllegalStateException("minimal one type expected, but is: " + types);
        }
        return types;
	}

	private String extractIdentifier(Model model) {
		Set identifiers = Models.getPropertyLiterals(model, subject, SCHEMA_ORG.identifier);
        if(identifiers.size()!=1) {
        	model.add(subject, SCHEMA_ORG.identifier, Values.literal(UUID.randomUUID().toString()));
        	identifiers = Models.getPropertyLiterals(model, subject, SCHEMA_ORG.identifier);
        }
        return identifiers.stream().findFirst().orElseThrow().stringValue();
	}

	private long extractVersion() {
		Set versions = Models.getPropertyLiterals(model, subject, SCHEMA_ORG.version);		
        if(versions.size()!=1) {
        	model.add(subject, SCHEMA_ORG.version, Values.literal(0));
        	versions = Models.getPropertyLiterals(model, subject, SCHEMA_ORG.version);
        }
        Literal versionLiteral = versions.stream().findFirst().orElseThrow();
        long version = versionLiteral.longValue();
        if (version < 0) {
            throw new IllegalStateException("extractVersion() -> minimum version is 0, but is" + version);
        }
		return version;
	}

	private IRI extractSubject(Model model) {
		Map> bySubject = model.stream()
                .collect(Collectors.groupingBy(x -> x.getSubject()));
        String msg = "exact one subject expected, but is: " + bySubject.keySet();
		if(bySubject.size()>1) {
        	ModelLogger.error(log, model, msg);
        	throw new IllegalStateException(msg);
        }
        return (IRI)bySubject.keySet().stream()
        		.findFirst()
        		.orElseThrow(()->new IllegalStateException(msg));
	}
	
    /**
     * Extracts the {@link IRI} of the property {@link AS#attributedTo} from the {@link ModelAndSubject#getSubject()} object.
     * 
     * @param model
     * @param subject
     * @return The {@link IRI} of the property {@link AS#attributedTo} from the {@link ModelAndSubject#getSubject()} object.
     */
    private Set extractAttributedTo(Model model, IRI subject) {
        return Models.getPropertyIRIs(model, subject, AS.attributedTo);
    }
    
	@Override
	public String toString() {
		StringWriter sw = new StringWriter();
		if(model!=null) {
			Rio.write(model, sw, RDFFormat.TRIGSTAR);
		}
		return "RdfObject ["+sw.toString()+"]";
	}
	
	@Override
	public void dump(Logger logger) {
		logger.debug(toShortString());
		logger.trace(toExtendedString());
	}
	
	private String toShortString() {	
		StringBuilder sb = new StringBuilder();		
		sb.append("RdfObjectRevision: ")
		.append(subject).append(", ")
		.append("identifier: ").append(identifier).append(", ")
		.append("version: ").append(version).append(", ")
		.append("attributedtTo: ").append(extractAttributedTo(model, subject)).append(", ")
		.append("types: ").append(types);
		return sb.toString();
	}
	
	private String toExtendedString() {
		StringBuilder sb = new StringBuilder();
		Set stmts = model.filter(null, null, null);
		for (Statement stmt : stmts) {
			sb.append("\t")
			.append(stmt.getPredicate())
			.append(", ")
			.append(stmt.getObject())
			.append(" (")
			.append(stmt.getContext())
			.append(")\n");			
		}
		return sb.toString();
	}
	
	@Override
	public Resource[] getContexts() {
		return this.contexts;
	}
	
	@Override
	public void setContexts(Set contexts) {
		this.contexts = contexts.toArray(new IRI[] {});
	}

	@Override
	public String getModelAsTurtle() {
		StringWriter sw = new StringWriter();
		Rio.write(getModel(), sw, RDFFormat.TURTLE);
		return sw.toString();
	}    
	
	public Optional getPropertyIRI(IRI predicate) {
		return Models.getPropertyIRI(getModel(), getSubject(), predicate);
	}
	
	public Set getPropertyIRIs(IRI predicate) {
		return Models.getPropertyIRIs(getModel(), getSubject(), predicate);
	}

	public Optional getPropertyLiteral(IRI predicate) {
		return Models.getPropertyLiteral(getModel(), getSubject(), predicate);
	}

	public Optional getPropertyString(IRI predicate) {
		return Models.getPropertyString(getModel(), getSubject(), predicate);
	}
	
	public Set getAttributedtTo() {
		return extractAttributedTo(model, subject);
	}
	
	@Override
	public void addAttributedtTo(IRI attributedTo) {
		getModel().add(getSubject(), AS.attributedTo, attributedTo);
	}
	
	public Model getModel() {
		Model filtered = this.model.filter(null,  null,  null);
		return filtered;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy