View Javadoc
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.encoder;
18  
19  import java.util.Iterator;
20  import java.util.ServiceLoader;
21  
22  /**
23   * <p>
24   * This class is an interface for new Encoders (e.g. {@link org.sw4j.tool.barcode.random.encoder.impl.Base58Encoder})
25   * and a factory for such encoders.
26   * </p>
27   * @author Uwe Plonus &lt;u.plonus@gmail.com&gt;
28   */
29  public abstract class ByteArrayEncoder {
30  
31      /**
32       * <p>
33       * For concrete encoders 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 encoder.
37       */
38      public abstract boolean supports(String encoding);
39  
40      /**
41       * <p>
42       * Encode the given byte array data into the encoding that is supported by the encoder.
43       * </p>
44       * @param data the data to encode.
45       * @return the encoded data.
46       */
47      public abstract String encode(byte[] data);
48  
49      /**
50       * <p>
51       * Return an encoder for the given encoding (e.g. {@code base58}).
52       * </p>
53       * @param encoding the encoding for which an encoder should be created.
54       * @return the encoder for the encoding or {@code null} if no encoder is available.
55       */
56      public static ByteArrayEncoder forEncoding(final String encoding) {
57          ServiceLoader<ByteArrayEncoder> loader = ServiceLoader.load(ByteArrayEncoder.class);
58          Iterator<ByteArrayEncoder> iterator = loader.iterator();
59          ByteArrayEncoder encoder = null;
60          while (iterator.hasNext() && encoder == null) {
61              ByteArrayEncoder enc = iterator.next();
62              if (enc.supports(encoding)) {
63                  encoder = enc;
64              }
65          }
66          return encoder;
67      }
68  
69  }