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 javax.ws.rs.core.Response.status;
019import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
020import static org.slf4j.LoggerFactory.getLogger;
021
022import java.util.regex.Matcher;
023import java.util.regex.Pattern;
024
025import javax.ws.rs.core.Response;
026import javax.ws.rs.ext.ExceptionMapper;
027import javax.ws.rs.ext.Provider;
028
029import org.slf4j.Logger;
030
031import com.hp.hpl.jena.query.QueryParseException;
032
033
034/**
035 * Handles Sparql query parsing exceptions thrown when querying or updating.
036 *
037 * @author whikloj
038 * @since September 9, 2014
039 */
040@Provider
041public class QueryParseExceptionMapper implements
042ExceptionMapper<QueryParseException> {
043
044    private static final Logger LOGGER = getLogger(QueryParseExceptionMapper.class);
045
046    @Override
047    public Response toResponse(final QueryParseException e) {
048
049        LOGGER.debug("Captured a query parse exception {}", e.getMessage());
050        if (e.getMessage().matches(".* Unresolved prefixed name: .*")) {
051            final Pattern namespacePattern =
052                Pattern.compile("Unresolved prefixed name: (\\w+:\\w+)");
053            final Matcher namespaceMatch =
054                namespacePattern.matcher(e.getMessage());
055            if (namespaceMatch.find()) {
056                final String msg =
057                    String.format(
058                        "There are one or more undefined namespace(s) in your request [ %s ], " +
059                        "please define them before retrying",
060                        namespaceMatch.group(1));
061                return status(BAD_REQUEST).entity(msg).build();
062            }
063        }
064
065        return status(BAD_REQUEST).entity(e.getMessage()).build();
066    }
067
068}