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: 792319 $
035 */
036 public class DefaultExchangeComparator implements ExpressionResultComparator {
037
038 private Expression expression;
039
040 public Expression getExpression() {
041 return expression;
042 }
043
044 public void setExpression(Expression 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("Expression required to resolve sequence number");
052 } else if (expressions.size() > 1) {
053 throw new IllegalArgumentException("More than one expression currently not supported");
054 }
055 expression = expressions.get(0);
056 }
057
058 public boolean predecessor(Exchange o1, Exchange o2) {
059 long n1 = getSequenceNumber(o1);
060 long n2 = getSequenceNumber(o2);
061 return n1 == (n2 - 1L);
062 }
063
064 public boolean successor(Exchange o1, Exchange o2) {
065 long n1 = getSequenceNumber(o1);
066 long n2 = getSequenceNumber(o2);
067 return n2 == (n1 - 1L);
068 }
069
070 public int compare(Exchange o1, Exchange o2) {
071 Long n1 = getSequenceNumber(o1);
072 Long n2 = getSequenceNumber(o2);
073 return n1.compareTo(n2);
074 }
075
076 private long getSequenceNumber(Exchange exchange) {
077 return expression.evaluate(exchange, Long.class);
078 }
079
080 }