001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package org.apache.hadoop.lib.wsrs;
020
021 import org.apache.hadoop.fs.http.client.HttpFSFileSystem;
022 import org.slf4j.Logger;
023 import org.slf4j.LoggerFactory;
024
025 import javax.ws.rs.core.MediaType;
026 import javax.ws.rs.core.Response;
027 import javax.ws.rs.ext.ExceptionMapper;
028 import java.util.LinkedHashMap;
029 import java.util.Map;
030
031 public class ExceptionProvider implements ExceptionMapper<Throwable> {
032 private static Logger LOG = LoggerFactory.getLogger(ExceptionProvider.class);
033
034 private static final String ENTER = System.getProperty("line.separator");
035
036 protected Response createResponse(Response.Status status, Throwable throwable) {
037 Map<String, Object> json = new LinkedHashMap<String, Object>();
038 json.put(HttpFSFileSystem.ERROR_MESSAGE_JSON, getOneLineMessage(throwable));
039 json.put(HttpFSFileSystem.ERROR_EXCEPTION_JSON, throwable.getClass().getSimpleName());
040 json.put(HttpFSFileSystem.ERROR_CLASSNAME_JSON, throwable.getClass().getName());
041 Map<String, Object> response = new LinkedHashMap<String, Object>();
042 response.put(HttpFSFileSystem.ERROR_JSON, json);
043 log(status, throwable);
044 return Response.status(status).type(MediaType.APPLICATION_JSON).entity(response).build();
045 }
046
047 protected String getOneLineMessage(Throwable throwable) {
048 String message = throwable.getMessage();
049 if (message != null) {
050 int i = message.indexOf(ENTER);
051 if (i > -1) {
052 message = message.substring(0, i);
053 }
054 }
055 return message;
056 }
057
058 protected void log(Response.Status status, Throwable throwable) {
059 LOG.debug("{}", throwable.getMessage(), throwable);
060 }
061
062 @Override
063 public Response toResponse(Throwable throwable) {
064 return createResponse(Response.Status.BAD_REQUEST, throwable);
065 }
066
067 }