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.http.commons.exceptionhandlers; 007 008import static org.fcrepo.kernel.api.RdfLexicon.CONSTRAINED_BY; 009 010import javax.servlet.ServletContext; 011import javax.ws.rs.core.Link; 012import javax.ws.rs.core.UriInfo; 013import javax.ws.rs.ext.ExceptionMapper; 014 015import org.fcrepo.kernel.api.exception.ConstraintViolationException; 016 017/** 018 * Abstract class for constraint violation subclasses 019 * 020 * @author whikloj 021 * @since 2015-06-24 022 * @param <T> Throwable subclass of ConstraintViolationException 023 */ 024public abstract class ConstraintExceptionMapper<T extends ConstraintViolationException> implements ExceptionMapper<T> { 025 026 /** 027 * Where the RDF exception files sit. 028 */ 029 private static final String CONSTRAINT_DIR = "/static/constraints/"; 030 031 /** 032 * Creates a constrainedBy link header with the appropriate RDF URL for the exception. 033 * 034 * @param e ConstraintViolationException Exception which implements the buildContraintUri method. 035 * @param context ServletContext ServletContext that we're running in. 036 * @param uriInfo UriInfo UriInfo from the ExceptionMapper. 037 * @return Link A http://www.w3.org/ns/ldp#constrainedBy link header 038 */ 039 public static Link buildConstraintLink(final ConstraintViolationException e, 040 final ServletContext context, 041 final UriInfo uriInfo) { 042 return buildConstraintLink(e.getClass(), context, uriInfo); 043 } 044 045 /** 046 * Creates a constrainedBy link header with the appropriate RDF URL for the exception. 047 * 048 * @param clazz the class of the exception to build the link for. 049 * @param context ServletContext ServletContext that we're running in. 050 * @param uriInfo UriInfo UriInfo from the ExceptionMapper. 051 * @return Link A http://www.w3.org/ns/ldp#constrainedBy link header 052 */ 053 public static Link buildConstraintLink(final Class<? extends ConstraintViolationException> clazz, 054 final ServletContext context, 055 final UriInfo uriInfo) { 056 String path = context.getContextPath(); 057 if (path.equals("/")) { 058 path = ""; 059 } 060 061 final String constraintURI = uriInfo == null ? "" : String.format("%s://%s%s%s%s.rdf", 062 uriInfo.getBaseUri().getScheme(), uriInfo.getBaseUri().getAuthority(), path, 063 CONSTRAINT_DIR, clazz.getName().substring(clazz.getName().lastIndexOf('.') + 1)); 064 return Link.fromUri(constraintURI).rel(CONSTRAINED_BY.getURI()).build(); 065 } 066 067}