ByteArrayEncoder.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.encoder;
import java.util.Iterator;
import java.util.ServiceLoader;
/**
* <p>
* This class is an interface for new Encoders (e.g. {@link org.sw4j.tool.barcode.random.encoder.impl.Base58Encoder})
* and a factory for such encoders.
* </p>
* @author Uwe Plonus <u.plonus@gmail.com>
*/
public abstract class ByteArrayEncoder {
/**
* <p>
* For concrete encoders 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 encoder.
*/
public abstract boolean supports(String encoding);
/**
* <p>
* Encode the given byte array data into the encoding that is supported by the encoder.
* </p>
* @param data the data to encode.
* @return the encoded data.
*/
public abstract String encode(byte[] data);
/**
* <p>
* Return an encoder for the given encoding (e.g. {@code base58}).
* </p>
* @param encoding the encoding for which an encoder should be created.
* @return the encoder for the encoding or {@code null} if no encoder is available.
*/
public static ByteArrayEncoder forEncoding(final String encoding) {
ServiceLoader<ByteArrayEncoder> loader = ServiceLoader.load(ByteArrayEncoder.class);
Iterator<ByteArrayEncoder> iterator = loader.iterator();
ByteArrayEncoder encoder = null;
while (iterator.hasNext() && encoder == null) {
ByteArrayEncoder enc = iterator.next();
if (enc.supports(encoding)) {
encoder = enc;
}
}
return encoder;
}
}