]> git.basschouten.com Git - openhab-addons.git/blob
b9e1dc650c9a6421d1526e7935b3624f4796210d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.tr064.internal.phonebook;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.InputStream;
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.Optional;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
23 import java.util.stream.Collectors;
24
25 import javax.xml.bind.JAXBContext;
26 import javax.xml.bind.JAXBException;
27 import javax.xml.bind.Unmarshaller;
28 import javax.xml.transform.stream.StreamSource;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jetty.client.HttpClient;
32 import org.eclipse.jetty.client.api.ContentResponse;
33 import org.eclipse.jetty.http.HttpMethod;
34 import org.openhab.binding.tr064.internal.dto.additions.PhonebooksType;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * The {@link Tr064PhonebookImpl} class implements a phonebook
40  *
41  * @author Jan N. Klug - Initial contribution
42  */
43 @NonNullByDefault
44 public class Tr064PhonebookImpl implements Phonebook {
45     private final Logger logger = LoggerFactory.getLogger(Tr064PhonebookImpl.class);
46
47     private Map<String, String> phonebook = new HashMap<>();
48
49     private final HttpClient httpClient;
50     private final String phonebookUrl;
51
52     private String phonebookName = "";
53
54     public Tr064PhonebookImpl(HttpClient httpClient, String phonebookUrl) {
55         this.httpClient = httpClient;
56         this.phonebookUrl = phonebookUrl;
57         getPhonebook();
58     }
59
60     private void getPhonebook() {
61         try {
62             ContentResponse contentResponse = httpClient.newRequest(phonebookUrl).method(HttpMethod.GET)
63                     .timeout(2, TimeUnit.SECONDS).send();
64             InputStream xml = new ByteArrayInputStream(contentResponse.getContent());
65
66             JAXBContext context = JAXBContext.newInstance(PhonebooksType.class);
67             Unmarshaller um = context.createUnmarshaller();
68             PhonebooksType phonebooksType = um.unmarshal(new StreamSource(xml), PhonebooksType.class).getValue();
69
70             phonebookName = phonebooksType.getPhonebook().getName();
71
72             phonebook = phonebooksType.getPhonebook().getContact().stream().map(contact -> {
73                 String contactName = contact.getPerson().getRealName();
74                 return contact.getTelephony().getNumber().stream()
75                         .collect(Collectors.toMap(number -> normalizeNumber(number.getValue()), number -> contactName));
76             }).collect(HashMap::new, HashMap::putAll, HashMap::putAll);
77             logger.debug("Downloaded phonebook {}: {}", phonebookName, phonebook);
78         } catch (JAXBException | InterruptedException | ExecutionException | TimeoutException e) {
79             logger.warn("Failed to get phonebook with URL {}:", phonebookUrl, e);
80         }
81     }
82
83     @Override
84     public String getName() {
85         return phonebookName;
86     }
87
88     @Override
89     public Optional<String> lookupNumber(String number, int matchCount) {
90         String normalized = normalizeNumber(number);
91         String matchString = matchCount > 0 && matchCount < normalized.length()
92                 ? normalized.substring(normalized.length() - matchCount)
93                 : normalized;
94         logger.trace("Normalized '{}' to '{}', matchString is '{}'", number, normalized, matchString);
95         return matchString.isBlank() ? Optional.empty()
96                 : phonebook.keySet().stream().filter(n -> n.endsWith(matchString)).findFirst().map(phonebook::get);
97     }
98
99     @Override
100     public String toString() {
101         return "Phonebook{" + "phonebookName='" + phonebookName + "', phonebook=" + phonebook + '}';
102     }
103
104     private String normalizeNumber(String number) {
105         // Naive normalization: remove all non-digit characters
106         return number.replaceAll("[^0-9]\\+\\*", "");
107     }
108 }