001/* 002 * The contents of this file are subject to the license and copyright 003 * detailed in the LICENSE and NOTICE files at the root of the source 004 * tree. 005 */ 006package org.fcrepo.kernel.api.utils; 007 008import static org.apache.jena.graph.NodeFactory.createURI; 009 010import org.apache.jena.graph.Node; 011import org.apache.jena.graph.Triple; 012 013/** 014 * Utility for remapping subjects in rdf triples. 015 * 016 * @author bbpennel 017 */ 018public class SubjectMappingUtil { 019 020 private SubjectMappingUtil() { 021 // Empty constructor for static utility class 022 } 023 024 /** 025 * Maps the subject of t from resourceUri to destinationUri to produce a new Triple. 026 * If the triple does not have the subject resourceUri, then the triple is unchanged. 027 * 028 * @param t triple to be remapped. 029 * @param resourceUri resource subject uri to be remapped. 030 * @param destinationUri subject uri for the resultant triple. 031 * @return triple with subject remapped to destinationUri or the original subject. 032 */ 033 public static Triple mapSubject(final Triple t, final String resourceUri, final String destinationUri) { 034 final Node destinationNode = createURI(destinationUri); 035 return mapSubject(t, resourceUri, destinationNode); 036 } 037 038 /** 039 * Maps the subject of t from resourceUri to destinationNode to produce a new Triple. 040 * If the triple does not have the subject resourceUri, then the triple is unchanged. 041 * 042 * @param t triple to be remapped. 043 * @param resourceUri resource subject uri to be remapped. 044 * @param destinationNode subject node for the resultant triple. 045 * @return triple with subject remapped to destinationNode or the original subject. 046 */ 047 public static Triple mapSubject(final Triple t, final String resourceUri, final Node destinationNode) { 048 final Node tripleSubj = t.getSubject(); 049 final String tripleSubjUri = tripleSubj.getURI(); 050 final Node subject; 051 if (tripleSubjUri.equals(resourceUri)) { 052 subject = destinationNode; 053 } else if (tripleSubjUri.startsWith(resourceUri)) { 054 // If the subject begins with the originating resource uri, such as a hash uri, then rebase 055 // the portions of the subject after the resource uri to the destination uri. 056 final String suffix = tripleSubjUri.substring(resourceUri.length()); 057 subject = createURI(destinationNode.getURI() + suffix); 058 } else { 059 subject = t.getSubject(); 060 } 061 return new Triple(subject, t.getPredicate(), t.getObject()); 062 } 063}