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 * @author Martin Krasser
035 *
036 * @version $Revision: 743330 $
037 */
038 public class DefaultExchangeComparator implements ExpressionResultComparator {
039
040 private Expression expression;
041
042 public Expression getExpression() {
043 return expression;
044 }
045
046 public void setExpression(Expression expression) {
047 this.expression = expression;
048 }
049
050 @SuppressWarnings("unchecked")
051 public void setExpressions(List<Expression> expressions) {
052 if (expressions.isEmpty()) {
053 throw new IllegalArgumentException("Expression required to resolve sequence number");
054 } else if (expressions.size() > 1) {
055 throw new IllegalArgumentException("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 expression.evaluate(exchange, Long.class);
080 }
081
082 }