]> git.basschouten.com Git - openhab-addons.git/blob
4baa897b042bc1eda39e546597b6bacc86ab9fea
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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  * See {@link https://www.gs1.org/standards/id-keys/gln}}
20  * The Global Location Number (GLN) can be used by companies to identify their locations.
21  *
22  * @author Jacob Laursen - Initial contribution
23  */
24 @NonNullByDefault
25 public class GlobalLocationNumber {
26
27     public static final GlobalLocationNumber EMPTY = new GlobalLocationNumber("");
28
29     private static final int MAX_LENGTH = 13;
30
31     private final String gln;
32
33     public GlobalLocationNumber(String gln) {
34         if (gln.length() > MAX_LENGTH) {
35             throw new IllegalArgumentException("Maximum length exceeded: " + gln);
36         }
37         this.gln = gln;
38     }
39
40     @Override
41     public String toString() {
42         return gln;
43     }
44
45     public boolean isEmpty() {
46         return this == EMPTY;
47     }
48
49     public boolean isValid() {
50         if (gln.length() != 13) {
51             return false;
52         }
53
54         int checksum = 0;
55         for (int i = 13 - 2; i >= 0; i--) {
56             int digit = Character.getNumericValue(gln.charAt(i));
57             checksum += (i % 2 == 0 ? digit : digit * 3);
58         }
59         int controlDigit = 10 - (checksum % 10);
60         if (controlDigit == 10) {
61             controlDigit = 0;
62         }
63
64         return controlDigit == Character.getNumericValue(gln.charAt(13 - 1));
65     }
66
67     public static GlobalLocationNumber of(String gln) {
68         if (gln.isBlank()) {
69             return EMPTY;
70         }
71         return new GlobalLocationNumber(gln);
72     }
73 }