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.component.dataset;
018    
019    import java.util.concurrent.atomic.AtomicInteger;
020    
021    import org.apache.camel.Component;
022    import org.apache.camel.Consumer;
023    import org.apache.camel.Exchange;
024    import org.apache.camel.Message;
025    import org.apache.camel.PollingConsumer;
026    import org.apache.camel.Processor;
027    import org.apache.camel.Service;
028    import org.apache.camel.component.mock.MockEndpoint;
029    import org.apache.camel.impl.EventDrivenPollingConsumer;
030    import org.apache.camel.util.ExchangeHelper;
031    import org.apache.camel.util.ObjectHelper;
032    import org.apache.commons.logging.Log;
033    import org.apache.commons.logging.LogFactory;
034    
035    /**
036     * @version $Revision: 1.1 $
037     */
038    public class DataSetEndpoint extends MockEndpoint implements Service {
039        private static final transient Log LOG = LogFactory.getLog(DataSetEndpoint.class);
040        private DataSet dataSet;
041        private AtomicInteger receivedCounter = new AtomicInteger();
042        private long produceDelay = -1;
043        private long consumeDelay = -1;
044        private long startTime;
045    
046        public DataSetEndpoint(String endpointUri, Component component, DataSet dataSet) {
047            super(endpointUri, component);
048            this.dataSet = dataSet;
049        }
050    
051        public static void assertEquals(String description, Object expected, Object actual, Exchange exchange) {
052            if (!ObjectHelper.equal(expected, actual)) {
053                throw new AssertionError(description + " does not match. Expected: " + expected + " but was: " + actual + " on  " + exchange + " with headers: " + exchange.getIn().getHeaders());
054            }
055        }
056    
057        @Override
058        public PollingConsumer<Exchange> createPollingConsumer() throws Exception {
059            return new EventDrivenPollingConsumer<Exchange>(this);
060        }
061    
062        @Override
063        public Consumer<Exchange> createConsumer(Processor processor) throws Exception {
064            return new DataSetConsumer(this, processor);
065        }
066    
067        @Override
068        public void reset() {
069            super.reset();
070            receivedCounter.set(0);
071        }
072    
073        @Override
074        public int getReceivedCounter() {
075            return receivedCounter.get();
076        }
077    
078        /**
079         * Creates a message exchange for the given index in the {@link DataSet}
080         */
081        public Exchange createExchange(long messageIndex) throws Exception {
082            Exchange exchange = createExchange();
083            getDataSet().populateMessage(exchange, messageIndex);
084    
085            Message in = exchange.getIn();
086            in.setHeader(DataSet.INDEX_HEADER, messageIndex);
087    
088            return exchange;
089        }
090    
091        @Override
092        protected void waitForCompleteLatch() throws InterruptedException {
093            // TODO lets do a much better version of this!
094            long size = getDataSet().getSize();
095            size *= 4000;
096            setResultWaitTime(size);
097            super.waitForCompleteLatch();
098        }
099    
100        // Properties
101        //-------------------------------------------------------------------------
102    
103        public DataSet getDataSet() {
104            return dataSet;
105        }
106    
107        public void setDataSet(DataSet dataSet) {
108            this.dataSet = dataSet;
109        }
110    
111        public long getConsumeDelay() {
112            return consumeDelay;
113        }
114    
115        /**
116         * Allows a delay to be specified which causes consumers to pause - to simulate slow consumers
117         */
118        public void setConsumeDelay(long consumeDelay) {
119            this.consumeDelay = consumeDelay;
120        }
121    
122        public long getProduceDelay() {
123            return produceDelay;
124        }
125    
126        /**
127         * Allows a delay to be specified which causes producers to pause - to simpulate slow producers
128         */
129        public void setProduceDelay(long produceDelay) {
130            this.produceDelay = produceDelay;
131        }
132    
133        // Implementation methods
134        //-------------------------------------------------------------------------
135    
136        @Override
137        protected void performAssertions(Exchange actual) throws Exception {
138            if (startTime == 0) {
139                startTime = System.currentTimeMillis();
140            }
141            int receivedCount = receivedCounter.incrementAndGet();
142            long index = receivedCount - 1;
143            Exchange expected = createExchange(index);
144    
145            // now lets assert that they are the same
146            if (LOG.isDebugEnabled()) {
147                LOG.debug("Received message: " + index + " = " + actual);
148            }
149    
150            assertMessageExpected(index, expected, actual);
151    
152            if (consumeDelay > 0) {
153                Thread.sleep(consumeDelay);
154            }
155    
156            long group = getDataSet().getReportCount();
157            if (receivedCount % group == 0) {
158                reportProgress(actual, receivedCount);
159            }
160        }
161    
162        protected void reportProgress(Exchange actual, int receivedCount) {
163            long time = System.currentTimeMillis();
164            long elapsed = time - startTime;
165            startTime = time;
166    
167            LOG.info("Received: " + receivedCount + " messages so far. Last group took: " + elapsed + " millis");
168        }
169    
170        protected void assertMessageExpected(long index, Exchange expected, Exchange actual) throws Exception {
171            long actualCounter = ExchangeHelper.getMandatoryHeader(actual, DataSet.INDEX_HEADER, Long.class);
172            assertEquals("Header: " + DataSet.INDEX_HEADER, index, actualCounter, actual);
173    
174            getDataSet().assertMessageExpected(this, expected, actual, index);
175        }
176    
177        public void start() throws Exception {
178            long size = getDataSet().getSize();
179            expectedMessageCount((int) size);
180        }
181    
182        public void stop() throws Exception {
183        }
184    }