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 2014 ForgeRock AS. 015 */ 016 017package org.forgerock.openig.filter.oauth2; 018 019import static java.lang.Boolean.*; 020 021import java.io.IOException; 022 023import org.forgerock.openig.el.Expression; 024import org.forgerock.openig.filter.Filter; 025import org.forgerock.openig.filter.GenericFilter; 026import org.forgerock.openig.handler.Handler; 027import org.forgerock.openig.handler.HandlerException; 028import org.forgerock.openig.http.Exchange; 029 030/** 031 * A {@link EnforcerFilter} makes sure that the handled {@link Exchange} verifies a condition. 032 * If the condition is not verified, it simply throws a {@link HandlerException} (that actually stops the chain 033 * execution). 034 */ 035public class EnforcerFilter extends GenericFilter { 036 037 private final Expression enforcement; 038 private final Filter delegate; 039 040 /** 041 * Creates a new {@link EnforcerFilter} delegating to the given {@link Filter} if the enforcement expression yields 042 * {@literal true}. 043 * 044 * @param enforcement 045 * {@link Expression} that needs to evaluates to {@literal true} for the delegating Filter to be executed. 046 * @param delegate 047 * Filter instance to delegate to. 048 */ 049 public EnforcerFilter(final Expression enforcement, final Filter delegate) { 050 this.enforcement = enforcement; 051 this.delegate = delegate; 052 } 053 054 @Override 055 public void filter(final Exchange exchange, final Handler next) throws HandlerException, IOException { 056 if (!isConditionVerified(exchange)) { 057 throw new HandlerException("Exchange could not satisfy the enforcement expression"); 058 } 059 delegate.filter(exchange, next); 060 } 061 062 private boolean isConditionVerified(final Exchange exchange) { 063 return TRUE.equals(enforcement.eval(exchange, Boolean.class)); 064 } 065}