1 /*
2 * Copyright (c) 2006-present the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.codehaus.gmaven.plugin;
17
18 import javax.annotation.Nullable;
19
20 import com.google.common.annotations.VisibleForTesting;
21 import org.apache.maven.plugin.MojoExecutionException;
22 import org.codehaus.gmaven.adapter.ClosureTarget;
23
24 /**
25 * Target implementation of {@code fail} closure.
26 *
27 * <br/>
28 * Usage:
29 * <ul>
30 * <li>{@code fail()}</li>
31 * <li>{@code fail(Object)}</li>
32 * <li>{@code fail(Throwable)}</li>
33 * <li>{@code fail(Object, Throwable)}</li>
34 * </ul>
35 *
36 * <br/>
37 * Failing with a simple string:
38 * <pre>
39 * fail('I done goofed')
40 * </pre>
41 *
42 * <br/>
43 * Failing with an exception detail:
44 * <pre>
45 * try {
46 * ....
47 * }
48 * catch (e) {
49 * fail(e)
50 * }
51 * </pre>
52 *
53 * <br/>
54 * Failing with an exception detail and a message:
55 * <pre>
56 * try {
57 * ....
58 * }
59 * catch (e) {
60 * fail('Houston we have a problem', e)
61 * }
62 * </pre>
63 *
64 * @since 2.0
65 */
66 public class FailClosureTarget
67 implements ClosureTarget
68 {
69 @VisibleForTesting
70 static final String FAILED = "Failed";
71
72 /**
73 * Throws {@link MojoExecutionException}.
74 */
75 public Object call(final @Nullable Object[] args) throws Exception {
76 if (args == null || args.length == 0) {
77 throw new MojoExecutionException(FAILED);
78 }
79 else if (args.length == 1) {
80 if (args[0] instanceof Throwable) {
81 Throwable cause = (Throwable) args[0];
82 throw new MojoExecutionException(cause.getMessage(), cause);
83 }
84 else {
85 throw new MojoExecutionException(String.valueOf(args[0]));
86 }
87 }
88 else if (args.length == 2) {
89 if (args[1] instanceof Throwable) {
90 throw new MojoExecutionException(String.valueOf(args[0]), (Throwable) args[1]);
91 }
92 else {
93 throw new Error("Invalid arguments to fail(Object, Throwable), second argument must be a Throwable");
94 }
95 }
96 else {
97 throw new Error("Too many arguments; expected one of: fail(), fail(Object) or fail(Object, Throwable)");
98 }
99 }
100 }