1 /*
2 * Copyright (C) 2019 sw4j.org
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package org.sw4j.tool.barcode.random.decoder;
18
19 import java.util.Iterator;
20 import java.util.ServiceLoader;
21
22 /**
23 * <p>
24 * This class is an interface for new Decoders (e.g. {@link org.sw4j.tool.barcode.random.encoder.impl.Base58Decoder})
25 * and a factory for such decoders.
26 * </p>
27 * @author Uwe Plonus <u.plonus@gmail.com>
28 */
29 public abstract class ByteArrayDecoder {
30
31 /**
32 * <p>
33 * For concrete decoders this method should return {@code true} if the given encoding is supported.
34 * </p>
35 * @param encoding the encoding to check for.
36 * @return {@code true} if the encoding is supported by the decoder.
37 */
38 public abstract boolean supports(String encoding);
39
40 /**
41 * <p>
42 * Decode the given data into the encoding that is supported by the encoder.
43 * </p>
44 * @param data the data to decode.
45 * @return the decoded data.
46 */
47 public abstract byte[] decode(String data);
48
49 /**
50 * <p>
51 * Return an decoder for the given encoding (e.g. {@code base58}).
52 * </p>
53 * @param encoding the encoding for which an decoder should be created.
54 * @return the decoder for the encoding or {@code null} if no decoder is available.
55 */
56 public static ByteArrayDecoder forEncoding(final String encoding) {
57 ServiceLoader<ByteArrayDecoder> loader = ServiceLoader.load(ByteArrayDecoder.class);
58 Iterator<ByteArrayDecoder> iterator = loader.iterator();
59 ByteArrayDecoder decoder = null;
60 while (iterator.hasNext() && decoder == null) {
61 ByteArrayDecoder dec = iterator.next();
62 if (dec.supports(encoding)) {
63 decoder = dec;
64 }
65 }
66 return decoder;
67 }
68
69 }