001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions Copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2016 ForgeRock AS. 015 */ 016package org.forgerock.opendj.rest2ldap; 017 018import static org.forgerock.http.protocol.Responses.newInternalServerError; 019import static org.forgerock.opendj.rest2ldap.Rest2ldapMessages.ERR_ERROR_RESPONSE; 020import static org.forgerock.opendj.rest2ldap.Rest2ldapMessages.ERR_RUNTIME_EXCEPTION; 021 022import org.forgerock.http.Filter; 023import org.forgerock.http.Handler; 024import org.forgerock.http.protocol.Request; 025import org.forgerock.http.protocol.Response; 026import org.forgerock.http.protocol.Status; 027import org.forgerock.i18n.slf4j.LocalizedLogger; 028import org.forgerock.services.context.Context; 029import org.forgerock.util.Function; 030import org.forgerock.util.promise.NeverThrowsException; 031import org.forgerock.util.promise.Promise; 032import org.forgerock.util.promise.ResultHandler; 033 034/** Logs internal server errors and runtime exceptions once the request has been processed. */ 035public final class ErrorLoggerFilter implements Filter { 036 037 private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass(); 038 039 @Override 040 public Promise<Response, NeverThrowsException> filter(final Context context, 041 final Request request, 042 final Handler next) { 043 return next.handle(context, request) 044 .thenOnResult(new ResultHandler<Response>() { 045 @Override 046 public void handleResult(final Response response) { 047 final Exception cause = response.getCause(); 048 final Status status = response.getStatus(); 049 if (status.isServerError() && cause != null) { 050 logger.error(ERR_ERROR_RESPONSE, 051 toLog(request), 052 status.toString(), 053 cause.getLocalizedMessage(), 054 cause); 055 } 056 } 057 }).thenCatchRuntimeException(new Function<RuntimeException, Response, NeverThrowsException>() { 058 @Override 059 public Response apply(final RuntimeException e) { 060 logger.error(ERR_RUNTIME_EXCEPTION, toLog(request), e.getLocalizedMessage(), e); 061 return newInternalServerError(e); 062 } 063 }); 064 } 065 066 private String toLog(final Request request) { 067 return request.getMethod() + request.getUri(); 068 } 069}