6e6046bc7f3f31d071f956f48eb5ac1298a1e7b0
[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         public static int fetch_map(File file, String url) {
49                 if (file.exists())
50                         return success;
51
52                 if (forbidden_set && (System.nanoTime() - forbidden_time) < forbidden_interval)
53                         return forbidden;
54
55                 synchronized (fetch_lock) {
56                         URL u;
57                         long startTime = System.nanoTime();
58
59                         try {
60                                 u = new URL(url);
61                         } catch (java.net.MalformedURLException e) {
62                                 return bad_request;
63                         }
64
65                         byte[] data;
66                         URLConnection uc = null;
67                         try {
68                                 uc = u.openConnection();
69                                 String type = uc.getContentType();
70                                 int contentLength = uc.getContentLength();
71                                 if (uc instanceof HttpURLConnection) {
72                                         int response = ((HttpURLConnection) uc).getResponseCode();
73                                         switch (response) {
74                                         case HttpURLConnection.HTTP_FORBIDDEN:
75                                         case HttpURLConnection.HTTP_PAYMENT_REQUIRED:
76                                         case HttpURLConnection.HTTP_UNAUTHORIZED:
77                                                 forbidden_time = System.nanoTime();
78                                                 forbidden_set = true;
79                                                 return forbidden;
80                                         }
81                                 }
82                                 InputStream in = new BufferedInputStream(uc.getInputStream());
83                                 int bytesRead = 0;
84                                 int offset = 0;
85                                 data = new byte[contentLength];
86                                 while (offset < contentLength) {
87                                         bytesRead = in.read(data, offset, data.length - offset);
88                                         if (bytesRead == -1)
89                                                 break;
90                                         offset += bytesRead;
91                                 }
92                                 in.close();
93
94                                 if (offset != contentLength)
95                                         return failed;
96
97                         } catch (IOException e) {
98                                 return failed;
99                         }
100
101                         try {
102                                 FileOutputStream out = new FileOutputStream(file);
103                                 out.write(data);
104                                 out.flush();
105                                 out.close();
106                         } catch (FileNotFoundException e) {
107                                 return bad_request;
108                         } catch (IOException e) {
109                                 if (file.exists())
110                                         file.delete();
111                                 return bad_request;
112                         }
113
114                         long duration_ms = (System.nanoTime() - startTime) / 1000000;
115                         if (duration_ms < google_maps_ratelimit_ms) {
116                                 try {
117                                         Thread.sleep(google_maps_ratelimit_ms - duration_ms);
118                                 } catch (InterruptedException e) {
119                                         Thread.currentThread().interrupt();
120                                 }
121                         }
122                         return success;
123                 }
124         }
125
126         static final int                min_cache_size = 9;
127         static final int                max_cache_size = 24;
128
129         static int                      cache_size = min_cache_size;
130
131         static AltosSiteMapImage[]      images = new AltosSiteMapImage[cache_size];
132
133         static Object cache_lock = new Object();
134
135         public  static void set_cache_size(int new_size) {
136                 if (new_size < min_cache_size)
137                         new_size = min_cache_size;
138                 if (new_size > max_cache_size)
139                         new_size = max_cache_size;
140                 if (new_size == cache_size)
141                         return;
142
143                 synchronized(cache_lock) {
144                         AltosSiteMapImage[]     new_images = new AltosSiteMapImage[new_size];
145
146                         for (int i = 0; i < cache_size; i++) {
147                                 if (i < new_size)
148                                         new_images[i] = images[i];
149                                 else
150                                         images[i].flush();
151                         }
152                         images = new_images;
153                         cache_size = new_size;
154                 }
155         }
156
157         static long                     used;
158
159         private static Point tile_loc(AltosSiteMapTile tile) {
160                 Rectangle       r = tile.getBounds();
161                 int             x = r.x / 512;
162                 int             y = r.y / 512;
163
164                 return new Point (x, y);
165         }
166
167         private static void dump_cache() {
168                 int     min_x = 1000, max_x = -1000, min_y = 1000, max_y = -1000;
169
170                 for (int i = 0; i < cache_size; i++) {
171                         AltosSiteMapImage       image = images[i];
172                         if (image != null) {
173                                 Point p = tile_loc(image.tile);
174                                 min_x = min_x < p.x ? min_x : p.x;
175                                 max_x = max_x > p.x ? max_x : p.x;
176                                 min_y = min_y < p.y ? min_y : p.y;
177                                 max_y = max_y > p.y ? max_y : p.y;
178                                 System.out.printf ("entry %d %d,%d used %d\n", i, p.x, p.y, image.used);
179                         } else {
180                                 System.out.printf ("entry %d empty\n", i);
181                         }
182                 }
183
184                 int[][] map = new int[max_x - min_x + 1][max_y - min_y + 1];
185                 for (int i = 0; i < cache_size; i++) {
186                         AltosSiteMapImage       image = images[i];
187                         if (image != null) {
188                                 Point p = tile_loc(image.tile);
189                                 map[p.x - min_x][p.y - min_y]++;
190                         }
191                 }
192
193                 for (int y = min_y; y <= max_y; y++) {
194                         for (int x = min_x; x <= max_x; x++)
195                                 System.out.printf (" %2d", map[x - min_x][y - min_y]);
196                         System.out.printf("\n");
197                 }
198         }
199
200         public static AltosSiteMapImage get_image(AltosSiteMapTile tile, File file, int width, int height) {
201                 int             oldest = -1;
202                 long            age = used;
203
204                 synchronized(cache_lock) {
205                         AltosSiteMapImage       image = null;
206                         for (int i = 0; i < cache_size; i++) {
207                                 image = images[i];
208
209                                 if (image == null) {
210                                         oldest = i;
211                                         break;
212                                 }
213                                 if (image.tile == tile && file.equals(image.file)) {
214                                         image.used = used++;
215                                         return image;
216                                 }
217                                 if (image.used < age) {
218                                         oldest = i;
219                                         age = image.used;
220                                 }
221                         }
222
223                         try {
224                                 image = new AltosSiteMapImage(tile, file, width, height);
225                                 image.used = used++;
226                                 if (images[oldest] != null) {
227 //                                      dump_cache();
228                                         AltosSiteMap.debug_component(images[oldest].tile, "replacing cache");
229                                         AltosSiteMap.debug_component(tile, "replaced cache");
230                                         images[oldest].flush();
231                                 }
232                                 images[oldest] = image;
233                                 return image;
234                         } catch (IOException e) {
235                                 return null;
236                         }
237                 }
238         }
239 }