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 */ 017package org.apache.camel.processor.resequencer; 018 019import org.apache.camel.Exchange; 020import org.apache.camel.Expression; 021 022/** 023 * Compares elements of an {@link Exchange} sequence by comparing 024 * <code>long</code> values returned by this comparator's 025 * <code>expression</code>. 026 * 027 * @version 028 */ 029public class DefaultExchangeComparator implements ExpressionResultComparator { 030 031 private Expression expression; 032 033 @Override 034 public void setExpression(Expression expression) { 035 this.expression = expression; 036 } 037 038 @Override 039 public boolean predecessor(Exchange o1, Exchange o2) { 040 long n1 = getSequenceNumber(o1); 041 long n2 = getSequenceNumber(o2); 042 return n1 == (n2 - 1L); 043 } 044 045 @Override 046 public boolean successor(Exchange o1, Exchange o2) { 047 long n1 = getSequenceNumber(o1); 048 long n2 = getSequenceNumber(o2); 049 return n2 == (n1 - 1L); 050 } 051 052 @Override 053 public int compare(Exchange o1, Exchange o2) { 054 Long n1 = getSequenceNumber(o1); 055 Long n2 = getSequenceNumber(o2); 056 return n1.compareTo(n2); 057 } 058 059 private Long getSequenceNumber(Exchange exchange) { 060 return expression.evaluate(exchange, Long.class); 061 } 062 063 @Override 064 public boolean isValid(Exchange exchange) { 065 Long num = null; 066 try { 067 num = expression.evaluate(exchange, Long.class); 068 } catch (Exception e) { 069 // ignore 070 } 071 return num != null; 072 } 073 074 @Override 075 public String toString() { 076 return "Comparator[" + expression + "]"; 077 } 078}