Changeset 1879 in josm for trunk/src


Ignore:
Timestamp:
2009-08-02T14:36:40+02:00 (15 years ago)
Author:
Gubaer
Message:

towards a fix for #3142: JOSM applet class no longer functional

Location:
trunk/src/org/openstreetmap/josm
Files:
1 added
2 deleted
14 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/actions/AboutAction.java

    r1802 r1879  
    5858        URL u = Main.class.getResource("/REVISION");
    5959        if(u == null) {
    60             try {
    61                 manifest = true;
    62                 u = new URL("jar:" + Main.class.getProtectionDomain().getCodeSource().getLocation().toString()
    63                         + "!/META-INF/MANIFEST.MF");
    64             } catch (MalformedURLException e) {
    65                 e.printStackTrace();
    66             }
     60            //            try {
     61            manifest = true;
     62            //                u = new URL("jar:" + Main.class.getProtectionDomain().getCodeSource().getLocation().toString()
     63            //                        + "!/META-INF/MANIFEST.MF");
     64            u = Main.class.getResource("/META-INF/MANIFEST.MF");
     65            //            } catch (MalformedURLException e) {
     66            //                e.printStackTrace();
     67            //            }
    6768        }
    6869        revision = loadFile(u, manifest);
     
    155156
    156157        JOptionPane.showMessageDialog(Main.parent, about, tr("About JOSM..."),
    157         JOptionPane.INFORMATION_MESSAGE, ImageProvider.get("logo"));
     158                JOptionPane.INFORMATION_MESSAGE, ImageProvider.get("logo"));
    158159    }
    159160
     
    194195        area.setEditable(false);
    195196        Font font = Font.getFont("monospaced");
    196         if (font != null)
     197        if (font != null) {
    197198            area.setFont(font);
     199        }
    198200        if (resource == null)
    199201            return area;
     
    202204            in = new BufferedReader(new InputStreamReader(resource.openStream()));
    203205            String s = "";
    204             for (String line = in.readLine(); line != null; line = in.readLine())
     206            for (String line = in.readLine(); line != null; line = in.readLine()) {
    205207                s += line + "\n";
     208            }
    206209            if (manifest) {
    207210                s = Pattern.compile("\n ", Pattern.DOTALL).matcher(s).replaceAll("");
  • trunk/src/org/openstreetmap/josm/actions/DiskAccessAction.java

    r1808 r1879  
    106106        return file;
    107107    }
    108 
    109108}
  • trunk/src/org/openstreetmap/josm/actions/OpenFileAction.java

    r1847 r1879  
    6565    }
    6666
     67    @Override
     68    protected void updateEnabledState() {
     69        setEnabled(! Main.applet);
     70    }
    6771}
  • trunk/src/org/openstreetmap/josm/actions/SaveActionBase.java

    r1857 r1879  
    320320    @Override
    321321    protected void updateEnabledState() {
     322        if (Main.applet) {
     323            setEnabled(false);
     324            return;
     325        }
    322326        boolean check =  Main.map != null
    323327        && Main.map.mapView !=null
  • trunk/src/org/openstreetmap/josm/actions/SaveAsAction.java

    r1808 r1879  
    77import java.io.File;
    88
     9import org.openstreetmap.josm.Main;
    910import org.openstreetmap.josm.gui.layer.Layer;
    1011import org.openstreetmap.josm.tools.Shortcut;
  • trunk/src/org/openstreetmap/josm/actions/downloadtasks/DownloadOsmTask.java

    r1869 r1879  
    77import java.util.Collection;
    88import java.util.concurrent.Future;
     9import java.util.logging.Logger;
    910
    1011import javax.swing.JCheckBox;
     
    1617import org.openstreetmap.josm.data.osm.DataSet;
    1718import org.openstreetmap.josm.data.osm.DataSource;
     19import org.openstreetmap.josm.gui.ExceptionDialogUtil;
    1820import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    1921import org.openstreetmap.josm.gui.download.DownloadDialog.DownloadTask;
     
    3436 */
    3537public class DownloadOsmTask implements DownloadTask {
     38    private static final Logger logger = Logger.getLogger(DownloadOsmTask.class.getName());
     39
    3640    private static Bounds currentBounds;
    3741    private Future<Task> task = null;
     
    4246        private DataSet dataSet;
    4347        private boolean newLayer;
     48        private boolean cancelled;
     49        private Exception lastException;
    4450
    4551        public Task(boolean newLayer, OsmServerReader reader, ProgressMonitor progressMonitor) {
     
    5056
    5157        @Override public void realRun() throws IOException, SAXException, OsmTransferException {
    52             dataSet = reader.parseOsm(progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
     58            try {
     59                dataSet = reader.parseOsm(progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
     60            } catch(Exception e) {
     61                if (cancelled) {
     62                    logger.warning(tr("Ignoring exception because download has been cancelled. Exception was: {0}" + e.toString()));
     63                    return;
     64                }
     65                if (e instanceof OsmTransferException) {
     66                    lastException = e;
     67                } else {
     68                    lastException = new OsmTransferException(e);
     69                }
     70            }
    5371        }
    5472
     
    84102
    85103        @Override protected void finish() {
     104            if (cancelled)
     105                return;
     106            if (lastException != null) {
     107                ExceptionDialogUtil.explainException(lastException);
     108                return;
     109            }
    86110            if (dataSet == null)
    87111                return; // user canceled download or error occurred
  • trunk/src/org/openstreetmap/josm/data/ServerSidePreferences.java

    r1865 r1879  
    2020import java.util.StringTokenizer;
    2121import java.util.Map.Entry;
     22import java.util.logging.Logger;
    2223
    2324import javax.swing.JOptionPane;
     
    3738 */
    3839public class ServerSidePreferences extends Preferences {
     40    static private final Logger logger = Logger.getLogger(ServerSidePreferences.class.getName());
    3941
    4042    private final Connection connection;
     
    181183
    182184    @Override public Collection<Bookmark> loadBookmarks() {
     185        URL url = null;
    183186        try {
    184187            Collection<Bookmark> bookmarks;
    185             BufferedReader in = new BufferedReader(new InputStreamReader(new URL("http://"+connection.serverUrl.getHost()+"/josm/bookmarks").openStream()));
    186188            bookmarks = new LinkedList<Bookmark>();
     189            url = new URL("http://"+connection.serverUrl.getHost()+"/josm/bookmarks");
     190            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
     191
    187192            for (String line = in.readLine(); line != null; line = in.readLine()) {
    188193                StringTokenizer st = new StringTokenizer(line, ",");
     
    209214        } catch (IOException e) {
    210215            e.printStackTrace();
     216        } catch(SecurityException e) {
     217            e.printStackTrace();
     218            logger.warning(tr("Failed to load bookmarks from ''{0}'' for security reasons. Exception was: {1}",  url == null ? "null" : url.toExternalForm(), e.toString()));
    211219        }
    212220        return Collections.emptyList();
  • trunk/src/org/openstreetmap/josm/gui/GettingStarted.java

    r1755 r1879  
    55import static org.openstreetmap.josm.tools.I18n.tr;
    66
    7 import java.io.IOException;
    8 import java.util.ArrayList;
    9 import java.util.concurrent.Executors;
    10 import java.util.concurrent.ExecutorService;
    11 import java.util.concurrent.Callable;
    12 import java.util.concurrent.Future;
    13 import java.util.regex.Matcher;
    14 import java.util.regex.Pattern;
    15 
    167import java.awt.BorderLayout;
    178import java.awt.EventQueue;
    189
    19 import javax.swing.JScrollPane;
    2010import javax.swing.JEditorPane;
    2111import javax.swing.JPanel;
     12import javax.swing.JScrollPane;
     13import javax.swing.border.EmptyBorder;
    2214import javax.swing.event.HyperlinkEvent;
    2315import javax.swing.event.HyperlinkListener;
    24 import javax.swing.border.EmptyBorder;
    2516
    2617import org.openstreetmap.josm.Main;
     18import org.openstreetmap.josm.actions.AboutAction;
    2719import org.openstreetmap.josm.io.CacheCustomContent;
    2820import org.openstreetmap.josm.tools.LanguageInfo;
    2921import org.openstreetmap.josm.tools.OpenBrowser;
    3022import org.openstreetmap.josm.tools.WikiReader;
    31 import org.openstreetmap.josm.actions.AboutAction;
    3223
    3324public class GettingStarted extends JPanel {
    3425    private String content = "";
    35     static private String styles = "<style type=\"text/css\">\n"+
    36             "body { font-family: sans-serif; font-weight: bold; }\n"+
    37             "h1 {text-align: center;}\n"+
    38             "</style>\n";
     26    static private String styles = "<style type=\"text/css\">\n"
     27        + "body { font-family: sans-serif; font-weight: bold; }\n" + "h1 {text-align: center;}\n" + "</style>\n";
    3928
    4029    public class LinkGeneral extends JEditorPane implements HyperlinkListener {
     
    4635            addHyperlinkListener(this);
    4736        }
     37
    4838        public void hyperlinkUpdate(HyperlinkEvent e) {
    4939            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
     
    5646     * Grabs current MOTD from cache or webpage and parses it.
    5747     */
    58     private class assignContent extends CacheCustomContent {
    59         public assignContent() {
     48    private class MotdContent extends CacheCustomContent {
     49        public MotdContent() {
    6050            super("motd.html", CacheCustomContent.INTERVAL_DAILY);
    6151        }
     
    6858         * @see org.openstreetmap.josm.io.CacheCustomContent#updateData()
    6959         */
     60        @Override
    7061        protected byte[] updateData() {
    7162            String motd = new WikiReader().readLang("StartupPage");
    72             if(motd.length() == 0)
    73             {
    74                 motd = "<html>" + styles + "<body><h1>" +
    75                 "JOSM - " + tr("Java OpenStreetMap Editor") +
    76                 "</h1>\n<h2 align=\"center\">(" +
    77                 tr("Message of the day not available") +
    78                 ")</h2></html>";
    79             }
    80             else
    81             {
    82                 motd = motd.replace("<!-- VERSION -->", tr("- running version is {0}",
    83                 AboutAction.getVersionString()));
     63            if (motd.length() == 0) {
     64                motd = "<html>" + styles + "<body><h1>" + "JOSM - " + tr("Java OpenStreetMap Editor")
     65                + "</h1>\n<h2 align=\"center\">(" + tr("Message of the day not available") + ")</h2></html>";
     66            } else {
     67                motd = motd.replace("<!-- VERSION -->", tr("- running version is {0}", AboutAction.getVersionString()));
    8468            }
    8569            // Save this to prefs in case JOSM is updated so MOTD can be refreshed
     
    9882            // 1. Not yet written - but so isn't the interval variable, so it gets updated anyway
    9983            // 2. Cannot be written (e.g. while developing). Obviously we don't want to update
    100             //    everytime because of something we can't read.
     84            // everytime because of something we can't read.
    10185            return (Main.pref.getInteger("cache.motd.html.version", -999) == myVersion)
    10286            && Main.pref.get("cache.motd.html.lang").equals(myLang);
     
    10589
    10690    /**
    107      * Initializes getting the MOTD as well as enabling the FileDrop Listener.
    108      * Displays a message while the MOTD is downloading.
     91     * Initializes getting the MOTD as well as enabling the FileDrop Listener. Displays a message
     92     * while the MOTD is downloading.
    10993     */
    11094    public GettingStarted() {
    11195        super(new BorderLayout());
    112         final LinkGeneral lg = new LinkGeneral(
    113             "<html>" +
    114             styles +
    115             "<h1>" +
    116             "JOSM - " +
    117             tr("Java OpenStreetMap Editor") +
    118             "</h1><h2 align=\"center\">" +
    119             tr("Downloading \"Message of the day\"") +
    120             "</h2>");
     96        final LinkGeneral lg = new LinkGeneral("<html>" + styles + "<h1>" + "JOSM - " + tr("Java OpenStreetMap Editor")
     97                + "</h1><h2 align=\"center\">" + tr("Downloading \"Message of the day\"") + "</h2>");
    12198        JScrollPane scroller = new JScrollPane(lg);
    122         scroller.setViewportBorder(new EmptyBorder(10,100,10,100));
     99        scroller.setViewportBorder(new EmptyBorder(10, 100, 10, 100));
    123100        add(scroller, BorderLayout.CENTER);
    124101
     
    126103        Thread t = new Thread(new Runnable() {
    127104            public void run() {
    128                 if (content.length() == 0 && Main.pref.getBoolean("help.displaymotd", true))
    129                     content = new assignContent().updateIfRequiredString();
     105                if (content.length() == 0 && Main.pref.getBoolean("help.displaymotd", true)) {
     106                    content = new MotdContent().updateIfRequiredString();
     107                }
    130108
    131109                EventQueue.invokeLater(new Runnable() {
    132110                    public void run() {
    133                        lg.setText(content);
    134                        //lg.moveCaretPosition(0);
     111                        lg.setText(content);
     112                        // lg.moveCaretPosition(0);
    135113                    }
    136114                });
  • trunk/src/org/openstreetmap/josm/gui/download/SlippyMapChooser.java

    r1761 r1879  
    6666    public SlippyMapChooser() {
    6767        super();
    68         cachedLoader = new OsmFileCacheTileLoader(this);
     68        try {
     69            cachedLoader = new OsmFileCacheTileLoader(this);
     70        } catch(SecurityException e) {
     71            // set to null if a SecurityException was thrown
     72            // while creating the cachedLoader
     73            //
     74            cachedLoader = null;
     75        }
    6976        uncachedLoader = new OsmTileLoader(this);
    7077        setZoomContolsVisible(false);
     
    7481        // the area before the component has been displayed the first time
    7582        setBounds(new Rectangle(getMinimumSize()));
    76         setFileCacheEnabled(Main.pref.getBoolean("slippy_map_chooser.file_cache", true));
     83        if (cachedLoader == null) {
     84            setFileCacheEnabled(false);
     85        } else {
     86            setFileCacheEnabled(Main.pref.getBoolean("slippy_map_chooser.file_cache", true));
     87        }
    7788        setMaxTilesInMemory(Main.pref.getInteger("slippy_map_chooser.max_tiles", 1000));
    7889
  • trunk/src/org/openstreetmap/josm/io/BoundingBoxDownloader.java

    r1835 r1879  
    9999    public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
    100100        progressMonitor.beginTask(tr("Contacting OSM Server..."), 10);
     101        InputStream in = null;
    101102        try {
    102103            progressMonitor.indeterminateSubTask(null);
    103             final InputStream in = getInputStream("map?bbox="+lon1+","+lat1+","+lon2+","+lat2, progressMonitor.createSubTaskMonitor(9, false));
     104            in = getInputStream("map?bbox="+lon1+","+lat1+","+lon2+","+lat2, progressMonitor.createSubTaskMonitor(9, false));
    104105            if (in == null)
    105106                return null;
    106             final DataSet data = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
    107             in.close();
    108             activeConnection = null;
    109             return data;
    110         } catch (IOException e) {
    111             if (cancel)
    112                 return null;
    113             throw new OsmTransferException(e);
    114         } catch (SAXException e) {
    115             throw new OsmTransferException(e);
     107            return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
    116108        } catch(OsmTransferException e) {
    117109            throw e;
    118110        } catch (Exception e) {
    119             if (cancel)
    120                 return null;
    121111            throw new OsmTransferException(e);
    122112        } finally {
    123113            progressMonitor.finishTask();
     114            if (in != null) {
     115                try {in.close();} catch(IOException e) {}
     116            }
     117            activeConnection = null;
    124118        }
    125119    }
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r1870 r1879  
    2121import java.util.ArrayList;
    2222import java.util.Collection;
     23import java.util.Collections;
    2324import java.util.HashMap;
    2425import java.util.Properties;
     
    268269     * @throws OsmTransferException if something goes wrong
    269270     */
    270     public void deletePrimitive(OsmPrimitive osm) throws OsmTransferException {
     271    public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
    271272        initialize();
    272         // legacy mode does not require payload. normal mode (0.6 and up) requires payload for version matching.
    273         sendRequest("DELETE", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.id, version.equals("0.5") ? null : toXml(osm, false));
     273        // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
     274        // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
     275        // to diff upload.
     276        //
     277        uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
    274278    }
    275279
     
    400404        while(true) { // the retry loop
    401405            try {
    402                 URL url = new URL(new URL(getBaseUrl()), urlSuffix, new MyHttpHandler());
     406                URL url = new URL(new URL(getBaseUrl()), urlSuffix);
    403407                System.out.print(requestMethod + " " + url + "... ");
    404408                activeConnection = (HttpURLConnection)url.openConnection();
  • trunk/src/org/openstreetmap/josm/io/OsmServerWriter.java

    r1814 r1879  
    136136                                    NAME_FORMATTER.getName(osm),
    137137                                    osm.id));
    138                     makeApiRequest(osm);
     138                    makeApiRequest(osm,progressMonitor);
    139139                    processed.add(osm);
    140140                    progressMonitor.worked(1);
     
    148148    }
    149149
    150     void makeApiRequest(OsmPrimitive osm) throws OsmTransferException {
     150    void makeApiRequest(OsmPrimitive osm, ProgressMonitor progressMonitor) throws OsmTransferException {
    151151        if (osm.deleted) {
    152             api.deletePrimitive(osm);
     152            api.deletePrimitive(osm, progressMonitor);
    153153        } else if (osm.id == 0) {
    154154            api.createPrimitive(osm);
  • trunk/src/org/openstreetmap/josm/tools/ImageProvider.java

    r1814 r1879  
    4343     * @author imi
    4444     */
    45     public static enum OverlayPosition {NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST}
     45    public static enum OverlayPosition {
     46        NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST
     47    }
    4648
    4749    /**
     
    5153
    5254    /**
    53      * Add here all ClassLoader whose ressource should be searched.
    54      * Plugin's class loaders are added by main.
     55     * Add here all ClassLoader whose ressource should be searched. Plugin's class loaders are added
     56     * by main.
    5557     */
    5658    public static final List<ClassLoader> sources = new LinkedList<ClassLoader>();
     
    5860    /**
    5961     * Return an image from the specified location.
    60      *
    61      * @param subdir    The position of the directory, e.g. "layer"
    62      * @param name      The icons name (without the ending of ".png")
     62     * 
     63     * @param subdir The position of the directory, e.g. "layer"
     64     * @param name The icons name (without the ending of ".png")
    6365     * @return The requested Image.
    6466     */
     
    6769        if (icon == null) {
    6870            String ext = name.indexOf('.') != -1 ? "" : ".png";
    69             throw new NullPointerException("/images/"+subdir+"/"+name+ext+" not found");
     71            throw new NullPointerException("/images/" + subdir + "/" + name + ext + " not found");
    7072        }
    7173        return icon;
    7274    }
    7375
    74     public static ImageIcon getIfAvailable(String subdir, String name)
    75     {
    76         return getIfAvailable((Collection<String>)null, null, subdir, name);
    77     }
    78     public static final ImageIcon getIfAvailable(String[] dirs, String id, String subdir, String name)
    79     {
     76    public static ImageIcon getIfAvailable(String subdir, String name) {
     77        return getIfAvailable((Collection<String>) null, null, subdir, name);
     78    }
     79
     80    public static final ImageIcon getIfAvailable(String[] dirs, String id, String subdir, String name) {
    8081        return getIfAvailable(Arrays.asList(dirs), id, subdir, name);
    8182    }
    8283
    8384    /**
    84      * Like {@link #get(String)}, but does not throw and return <code>null</code>
    85      * in case of nothing is found. Use this, if the image to retrieve is optional.
    86      */
    87     public static ImageIcon getIfAvailable(Collection<String> dirs, String id, String subdir, String name)
    88     {
     85     * Like {@link #get(String)}, but does not throw and return <code>null</code> in case of nothing
     86     * is found. Use this, if the image to retrieve is optional.
     87     */
     88    public static ImageIcon getIfAvailable(Collection<String> dirs, String id, String subdir, String name) {
    8989        if (name == null)
    9090            return null;
    91         if (name.startsWith("http://"))
    92         {
     91        if (name.startsWith("http://")) {
    9392            Image img = cache.get(name);
    94             if(img == null)
    95             {
    96                 try
    97                 {
    98                     MirroredInputStream is = new MirroredInputStream(name,
    99                             new File(Main.pref.getPreferencesDir(), "images").toString());
    100                     if(is != null)
    101                     {
     93            if (img == null) {
     94                try {
     95                    MirroredInputStream is = new MirroredInputStream(name, new File(Main.pref.getPreferencesDir(),
     96                    "images").toString());
     97                    if (is != null) {
    10298                        img = Toolkit.getDefaultToolkit().createImage(is.getFile().toURI().toURL());
    10399                        cache.put(name, img);
    104100                    }
    105                 }
    106                 catch(IOException e) {
     101                } catch (IOException e) {
    107102                }
    108103            }
     
    115110        }
    116111        String ext = name.indexOf('.') != -1 ? "" : ".png";
    117         String full_name = subdir+name+ext;
     112        String full_name = subdir + name + ext;
    118113        String cache_name = full_name;
    119114        /* cache separately */
    120         if(dirs != null && dirs.size() > 0) {
    121             cache_name = "id:"+id+":"+full_name;
     115        if (dirs != null && dirs.size() > 0) {
     116            cache_name = "id:" + id + ":" + full_name;
    122117        }
    123118
     
    125120        if (img == null) {
    126121            // getImageUrl() does a ton of "stat()" calls and gets expensive
    127             // and redundant when you have a whole ton of objects.  So,
     122            // and redundant when you have a whole ton of objects. So,
    128123            // index the cache by the name of the icon we're looking for
    129124            // and don't bother to create a URL unless we're actually
     
    139134    }
    140135
    141     private static URL getImageUrl(String path, String name)
    142     {
    143         if(path.startsWith("resource://"))
    144         {
     136    private static URL getImageUrl(String path, String name) {
     137        if (path.startsWith("resource://")) {
    145138            String p = path.substring("resource://".length());
    146             for (ClassLoader source : sources)
    147             {
     139            for (ClassLoader source : sources) {
    148140                URL res;
    149                 if ((res = source.getResource(p+name)) != null)
     141                if ((res = source.getResource(p + name)) != null)
    150142                    return res;
    151143            }
    152         }
    153         else
    154         {
     144        } else {
    155145            try {
    156146                File f = new File(path, name);
    157                 if(f.exists())
     147                if (f.exists())
    158148                    return f.toURI().toURL();
    159             } catch (MalformedURLException e) {}
     149            } catch (MalformedURLException e) {
     150            }
    160151        }
    161152        return null;
    162153    }
    163154
    164     private static URL getImageUrl(String imageName, Collection<String> dirs)
    165     {
    166         URL u;
     155    private static URL getImageUrl(String imageName, Collection<String> dirs) {
     156        URL u = null;
     157
    167158        // Try passed directories first
    168         if(dirs != null)
    169         {
    170             for (String name : dirs)
    171             {
    172                 u = getImageUrl(name, imageName);
    173                 if(u != null) return u;
     159        if (dirs != null) {
     160            for (String name : dirs) {
     161                try {
     162                    u = getImageUrl(name, imageName);
     163                    if (u != null)
     164                        return u;
     165                } catch (SecurityException e) {
     166                    System.out.println(tr(
     167                            "Warning: failed to acccess directory ''{0}'' for security reasons. Exception was: {1}",
     168                            name, e.toString()));
     169                }
     170
    174171            }
    175172        }
    176173        // Try user-preference directory
    177         u = getImageUrl(Main.pref.getPreferencesDir()+"images", imageName);
    178         if(u != null) return u;
     174        String dir = Main.pref.getPreferencesDir() + "images";
     175        try {
     176            u = getImageUrl(dir, imageName);
     177            if (u != null)
     178                return u;
     179        } catch (SecurityException e) {
     180            System.out.println(tr(
     181                    "Warning: failed to acccess directory ''{0}'' for security reasons. Exception was: {1}", dir, e
     182                    .toString()));
     183        }
    179184
    180185        // Try plugins and josm classloader
    181186        u = getImageUrl("resource://images/", imageName);
    182         if(u != null) return u;
     187        if (u != null)
     188            return u;
    183189
    184190        // Try all other ressource directories
    185         for (String location : Main.pref.getAllPossiblePreferenceDirs())
    186         {
    187             u = getImageUrl(location+"images", imageName);
    188             if(u != null) return u;
     191        for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
     192            u = getImageUrl(location + "images", imageName);
     193            if (u != null)
     194                return u;
    189195            u = getImageUrl(location, imageName);
    190             if(u != null) return u;
    191         }
     196            if (u != null)
     197                return u;
     198        }
     199        System.out
     200        .println(tr(
     201                "Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.",
     202                imageName));
    192203        return null;
    193204    }
     
    201212
    202213    public static Cursor getCursor(String name, String overlay) {
    203         ImageIcon img = get("cursor",name);
     214        ImageIcon img = get("cursor", name);
    204215        if (overlay != null) {
    205             img = overlay(img, "cursor/modifier/"+overlay, OverlayPosition.SOUTHEAST);
     216            img = overlay(img, "cursor/modifier/" + overlay, OverlayPosition.SOUTHEAST);
    206217        }
    207218        Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
    208                 name.equals("crosshair") ? new Point(10,10) : new Point(3,2), "Cursor");
     219                name.equals("crosshair") ? new Point(10, 10) : new Point(3, 2), "Cursor");
    209220        return c;
    210221    }
    211222
    212223    /**
    213      * @return an icon that represent the overlay of the two given icons. The
    214      * second icon is layed on the first relative to the given position.
     224     * @return an icon that represent the overlay of the two given icons. The second icon is layed
     225     * on the first relative to the given position.
    215226     */
    216227    public static ImageIcon overlay(Icon ground, String overlayImage, OverlayPosition pos) {
    217         GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
     228        GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
     229        .getDefaultConfiguration();
    218230        int w = ground.getIconWidth();
    219231        int h = ground.getIconHeight();
     
    221233        int wo = overlay.getIconWidth();
    222234        int ho = overlay.getIconHeight();
    223         BufferedImage img = conf.createCompatibleImage(w,h, Transparency.TRANSLUCENT);
     235        BufferedImage img = conf.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
    224236        Graphics g = img.createGraphics();
    225237        ground.paintIcon(null, g, 0, 0);
     
    231243            break;
    232244        case NORTHEAST:
    233             x = w-wo;
     245            x = w - wo;
    234246            y = 0;
    235247            break;
    236248        case SOUTHWEST:
    237249            x = 0;
    238             y = h-ho;
     250            y = h - ho;
    239251            break;
    240252        case SOUTHEAST:
    241             x = w-wo;
    242             y = h-ho;
     253            x = w - wo;
     254            y = h - ho;
    243255            break;
    244256        }
     
    256268    }
    257269
    258     /* from: http://www.jidesoft.com/blog/2008/02/29/rotate-an-icon-in-java/
    259      * License: "feel free to use"
     270    /*
     271     * from: http://www.jidesoft.com/blog/2008/02/29/rotate-an-icon-in-java/ License:
     272     * "feel free to use"
    260273     */
    261274    final static double DEGREE_90 = 90.0 * Math.PI / 180.0;
     
    263276    /**
    264277     * Creates a rotated version of the input image.
    265      *
    266      * @param c            The component to get properties useful for painting, e.g. the foreground
    267      *                     or background color.
    268      * @param icon         the image to be rotated.
     278     * 
     279     * @param c The component to get properties useful for painting, e.g. the foreground or
     280     * background color.
     281     * @param icon the image to be rotated.
    269282     * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
    270      *                     will mod it with 360 before using it.
    271      *
     283     * will mod it with 360 before using it.
     284     * 
    272285     * @return the image after rotating.
    273286     */
     
    295308            w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
    296309            h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
    297         }
    298         else {
     310        } else {
    299311            w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
    300312            h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
     
    309321
    310322        // move the graphics center point to the center of the icon.
    311         g2d.translate(w/2, h/2);
     323        g2d.translate(w / 2, h / 2);
    312324
    313325        // rotate the graphics about the center point of the icon
     
    329341        if (type == null)
    330342            throw new IllegalArgumentException(tr("parameter ''{0}'' must not be null", "type"));
    331         return get("data",type.getAPIName());
     343        return get("data", type.getAPIName());
    332344    }
    333345}
  • trunk/src/org/openstreetmap/josm/tools/WikiReader.java

    r1755 r1879  
    44import java.io.BufferedReader;
    55import java.io.IOException;
     6import java.io.InputStream;
    67import java.io.InputStreamReader;
    78import java.net.URL;
     
    1011import org.openstreetmap.josm.tools.LanguageInfo;
    1112
     13import static org.openstreetmap.josm.tools.I18n.tr;
     14
    1215/**
    1316 * Read a trac-wiki page.
    14  *
     17 * 
    1518 * @author imi
    1619 */
     
    2932    /**
    3033     * Read the page specified by the url and return the content.
    31      *
    32      * If the url is within the baseurl path, parse it as an trac wikipage and
    33      * replace relative pathes etc..
    34      *
     34     * 
     35     * If the url is within the baseurl path, parse it as an trac wikipage and replace relative
     36     * pathes etc..
     37     * 
    3538     * @return Either the string of the content of the wiki page.
    3639     * @throws IOException Throws, if the page could not be loaded.
     
    4548    public String readLang(String text) {
    4649        String languageCode = LanguageInfo.getLanguageCodeWiki();
    47         String url = baseurl + "/wiki/"+languageCode+text;
     50        String url = baseurl + "/wiki/" + languageCode + text;
    4851        String res = "";
     52        InputStream in = null;
    4953        try {
    50             res = readFromTrac(new BufferedReader(new InputStreamReader(new URL(url).openStream(), "utf-8")));
    51         } catch (IOException ioe) {}
    52         if(res.length() == 0 && languageCode.length() != 0)
    53         {
    54             url = baseurl + "/wiki/"+text;
     54            in = new URL(url).openStream();
     55            res = readFromTrac(new BufferedReader(new InputStreamReader(in, "utf-8")));
     56        } catch (IOException ioe) {
     57            System.out.println(tr("Warning: failed to read MOTD from ''{0}''. Exception was: {1}", url, ioe
     58                    .toString()));
     59        } catch(SecurityException e) {
     60            System.out.println(tr(
     61                    "Warning: failed to read MOTD from ''{0}'' for security reasons. Exception was: {1}", url, e
     62                    .toString()));
     63        } finally {
     64            if (in != null) {
     65                try {
     66                    in.close();
     67                } catch (IOException e) {
     68                }
     69            }
     70        }
     71        if (res.length() == 0 && languageCode.length() != 0) {
     72            url = baseurl + "/wiki/" + text;
    5573            try {
    56                 res = readFromTrac(new BufferedReader(new InputStreamReader(new URL(url).openStream(), "utf-8")));
    57             } catch (IOException ioe) {}
     74                in = new URL(url).openStream();
     75            } catch (IOException e) {
     76                System.out.println(tr("Warning: failed to read MOTD from ''{0}''. Exception was: {1}", url, e
     77                        .toString()));
     78                return res;
     79            } catch (SecurityException e) {
     80                System.out.println(tr(
     81                        "Warning: failed to read MOTD from ''{0}'' for security reasons. Exception was: {1}", url, e
     82                        .toString()));
     83                return res;
     84            }
     85            try {
     86                res = readFromTrac(new BufferedReader(new InputStreamReader(in, "utf-8")));
     87            } catch (IOException ioe) {
     88                System.out.println(tr("Warning: failed to read MOTD from ''{0}''. Exception was: {1}", url, ioe
     89                        .toString()));
     90                return res;
     91            } finally {
     92                if (in != null) {
     93                    try {
     94                        in.close();
     95                    } catch (IOException e) {
     96                    }
     97                }
     98            }
    5899        }
    59100        return res;
     
    63104        String b = "";
    64105        for (String line = in.readLine(); line != null; line = in.readLine()) {
    65             if(!line.contains("[[TranslatedPages]]"))
     106            if (!line.contains("[[TranslatedPages]]")) {
    66107                b += line.replaceAll(" />", ">") + "\n";
     108            }
    67109        }
    68110        return "<html>" + b + "</html>";
     
    74116        String b = "";
    75117        for (String line = in.readLine(); line != null; line = in.readLine()) {
    76             if (line.contains("<div id=\"searchable\">"))
     118            if (line.contains("<div id=\"searchable\">")) {
    77119                inside = true;
    78             else if (line.contains("<div class=\"wiki-toc trac-nav\""))
     120            } else if (line.contains("<div class=\"wiki-toc trac-nav\"")) {
    79121                transl = true;
    80             else if (line.contains("<div class=\"wikipage searchable\">"))
     122            } else if (line.contains("<div class=\"wikipage searchable\">")) {
    81123                inside = true;
    82             else if (line.contains("<div class=\"buttons\">"))
     124            } else if (line.contains("<div class=\"buttons\">")) {
    83125                inside = false;
     126            }
    84127            if (inside && !transl) {
    85                 b += line.replaceAll("<img src=\"/", "<img src=\""+baseurl+"/")
    86                          .replaceAll("href=\"/", "href=\""+baseurl+"/")
    87                          .replaceAll(" />", ">") + "\n";
     128                b += line.replaceAll("<img src=\"/", "<img src=\"" + baseurl + "/").replaceAll("href=\"/",
     129                        "href=\"" + baseurl + "/").replaceAll(" />", ">")
     130                        + "\n";
     131            } else if (transl && line.contains("</div>")) {
     132                transl = false;
    88133            }
    89             else if (transl && line.contains("</div>"))
    90                 transl = false;
    91134        }
    92         if(b.indexOf("      Describe ") >= 0)
     135        if (b.indexOf("      Describe ") >= 0)
    93136            return "";
    94137        return "<html>" + b + "</html>";
Note: See TracChangeset for help on using the changeset viewer.