ByteArrayDecoder.java
/*
* Copyright (C) 2019 sw4j.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sw4j.tool.barcode.random.decoder;
import java.util.Iterator;
import java.util.ServiceLoader;
/**
* <p>
* This class is an interface for new Decoders (e.g. {@link org.sw4j.tool.barcode.random.encoder.impl.Base58Decoder})
* and a factory for such decoders.
* </p>
* @author Uwe Plonus <u.plonus@gmail.com>
*/
public abstract class ByteArrayDecoder {
/**
* <p>
* For concrete decoders this method should return {@code true} if the given encoding is supported.
* </p>
* @param encoding the encoding to check for.
* @return {@code true} if the encoding is supported by the decoder.
*/
public abstract boolean supports(String encoding);
/**
* <p>
* Decode the given data into the encoding that is supported by the encoder.
* </p>
* @param data the data to decode.
* @return the decoded data.
*/
public abstract byte[] decode(String data);
/**
* <p>
* Return an decoder for the given encoding (e.g. {@code base58}).
* </p>
* @param encoding the encoding for which an decoder should be created.
* @return the decoder for the encoding or {@code null} if no decoder is available.
*/
public static ByteArrayDecoder forEncoding(final String encoding) {
ServiceLoader<ByteArrayDecoder> loader = ServiceLoader.load(ByteArrayDecoder.class);
Iterator<ByteArrayDecoder> iterator = loader.iterator();
ByteArrayDecoder decoder = null;
while (iterator.hasNext() && decoder == null) {
ByteArrayDecoder dec = iterator.next();
if (dec.supports(encoding)) {
decoder = dec;
}
}
return decoder;
}
}