1 /* 2 * Copyright (C) 2010 The Android Open Source Project 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 17 package com.android.ant; 18 19 import org.apache.tools.ant.BuildException; 20 import org.apache.tools.ant.Task; 21 import org.apache.tools.ant.taskdefs.Sequential; 22 23 /** 24 * If (condition) then: {@link Sequential} else: {@link Sequential}. 25 * 26 * In XML: 27 * <if condition="${some.condition}"> 28 * <then> 29 * </then> 30 * <else> 31 * </else> 32 * </if> 33 * 34 * both <then> and <else> behave like <sequential>. 35 * 36 * The presence of both <then> and <else> is not required, but one of them must be present. 37 * <if condition="${some.condition}"> 38 * <else> 39 * </else> 40 * </if> 41 * is perfectly valid. 42 * 43 */ 44 public class IfElseTask extends Task { 45 46 private boolean mCondition; 47 private boolean mConditionIsSet = false; 48 private Sequential mThen; 49 private Sequential mElse; 50 51 /** 52 * Sets the condition value 53 */ 54 public void setCondition(boolean condition) { 55 mCondition = condition; 56 mConditionIsSet = true; 57 } 58 59 /** 60 * Creates and returns the <then> {@link Sequential} 61 */ 62 public Object createThen() { 63 mThen = new Sequential(); 64 return mThen; 65 } 66 67 /** 68 * Creates and returns the <else> {@link Sequential} 69 */ 70 public Object createElse() { 71 mElse = new Sequential(); 72 return mElse; 73 } 74 75 @Override 76 public void execute() throws BuildException { 77 if (mConditionIsSet == false) { 78 throw new BuildException("Condition has not been set."); 79 } 80 81 // need at least one. 82 if (mThen == null && mElse == null) { 83 throw new BuildException("Need at least <then> or <else>"); 84 } 85 86 if (mCondition) { 87 if (mThen != null) { 88 mThen.execute(); 89 } 90 } else { 91 if (mElse != null) { 92 mElse.execute(); 93 } 94 } 95 } 96 } 97