]> git.basschouten.com Git - openhab-addons.git/blob
933e013b0e2f4639c35b1ed93451b2de58378c70
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.energidataservice.internal.api;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16
17 /**
18  * Global Location Number.
19  * 
20  * The <a href="https://www.gs1.org/standards/id-keys/gln">Global Location Number (GLN)</a>
21  * can be used by companies to identify their locations.
22  *
23  * @author Jacob Laursen - Initial contribution
24  */
25 @NonNullByDefault
26 public class GlobalLocationNumber {
27
28     public static final GlobalLocationNumber EMPTY = new GlobalLocationNumber("");
29
30     private static final int MAX_LENGTH = 13;
31
32     private final String gln;
33
34     public GlobalLocationNumber(String gln) {
35         if (gln.length() > MAX_LENGTH) {
36             throw new IllegalArgumentException("Maximum length exceeded: " + gln);
37         }
38         this.gln = gln;
39     }
40
41     @Override
42     public String toString() {
43         return gln;
44     }
45
46     public boolean isEmpty() {
47         return this == EMPTY;
48     }
49
50     public boolean isValid() {
51         if (gln.length() != 13) {
52             return false;
53         }
54
55         int checksum = 0;
56         for (int i = 13 - 2; i >= 0; i--) {
57             int digit = Character.getNumericValue(gln.charAt(i));
58             checksum += (i % 2 == 0 ? digit : digit * 3);
59         }
60         int controlDigit = 10 - (checksum % 10);
61         if (controlDigit == 10) {
62             controlDigit = 0;
63         }
64
65         return controlDigit == Character.getNumericValue(gln.charAt(13 - 1));
66     }
67
68     public static GlobalLocationNumber of(String gln) {
69         if (gln.isBlank()) {
70             return EMPTY;
71         }
72         return new GlobalLocationNumber(gln);
73     }
74 }