net.java.truecommons.shed.AbstractExceptionBuilder Maven / Gradle / Ivy
Show all versions of truecommons-shed Show documentation
/*
* Copyright (C) 2005-2015 Schlichtherle IT Services.
* All rights reserved. Use is subject to license terms.
*/
package net.java.truecommons.shed;
import static java.util.Objects.requireNonNull;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Abstract implementation of an exception builder.
* Subclasses must implement {@link #update(Throwable, Throwable)} and may
* override {@link #post(Throwable)}.
*
* @param the type of the input exceptions.
* @param the type of the assembled (output) exceptions.
* @author Christian Schlichtherle
*/
@NotThreadSafe
public abstract class AbstractExceptionBuilder< I extends Throwable,
O extends Throwable>
implements ExceptionBuilder {
private @CheckForNull O assembly;
/**
* {@inheritDoc}
*
* @see #update(Throwable, Throwable)
* @see #post(Throwable)
*/
@Override
public final O fail(I input) {
final O assembly = update(input);
this.assembly = null;
return post(assembly);
}
/**
* {@inheritDoc}
*
* The implementation in the class {@link AbstractExceptionBuilder} adds
* the given exception to the assembly for subsequent rethrowing upon a
* call to {@link #check()}.
*
* @see #update(Throwable, Throwable)
*/
@Override
public final void warn(I input) { this.assembly = update(input); }
/**
* {@inheritDoc}
*
* @see #post(Throwable)
*/
@Override
public final void check() throws O {
final O assembly = this.assembly;
if (null != assembly) {
this.assembly = null;
throw post(assembly);
}
}
private O update(I input) {
return update(requireNonNull(input), this.assembly);
}
/**
* This function gets called to update the given {@code previous} result of
* the assembly with the given input exception.
*
* @param input the input exception to handle.
* @param assembly the current assembled (output) exception or {@code null}
* if this is the first call to this method or the last assembly
* has already been checked out.
* @return The next assembled (output) exception, never {@code null}.
*/
protected abstract O update(I input, @CheckForNull O assembly);
/**
* This function gets called to post-process the given result of the
* assembly after it has been checked out.
*
* The implementation in the class {@link AbstractExceptionBuilder} simply
* returns {@code assembly}.
*
* @param assembly the assembled (output) exception.
* @return The result of the optional post-processing.
*/
protected O post(O assembly) { return assembly; }
}