2 * Copyright © 2010 Anthony Towns <aj@erisian.com.au>
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.
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.
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.
21 import javax.imageio.ImageIO;
22 import java.awt.image.*;
25 import java.net.URLConnection;
27 public class AltosSiteMapCache extends JLabel {
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.
32 public static boolean fetchMap(File file, String url) {
34 long startTime = System.nanoTime();
38 } catch (java.net.MalformedURLException e) {
44 URLConnection uc = u.openConnection();
45 int contentLength = uc.getContentLength();
46 InputStream in = new BufferedInputStream(uc.getInputStream());
49 data = new byte[contentLength];
50 while (offset < contentLength) {
51 bytesRead = in.read(data, offset, data.length - offset);
58 if (offset != contentLength) {
61 } catch (IOException e) {
66 FileOutputStream out = new FileOutputStream(file);
70 } catch (FileNotFoundException e) {
72 } catch (IOException e) {
79 long duration_ms = (System.nanoTime() - startTime) / 1000000;
80 if (duration_ms < google_maps_ratelimit_ms) {
82 Thread.sleep(google_maps_ratelimit_ms - duration_ms);
83 } catch (InterruptedException e) {
84 Thread.currentThread().interrupt();
91 public static ImageIcon fetchAndLoadMap(File pngfile, String url) {
92 if (!pngfile.exists()) {
93 if (!fetchMap(pngfile, url)) {
97 return loadMap(pngfile, url);
100 public static ImageIcon loadMap(File pngfile, String url) {
101 if (!pngfile.exists()) {
108 img = ImageIO.read(pngfile);
110 System.out.printf("# Can't read pngfile %s\n", pngfile);
113 return new ImageIcon(img);
114 } catch (IOException e) {
115 System.out.printf("# IO error trying to load %s\n", pngfile);