package org.talend.sdk.component.junit;

import static org.junit.Assert.fail;

import java.util.function.Consumer;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

/**
 * A rule to access an exception from a test using a Consumer<HttpException>.
 * <code>
 *
 * @Rule public ExceptionVerifier<HttpException> httpExceptionRule = new ExceptionVerifier<>();
 * ...
 * httpExceptionRule.assertWith(e -> {
 * assertEquals(401, e.getResponse().status());
 * assertEquals("expected error message", e.getResponse().error(String.class));
 * });
 *
 * </code>
 */
public class ExceptionVerifier<T extends RuntimeException> implements TestRule {

    private Consumer<T> consumer;

    public void assertWith(final Consumer<T> consumer) {
        this.consumer = consumer;
    }

    @Override
    public Statement apply(final Statement base, final Description description) {

        return new Statement() {

            @Override
            public void evaluate() throws Throwable {
                try {
                    base.evaluate();
                    if (consumer != null) {
                        fail("expected exception not thrown");
                    }
                } catch (final RuntimeException e) {
                    if (consumer == null) {
                        throw e;
                    }
                    try {
                        consumer.accept((T) e);
                    } catch (final ClassCastException cce) {
                        throw e;
                    }
                } finally {
                    consumer = null;
                }
            }
        };
    }
}

@@ -1,8 +1,638 @@
+/**%0A * Copyright (C) 2006-2017 Talend Inc. - www.talend.com%0A * %3Cp%3E%0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A * %3Cp%3E%0A * http://www.apache.org/licenses/LICENSE-2.0%0A * %3Cp%3E%0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License.%0A */%0A
 package 
@@ -909,24 +909,31 @@
 using a 
+%7B@link 
 Consumer
 %3CHttpExc
@@ -928,42 +928,55 @@
 umer
-%3CHttpException%3E.
+%7D%0A * Usage example :%0A * %0A * %3Cpre%3E
 %0A * 
-%3C
+%7B@
 code
-%3E
 %0A *
-%0A * @
+ 
 Rule
@@ -1070,14 +1070,50 @@
 %0A * 
-...%0A *
+ &#64;Test%0A *  public void test()%7B%0A *     
  htt
@@ -1147,16 +1147,25 @@
  -%3E %7B%0A *
+         
  assertE
@@ -1204,16 +1204,25 @@
 s());%0A *
+         
  assertE
@@ -1297,24 +1297,36 @@
 ;%0A *
+     
  %7D);%0A *
+  %7D%0A * %7D
 %0A * %3C/
-cod
+pr
 e%3E%0A 

add javadoc and copyright header