7f436ef0729b595da087f7c706098dd854fc4eca
[fw/altos] / altosuilib / AltosSiteMapCache.java
1 /*
2  * Copyright © 2010 Anthony Towns <aj@erisian.com.au>
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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.altosuilib_2;
19
20 import javax.swing.*;
21 import javax.imageio.ImageIO;
22 import java.awt.image.*;
23 import java.awt.*;
24 import java.io.*;
25 import java.net.*;
26
27 public class AltosSiteMapCache {
28         static final long google_maps_ratelimit_ms = 1200;
29         // Google limits static map queries to 50 per minute per IP, so
30         // each query should take at least 1.2 seconds.
31
32         static final int        success = 0;
33         static final int        loading = 1;
34         static final int        failed = 2;
35         static final int        bad_request = 3;
36         static final int        forbidden = 4;
37
38         public static boolean has_map(File file, String url) {
39                 return file.exists();
40         }
41
42         static long     forbidden_time;
43         static boolean  forbidden_set = false;
44         static final long       forbidden_interval = 60l * 1000l * 1000l * 1000l;
45
46         static private Object fetch_lock = new Object();
47
48         private static int fetch_one(File file, String url) {
49                 URL u;
50
51                 try {
52                         u = new URL(url);
53                 } catch (java.net.MalformedURLException e) {
54                         return bad_request;
55                 }
56
57                 byte[] data;
58                 URLConnection uc = null;
59                 try {
60                         uc = u.openConnection();
61                         String type = uc.getContentType();
62                         int contentLength = uc.getContentLength();
63                         if (uc instanceof HttpURLConnection) {
64                                 int response = ((HttpURLConnection) uc).getResponseCode();
65                                 switch (response) {
66                                 case HttpURLConnection.HTTP_FORBIDDEN:
67                                 case HttpURLConnection.HTTP_PAYMENT_REQUIRED:
68                                 case HttpURLConnection.HTTP_UNAUTHORIZED:
69                                         forbidden_time = System.nanoTime();
70                                         forbidden_set = true;
71                                         return forbidden;
72                                 }
73                         }
74                         InputStream in = new BufferedInputStream(uc.getInputStream());
75                         int bytesRead = 0;
76                         int offset = 0;
77                         data = new byte[contentLength];
78                         while (offset < contentLength) {
79                                 bytesRead = in.read(data, offset, data.length - offset);
80                                 if (bytesRead == -1)
81                                         break;
82                                 offset += bytesRead;
83                         }
84                         in.close();
85
86                         if (offset != contentLength)
87                                 return failed;
88
89                 } catch (IOException e) {
90                         return failed;
91                 }
92
93                 try {
94                         FileOutputStream out = new FileOutputStream(file);
95                         out.write(data);
96                         out.flush();
97                         out.close();
98                 } catch (FileNotFoundException e) {
99                         return bad_request;
100                 } catch (IOException e) {
101                         if (file.exists())
102                                 file.delete();
103                         return bad_request;
104                 }
105                 return success;
106         }
107
108         public static int fetch_map(File file, String url) {
109                 if (file.exists())
110                         return success;
111
112                 if (forbidden_set && (System.nanoTime() - forbidden_time) < forbidden_interval)
113                         return forbidden;
114
115                 int     status = bad_request;
116
117                 if (!AltosUIVersion.has_google_maps_api_key()) {
118                         synchronized (fetch_lock) {
119                                 long startTime = System.nanoTime();
120                                 status = fetch_one(file, url);
121                                 if (status == success) {
122                                         long duration_ms = (System.nanoTime() - startTime) / 1000000;
123                                         if (duration_ms < google_maps_ratelimit_ms) {
124                                                 try {
125                                                         Thread.sleep(google_maps_ratelimit_ms - duration_ms);
126                                                 } catch (InterruptedException e) {
127                                                         Thread.currentThread().interrupt();
128                                                 }
129                                         }
130                                 }
131                         }
132                 } else {
133                         status = fetch_one(file, url);
134                 }
135                 return status;
136         }
137
138         static final int                min_cache_size = 9;
139         static final int                max_cache_size = 24;
140
141         static int                      cache_size = min_cache_size;
142
143         static AltosSiteMapImage[]      images = new AltosSiteMapImage[cache_size];
144
145         static Object cache_lock = new Object();
146
147         public  static void set_cache_size(int new_size) {
148                 if (new_size < min_cache_size)
149                         new_size = min_cache_size;
150                 if (new_size > max_cache_size)
151                         new_size = max_cache_size;
152                 if (new_size == cache_size)
153                         return;
154
155                 synchronized(cache_lock) {
156                         AltosSiteMapImage[]     new_images = new AltosSiteMapImage[new_size];
157
158                         for (int i = 0; i < cache_size; i++) {
159                                 if (i < new_size)
160                                         new_images[i] = images[i];
161                                 else
162                                         images[i].flush();
163                         }
164                         images = new_images;
165                         cache_size = new_size;
166                 }
167         }
168
169         static long                     used;
170
171         private static Point tile_loc(AltosSiteMapTile tile) {
172                 Rectangle       r = tile.getBounds();
173                 int             x = r.x / 512;
174                 int             y = r.y / 512;
175
176                 return new Point (x, y);
177         }
178
179         private static void dump_cache() {
180                 int     min_x = 1000, max_x = -1000, min_y = 1000, max_y = -1000;
181
182                 for (int i = 0; i < cache_size; i++) {
183                         AltosSiteMapImage       image = images[i];
184                         if (image != null) {
185                                 Point p = tile_loc(image.tile);
186                                 min_x = min_x < p.x ? min_x : p.x;
187                                 max_x = max_x > p.x ? max_x : p.x;
188                                 min_y = min_y < p.y ? min_y : p.y;
189                                 max_y = max_y > p.y ? max_y : p.y;
190                                 System.out.printf ("entry %d %d,%d used %d\n", i, p.x, p.y, image.used);
191                         } else {
192                                 System.out.printf ("entry %d empty\n", i);
193                         }
194                 }
195
196                 int[][] map = new int[max_x - min_x + 1][max_y - min_y + 1];
197                 for (int i = 0; i < cache_size; i++) {
198                         AltosSiteMapImage       image = images[i];
199                         if (image != null) {
200                                 Point p = tile_loc(image.tile);
201                                 map[p.x - min_x][p.y - min_y]++;
202                         }
203                 }
204
205                 for (int y = min_y; y <= max_y; y++) {
206                         for (int x = min_x; x <= max_x; x++)
207                                 System.out.printf (" %2d", map[x - min_x][y - min_y]);
208                         System.out.printf("\n");
209                 }
210         }
211
212         public static AltosSiteMapImage get_image(AltosSiteMapTile tile, File file, int width, int height) {
213                 int             oldest = -1;
214                 long            age = used;
215
216                 synchronized(cache_lock) {
217                         AltosSiteMapImage       image = null;
218                         for (int i = 0; i < cache_size; i++) {
219                                 image = images[i];
220
221                                 if (image == null) {
222                                         oldest = i;
223                                         break;
224                                 }
225                                 if (image.tile == tile && file.equals(image.file)) {
226                                         image.used = used++;
227                                         return image;
228                                 }
229                                 if (image.used < age) {
230                                         oldest = i;
231                                         age = image.used;
232                                 }
233                         }
234
235                         try {
236                                 image = new AltosSiteMapImage(tile, file, width, height);
237                                 image.used = used++;
238                                 if (images[oldest] != null) {
239 //                                      dump_cache();
240                                         AltosSiteMap.debug_component(images[oldest].tile, "replacing cache");
241                                         AltosSiteMap.debug_component(tile, "replaced cache");
242                                         images[oldest].flush();
243                                 }
244                                 images[oldest] = image;
245                                 return image;
246                         } catch (IOException e) {
247                                 return null;
248                         }
249                 }
250         }
251 }