001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.processor.resequencer;
018
019 import java.util.List;
020
021 import org.apache.camel.Exchange;
022 import org.apache.camel.Expression;
023
024 /**
025 * Compares elements of an {@link Exchange} sequence by comparing
026 * <code>long</code> values returned by this comaprator's
027 * <code>expression</code>. The expression is set during route definition
028 * e.g.
029 *
030 * <pre>
031 * ...resequencer(header("seqnum")).stream()...
032 * </pre>
033 *
034 * @version $Revision: 14059 $
035 */
036 public class DefaultExchangeComparator implements ExpressionResultComparator<Exchange> {
037
038 private Expression<Exchange> expression;
039
040 public Expression<Exchange> getExpression() {
041 return expression;
042 }
043
044 public void setExpression(Expression<Exchange> expression) {
045 this.expression = expression;
046 }
047
048 @SuppressWarnings("unchecked")
049 public void setExpressions(List<Expression> expressions) {
050 if (expressions.isEmpty()) {
051 throw new IllegalArgumentException(
052 "Expression required to resolve sequence number");
053 } else if (expressions.size() > 1) {
054 throw new IllegalArgumentException(
055 "More than one expression currently not supported");
056 }
057 expression = expressions.get(0);
058 }
059
060 public boolean predecessor(Exchange o1, Exchange o2) {
061 long n1 = getSequenceNumber(o1);
062 long n2 = getSequenceNumber(o2);
063 return n1 == (n2 - 1L);
064 }
065
066 public boolean successor(Exchange o1, Exchange o2) {
067 long n1 = getSequenceNumber(o1);
068 long n2 = getSequenceNumber(o2);
069 return n2 == (n1 - 1L);
070 }
071
072 public int compare(Exchange o1, Exchange o2) {
073 Long n1 = getSequenceNumber(o1);
074 Long n2 = getSequenceNumber(o2);
075 return n1.compareTo(n2);
076 }
077
078 private long getSequenceNumber(Exchange exchange) {
079 return (Long)expression.evaluate(exchange);
080 }
081
082 }