001/*
002 * HA-JDBC: High-Availability JDBC
003 * Copyright (C) 2012  Paul Ferraro
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Lesser General Public License as published by
007 * the Free Software Foundation, either version 3 of the License, or
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Lesser General Public License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018package net.sf.hajdbc.codec;
019
020import java.io.Serializable;
021import java.sql.SQLException;
022
023import net.sf.hajdbc.IdentifiableMatcher;
024import net.sf.hajdbc.util.ServiceLoaders;
025
026/**
027 * Codec factory that whose decoding behavior is determined by a prefix.
028 * @author Paul Ferraro
029 */
030public class MultiplexingDecoderFactory implements DecoderFactory, Serializable {
031
032        public static final String DELIMITER = ":";
033        private static final long serialVersionUID = 4413927326976263687L;
034
035        @Override
036        public Decoder createDecoder(String clusterId)
037        {
038                return new MultiplexingDecoder(clusterId);
039        }
040
041        private static class MultiplexingDecoder implements Decoder
042        {
043                private final String clusterId;
044                
045                MultiplexingDecoder(String clusterId)
046                {
047                        this.clusterId = clusterId;
048                }
049                
050                @Override
051                public String decode(String value) throws SQLException
052                {
053                        if (value == null) return null;
054                        int index = value.indexOf(DELIMITER);
055                        String id = (index >= 0) ? value.substring(0, index) : null;
056                        String source = (index >= 0) ? value.substring(index + 1) : value;
057                        CodecFactory factory = ServiceLoaders.findRequiredService(new IdentifiableMatcher<CodecFactory>(id), CodecFactory.class);
058                        return factory.createCodec(this.clusterId).decode(source);
059                }
060        }
061}