2 * Rhynodge - FailedState.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.rhynodge.states;
20 import java.io.IOException;
21 import java.io.PrintWriter;
22 import java.io.StringWriter;
23 import java.io.Writer;
24 import javax.annotation.Nonnull;
26 import net.pterodactylus.rhynodge.State;
29 * {@link State} implementation that signals failure.
31 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
33 public class FailedState extends AbstractState {
35 /** A failed state instance without an exception. */
36 public static final State INSTANCE = new FailedState();
39 * Creates a new failed state.
41 public FailedState() {
46 * Creates a new failed state with the given exception
49 * The exception of the state
51 public FailedState(Throwable exception) {
56 public boolean isEmpty() {
62 protected String plainText() {
63 if (exception() == null) {
66 try (Writer stringWriter = new StringWriter();
67 PrintWriter printWriter = new PrintWriter(stringWriter)) {
68 exception().printStackTrace(printWriter);
69 return "Failed: " + stringWriter.toString();
70 } catch (IOException ioe1) {
71 return "Failed while rendering exception";
80 * Returns a failed state for the given state. The failed state will be
81 * unsuccessful ({@link #success()} returns false) and it will contain the
82 * same {@link #exception()} as the given state.
85 * The state to copy the exception from
86 * @return A failed state
88 public static FailedState from(State state) {
89 if (state instanceof FailedState) {
90 return (FailedState) state;
92 return new FailedState(state.exception());
103 public String toString() {
104 return String.format("%s[exception=%s]", getClass().getSimpleName(), exception());