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