source: josm/trunk/src/org/openstreetmap/josm/io/imagery/ApiKeyProvider.java

Last change on this file was 15868, checked in by Don-vip, 5 years ago

see #18440 - cache API keys in memory

File size: 1.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.imagery;
3
4import java.io.IOException;
5import java.net.HttpURLConnection;
6import java.net.URL;
7import java.util.Collections;
8import java.util.HashMap;
9import java.util.List;
10import java.util.Map;
11
12import org.openstreetmap.josm.data.Preferences;
13import org.openstreetmap.josm.spi.preferences.Config;
14import org.openstreetmap.josm.tools.HttpClient;
15import org.openstreetmap.josm.tools.HttpClient.Response;
16import org.openstreetmap.josm.tools.Utils;
17
18/**
19 * Provider of confidential imagery API keys.
20 * @since 15855
21 */
22public final class ApiKeyProvider {
23
24 private static final Map<String, String> CACHE = new HashMap<>();
25
26 private ApiKeyProvider() {
27 // Hide public constructor
28 }
29
30 private static List<String> getApiKeySites() {
31 return Preferences.main().getList("apikey.sites",
32 Collections.singletonList(Config.getUrls().getJOSMWebsite()+"/mapkey/"));
33 }
34
35 /**
36 * Retrieves the API key for the given imagery id.
37 * @param imageryId imagery id
38 * @return the API key for the given imagery id
39 * @throws IOException in case of I/O error
40 */
41 public static String retrieveApiKey(String imageryId) throws IOException {
42 if (CACHE.containsKey(imageryId)) {
43 return CACHE.get(imageryId);
44 }
45 for (String siteUrl : getApiKeySites()) {
46 Response response = HttpClient.create(new URL(siteUrl + imageryId)).connect();
47 try {
48 if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
49 String key = Utils.strip(response.fetchContent());
50 CACHE.put(imageryId, key);
51 return key;
52 }
53 } finally {
54 response.disconnect();
55 }
56 }
57 return null;
58 }
59}
Note: See TracBrowser for help on using the repository browser.