001/**
002 *   GRANITE DATA SERVICES
003 *   Copyright (C) 2006-2014 GRANITE DATA SERVICES S.A.S.
004 *
005 *   This file is part of the Granite Data Services Platform.
006 *
007 *   Granite Data Services is free software; you can redistribute it and/or
008 *   modify it under the terms of the GNU Lesser General Public
009 *   License as published by the Free Software Foundation; either
010 *   version 2.1 of the License, or (at your option) any later version.
011 *
012 *   Granite Data Services is distributed in the hope that it will be useful,
013 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
014 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
015 *   General Public License for more details.
016 *
017 *   You should have received a copy of the GNU Lesser General Public
018 *   License along with this library; if not, write to the Free Software
019 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
020 *   USA, or see <http://www.gnu.org/licenses/>.
021 */
022package org.granite.gravity.selector;
023
024import java.util.HashMap;
025
026import org.jboss.mq.selectors.Identifier;
027import org.jboss.mq.selectors.Operator;
028import org.jboss.mq.selectors.SelectorParser;
029
030import flex.messaging.messages.Message;
031
032/**
033 * @author William DRAI
034 */
035public class JBossMQMessageSelector implements MessageSelector {
036
037    private Object selector;
038    private HashMap<String, Identifier> identifierMap = new HashMap<String, Identifier>();
039
040
041    public JBossMQMessageSelector(String selector) {
042        try {
043            this.selector = SelectorParser.doParse(selector, identifierMap);
044        }
045        catch (Exception e) {
046            throw new RuntimeException("JBossMQ SelectorParser error " + selector, e);
047        }
048    }
049
050    public synchronized boolean accept(Message message) {
051        try {
052            for (Identifier identifier : identifierMap.values()) {
053                Object value = message.getHeader(identifier.getName());
054                identifier.setValue(value);
055            }
056
057            Object res = null;
058
059            if (selector instanceof Identifier)
060                res = ((Identifier)selector).getValue();
061            else if (selector instanceof Operator)
062                res = ((Operator)selector).apply();
063            else
064                res = selector;
065
066            if (res == null)
067                return false;
068
069            if (!(res.getClass().equals(Boolean.class)))
070               throw new Exception("Bad selector result type: " + res);
071
072            return ((Boolean)res).booleanValue();
073        }
074        catch (Exception e) {
075            throw new RuntimeException("JBossMQ selector accept error " + message, e);
076        }
077    }
078
079}