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.reifier;
018
019import java.util.Comparator;
020
021import org.apache.camel.Expression;
022import org.apache.camel.Processor;
023import org.apache.camel.model.ProcessorDefinition;
024import org.apache.camel.model.SortDefinition;
025import org.apache.camel.processor.SortProcessor;
026import org.apache.camel.spi.RouteContext;
027import org.apache.camel.support.ObjectHelper;
028
029import static org.apache.camel.builder.ExpressionBuilder.bodyExpression;
030import static org.apache.camel.util.ObjectHelper.isNotEmpty;
031
032public class SortReifier<T, U extends SortDefinition<T>> extends ExpressionReifier<U> {
033
034    public SortReifier(ProcessorDefinition<?> definition) {
035        super((U)definition);
036    }
037
038    @Override
039    @SuppressWarnings("unchecked")
040    public Processor createProcessor(RouteContext routeContext) throws Exception {
041        // lookup in registry
042        if (isNotEmpty(definition.getComparatorRef())) {
043            definition.setComparator(routeContext.lookup(definition.getComparatorRef(), Comparator.class));
044        }
045
046        // if no comparator then default on to string representation
047        if (definition.getComparator() == null) {
048            definition.setComparator(new Comparator<T>() {
049                public int compare(T o1, T o2) {
050                    return ObjectHelper.compare(o1, o2);
051                }
052            });
053        }
054
055        // if no expression provided then default to body expression
056        Expression exp;
057        if (definition.getExpression() == null) {
058            exp = bodyExpression();
059        } else {
060            exp = definition.getExpression().createExpression(routeContext);
061        }
062        return new SortProcessor<T>(exp, definition.getComparator());
063    }
064
065}