001/**
002 * Copyright 2015 DuraSpace, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.fcrepo.http.commons.exceptionhandlers;
017
018import static org.fcrepo.kernel.api.RdfLexicon.CONSTRAINED_BY;
019
020import javax.ws.rs.core.Link;
021import javax.ws.rs.core.UriInfo;
022import javax.ws.rs.ext.ExceptionMapper;
023
024import org.fcrepo.kernel.api.exception.ConstraintViolationException;
025
026/**
027 * Abstract class for constraint violation subclasses
028 *
029 * @author whikloj
030 * @since 2015-06-24
031 * @param <T> Throwable subclass of ConstraintViolationException
032 */
033public abstract class ConstraintExceptionMapper<T extends ConstraintViolationException> implements ExceptionMapper<T> {
034
035    /**
036     * Where the RDF exception files sit.
037     */
038    private static final String CONSTRAINT_DIR = "/static/constraints/";
039
040    /**
041     * Creates a constrainedBy link header with the appropriate RDF URL for the exception.
042     *
043     * @param e ConstraintViolationException Exception which implements the buildContraintUri method.
044     * @param uriInfo UriInfo UriInfo from the ExceptionMapper.
045     * @return Link A http://www.w3.org/ns/ldp#constrainedBy link header
046     */
047    public static Link buildConstraintLink(final ConstraintViolationException e, final UriInfo uriInfo) {
048        final String constraintURI = uriInfo == null ? "" : String.format("%s://%s%s%s.rdf",
049                uriInfo.getBaseUri().getScheme(), uriInfo.getBaseUri().getAuthority(),
050                CONSTRAINT_DIR, e.getClass().toString().substring(e.getClass().toString().lastIndexOf('.') + 1));
051        return Link.fromUri(constraintURI).rel(CONSTRAINED_BY.getURI()).build();
052    }
053
054}