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.activemq.broker.region.policy; 018 019 import org.apache.activemq.broker.region.MessageReference; 020 import org.slf4j.Logger; 021 import org.slf4j.LoggerFactory; 022 023 import java.io.IOException; 024 import java.util.ArrayList; 025 import java.util.HashMap; 026 import java.util.Iterator; 027 import java.util.LinkedList; 028 029 030 /** 031 * An eviction strategy which evicts the oldest message within messages with the same property value 032 * 033 * 034 * @org.apache.xbean.XBean 035 * 036 */ 037 public class UniquePropertyMessageEvictionStrategy extends MessageEvictionStrategySupport { 038 039 private static final Logger LOG = LoggerFactory.getLogger(UniquePropertyMessageEvictionStrategy.class); 040 041 protected String propertyName; 042 043 public String getPropertyName() { 044 return propertyName; 045 } 046 047 public void setPropertyName(String propertyName) { 048 this.propertyName = propertyName; 049 } 050 051 @Override 052 public MessageReference[] evictMessages(LinkedList messages) throws IOException { 053 MessageReference oldest = (MessageReference)messages.getFirst(); 054 HashMap<Object, MessageReference> pivots = new HashMap<Object, MessageReference>(); 055 Iterator iter = messages.iterator(); 056 057 for (int i = 0; iter.hasNext(); i++) { 058 MessageReference reference = (MessageReference) iter.next(); 059 if (propertyName != null && reference.getMessage().getProperty(propertyName) != null) { 060 Object key = reference.getMessage().getProperty(propertyName); 061 if (pivots.containsKey(key)) { 062 MessageReference pivot = pivots.get(key); 063 if (reference.getMessage().getTimestamp() > pivot.getMessage().getTimestamp()) { 064 pivots.put(key, reference); 065 } 066 } else { 067 pivots.put(key, reference); 068 } 069 } 070 } 071 072 if (!pivots.isEmpty()) { 073 for (MessageReference ref : pivots.values()) { 074 messages.remove(ref); 075 } 076 077 if (messages.size() != 0) { 078 return (MessageReference[])messages.toArray(new MessageReference[messages.size()]); 079 } 080 } 081 return new MessageReference[] {oldest}; 082 083 } 084 }