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.loadbalancer;
018    
019    import java.util.List;
020    import java.util.Random;
021    
022    import org.apache.camel.Exchange;
023    import org.apache.camel.Processor;
024    
025    public class WeightedRandomLoadBalancer extends WeightedLoadBalancer {
026        private int randomCounter;
027        
028        public WeightedRandomLoadBalancer(List<Integer> distributionRatioList) {
029            super(distributionRatioList);
030        }
031        
032        @Override
033        protected Processor chooseProcessor(List<Processor> processors, Exchange exchange) {
034            boolean found = false;
035            while (!found) {
036                if (getRuntimeRatios().isEmpty())  {
037                    loadRuntimeRatios(getDistributionRatioList());
038                }
039                
040                randomCounter = 0;
041                if (getRuntimeRatios().size() > 0) {
042                    randomCounter = new Random().nextInt(getRuntimeRatios().size());
043                } 
044                    
045                if (getRuntimeRatios().get(randomCounter).getRuntimeWeight() > 0) {
046                    getRuntimeRatios().get(randomCounter).setRuntimeWeight((getRuntimeRatios().get(randomCounter).getRuntimeWeight()) - 1);
047                    found = true;
048                } else {
049                    getRuntimeRatios().remove(randomCounter);
050                }
051            }
052    
053            return processors.get(getRuntimeRatios().get(randomCounter).getProcessorPosition());
054        }
055        
056    }