1 18 19 package sync4j.framework.server.store; 20 21 import java.io.Serializable ; 22 import java.util.ArrayList ; 23 24 import org.apache.commons.lang.builder.ToStringBuilder; 25 26 35 public class LogicalClause 36 extends Clause 37 implements Serializable { 38 39 41 public static final String OPT_AND = "AND"; 42 public static final String OPT_OR = "OR" ; 43 public static final String OPT_NOT = "NOT"; 44 45 47 private String operator; 48 private Clause[] operands; 49 50 52 55 public LogicalClause() {} 56 57 75 public LogicalClause(String operator, Clause[] operands) { 76 if (!OPT_AND.equalsIgnoreCase(operator) && 77 !OPT_OR.equalsIgnoreCase(operator) && 78 !OPT_NOT.equalsIgnoreCase(operator)) { 79 throw new IllegalArgumentException ( 80 "operator " + 81 operator + 82 " not supported; it must be one of (" + 83 OPT_AND + 84 "," + 85 OPT_OR + 86 "," + 87 OPT_NOT + 88 ")" 89 ); 90 } 91 if (operands == null) { 92 throw new NullPointerException ("operands is null!"); 93 } 94 95 if (OPT_NOT.equalsIgnoreCase(operator)) { 96 if (operands.length != 1) { 97 throw new IllegalArgumentException ( 98 "one and only one operand is required with " + OPT_NOT 99 ); 100 } 101 } else { 102 if (operands.length < 2) { 103 throw new IllegalArgumentException ( 104 "two or more operands are required with " + OPT_AND + " or " + OPT_OR 105 ); 106 } 107 } 108 109 this.operator = operator; 110 this.operands = operands; 111 } 112 113 117 public String getOperator() { 118 return operator; 119 } 120 121 125 public void setOperator(java.lang.String operator) { 126 this.operator = operator; 127 } 128 129 133 public Clause[] getOperands() { 134 return operands; 135 } 136 137 141 public void setOperands(sync4j.framework.server.store.Clause[] operands) { 142 this.operands = operands; 143 } 144 145 146 148 public PreparedWhere getPreparedWhere() { 149 StringBuffer sql = new StringBuffer (); 150 ArrayList parameters = new ArrayList (); 151 PreparedWhere pw = null; 152 153 if (isUnaryOperator()) { 154 pw = operands[0].getPreparedWhere(); 155 sql.append(operator.toLowerCase()).append(pw.sql); 156 for(int i=0; i<pw.parameters.length; ++i) { 157 parameters.add(pw.parameters[i]); 158 } 159 } else { 160 for (int i=0; i<operands.length; ++i) { 161 pw = operands[i].getPreparedWhere(); 162 163 if (i>0) { 164 sql.append(' ').append(operator.toLowerCase()).append(' '); 165 } 166 sql.append(pw.sql); 167 168 for(int j=0; j<pw.parameters.length; ++j) { 169 parameters.add(pw.parameters[j]); 170 } 171 } 172 } 173 174 PreparedWhere ret = new PreparedWhere(); 175 176 ret.sql = '(' + sql.toString() + ')'; 177 ret.parameters = parameters.toArray(); 178 179 return ret; 180 } 181 182 184 private boolean isUnaryOperator() { 185 return OPT_NOT.equalsIgnoreCase(operator); 186 } 187 188 190 public String toString() { 191 ToStringBuilder sb = new ToStringBuilder(this); 192 sb.append("operator:", operator); 193 194 return sb.toString(); 195 } 196 197 } 198 | Popular Tags |