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 019package org.apache.oozie.servlet; 020 021import org.apache.oozie.client.rest.JsonTags; 022import org.json.simple.JSONObject; 023 024import javax.servlet.ServletException; 025import javax.servlet.http.HttpServlet; 026import javax.servlet.http.HttpServletRequest; 027import javax.servlet.http.HttpServletResponse; 028import java.io.IOException; 029 030import static org.apache.oozie.servlet.JsonRestServlet.JSON_UTF8; 031 032/** 033 * Servlet to show error response in JSON 034 */ 035public class ErrorServlet extends HttpServlet{ 036 private static final long serialVersionUID = 1L; 037 038 @Override 039 protected void doGet(HttpServletRequest request, HttpServletResponse response) 040 throws ServletException, IOException { 041 handleError(request, response); 042 } 043 044 @Override 045 protected void doPost(HttpServletRequest request, HttpServletResponse response) 046 throws ServletException, IOException { 047 handleError(request, response); 048 } 049 050 @Override 051 protected void doPut(HttpServletRequest request, HttpServletResponse response) 052 throws ServletException, IOException { 053 handleError(request, response); 054 } 055 056 /** 057 * Writes error message as JSON to response 058 * @param request the request to get the error message from 059 * @param response the response to write the error to 060 * @throws IOException IOException 061 */ 062 private void handleError(HttpServletRequest request, HttpServletResponse response) throws IOException { 063 Object errorMsg = request.getAttribute("javax.servlet.error.message"); 064 Object statusCode = request.getAttribute("javax.servlet.error.status_code"); 065 JSONObject json = new JSONObject(); 066 json.put(JsonTags.HTTP_STATUS_CODE, statusCode); 067 json.put(JsonTags.WORKFLOW_ACTION_ERROR_MESSAGE, errorMsg); 068 response.setContentType(JSON_UTF8); 069 json.writeJSONString(response.getWriter()); 070 } 071}