2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.aai.aaf.auth;
23 import org.onap.aai.exceptions.AAIException;
24 import org.onap.aai.logging.ErrorLogHelper;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpServletResponse;
28 import javax.ws.rs.core.MediaType;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.Collections;
33 public class ResponseFormatter {
35 private static final String ACCEPT_HEADER = "accept";
36 private static final String CONTENT_TYPE_HEADER = "Content-Type";
38 private ResponseFormatter() {
39 throw new IllegalStateException("Utility class");
42 public static void errorResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
43 errorResponse(new AAIException("AAI_3300"), request, response);
46 public static void errorResponse(AAIException exception, HttpServletRequest request, HttpServletResponse response) throws IOException {
48 if(response.isCommitted()){
52 String accept = request.getHeader(ACCEPT_HEADER);
53 switch (accept != null ? accept : MediaType.APPLICATION_XML) {
54 case MediaType.APPLICATION_JSON:
55 response.setHeader(CONTENT_TYPE_HEADER, MediaType.APPLICATION_JSON);
57 case MediaType.APPLICATION_XML:
59 response.setHeader(CONTENT_TYPE_HEADER, MediaType.APPLICATION_XML);
62 response.setStatus(exception.getErrorObject().getHTTPResponseCode().getStatusCode());
63 response.resetBuffer();
65 String resp = ErrorLogHelper.getRESTAPIErrorResponse(Collections.singletonList(MediaType.valueOf(accept)), exception, new ArrayList<>());
66 response.getOutputStream().print(resp);
67 response.flushBuffer();