Changeset 2748 in josm


Ignore:
Timestamp:
2010-01-06T20:35:56+01:00 (11 years ago)
Author:
Gubaer
Message:

new: JOSM now supports OAuth

See also online help for server preferences and new OAuth Authorisation Wizard

Location:
trunk
Files:
1 added
22 edited

Legend:

Unmodified
Added
Removed
  • trunk/CONTRIBUTION

    r2704 r2748  
    22and is now maintained by the OpenStreetMap community.
    33
    4 The current JOSM maintainer is Dirk Stöcker.
     4The current JOSM maintainer is Dirk Stöcker.
    55
    66Major code contributions from (in alphabetical order):
     
    1717Raphael Mack
    1818Frederik Ramm
    19 Dirk Stöcker
     19Dirk Stöcker
    2020
    2121Many minor contributions and patches by others; see SVN history
     
    3838The Bzip2 code is from Keiron Liddle (Apache project) and licensed
    3939with Apache license version 2.0.
     40
     41The signpost code (http://code.google.com/p/oauth-signpost/)
     42is from Matthias Käppler and licensed with the Apache License 2.0.
  • trunk/build.xml

    r2715 r2748  
    103103                        <zipfileset src="lib/gettext-commons-0.9.6.jar" />
    104104                        <zipfileset src="lib/metadata-extractor-2.3.1-nosun.jar" />
     105                        <zipfileset src="lib/commons-codec-1.4.jar" />
     106                        <zipfileset src="lib/signpost-core-1.1.jar" />
    105107                </jar>
    106108        </target>
  • trunk/src/org/openstreetmap/josm/actions/PreferencesAction.java

    r2323 r2748  
    22package org.openstreetmap.josm.actions;
    33
     4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
    45import static org.openstreetmap.josm.tools.I18n.tr;
    5 import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
    66
    7 import java.awt.Dimension;
    8 import java.awt.GridBagLayout;
    97import java.awt.event.ActionEvent;
    108import java.awt.event.KeyEvent;
    119
    12 import javax.swing.JDialog;
    13 import javax.swing.JOptionPane;
    14 import javax.swing.JPanel;
    15 
    1610import org.openstreetmap.josm.Main;
    1711import org.openstreetmap.josm.gui.preferences.PreferenceDialog;
    18 import org.openstreetmap.josm.tools.GBC;
    1912import org.openstreetmap.josm.tools.Shortcut;
    2013
     
    3023     */
    3124    public PreferencesAction() {
    32         super(tr("Preferences..."), "preference", tr("Open a preferences page for global settings."),
    33         Shortcut.registerShortcut("system:preferences", tr("Preferences"), KeyEvent.VK_F12, Shortcut.GROUP_DIRECT), true);
     25        super(tr("Preferences..."), "preference", tr("Open a preferences dialog for global settings."),
     26                Shortcut.registerShortcut("system:preferences", tr("Preferences"), KeyEvent.VK_F12, Shortcut.GROUP_DIRECT), true);
    3427        putValue("help", ht("/Action/Preferences"));
    3528    }
     
    4336
    4437    public void run() {
    45         PreferenceDialog prefDlg = new PreferenceDialog();
    46         prefDlg.setMinimumSize(new Dimension(400,300));
    47         JPanel prefPanel = new JPanel(new GridBagLayout());
    48         prefPanel.add(prefDlg, GBC.eol().fill(GBC.BOTH));
    49 
    50         JOptionPane pane = new JOptionPane(prefPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    51         JDialog dlg = pane.createDialog(Main.parent, tr("Preferences"));
    52         dlg.setResizable(true);
    53         dlg.setMinimumSize(new Dimension(500,400));
    54 
    55 //      if (dlg.getWidth() > 600)
    56 //          dlg.setSize(600, dlg.getHeight());
    57 //      if (dlg.getHeight() > 600)
    58 //          dlg.setSize(dlg.getWidth(),600);
    59 
    60         int JOSMWidth = Main.parent.getWidth();
    61         int JOSMHeight = Main.parent.getHeight();
    62 
    63         if (JOSMWidth > 2000 && JOSMWidth >  JOSMHeight * 2)
    64             // don't center on horizontal span monitor configurations (yes, can be selfish sometimes)
    65             JOSMWidth /= 2;
    66 
    67         int targetWidth = JOSMWidth / 2;
    68         if (targetWidth < 600) targetWidth = 600;
    69         if (targetWidth > 1200) targetWidth = 1200;
    70         int targetHeight = (JOSMHeight * 3) / 4;
    71         if (targetHeight < 600) targetHeight = 600;
    72         if (targetHeight > 1200) targetHeight = 1200;
    73 
    74         int targetX = Main.parent.getX() + JOSMWidth / 2 - targetWidth / 2;
    75         int targetY = Main.parent.getY() + JOSMHeight / 2 - targetHeight / 2;
    76 
    77         dlg.setBounds(targetX, targetY, targetWidth, targetHeight);
    78 
    79         dlg.setModal(true);
    80         dlg.setVisible(true);
    81         if (pane.getValue() instanceof Integer && (Integer)pane.getValue() == JOptionPane.OK_OPTION)
    82             prefDlg.ok();
    83         dlg.dispose();
     38        new PreferenceDialog(Main.parent).setVisible(true);
    8439    }
    8540}
  • trunk/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java

    r2500 r2748  
    9090
    9191                while ((line = input.readLine()) != null) {
    92                     // Skip potential private information
    93                     if (line.trim().toLowerCase().startsWith("osm-server.username")) {
     92                    String toCheck = line.trim().toLowerCase();
     93                    if (toCheck.startsWith("osm-server.username")
     94                            || toCheck.startsWith("osm-server.password")
     95                            || toCheck.startsWith("marker.show")
     96                            || toCheck.startsWith("oauth.access-token.key")
     97                            || toCheck.startsWith("oauth.access-token.secret")) {
    9498                        continue;
    9599                    }
    96                     if (line.trim().toLowerCase().startsWith("osm-server.password")) {
    97                         continue;
    98                     }
    99                     if (line.trim().toLowerCase().startsWith("marker.show")) {
    100                         continue;
    101                     }
    102 
    103100                    text.append(line);
    104101                    text.append("\n");
  • trunk/src/org/openstreetmap/josm/actions/UnGlueAction.java

    r2589 r2748  
    9090                int count = 0;
    9191                for (Way w : OsmPrimitive.getFilteredList(n.getReferrers(), Way.class)) {
    92                     if (!w.isUsable())
     92                    if (!w.isUsable()) {
    9393                        continue;
     94                    }
    9495                    count++;
    9596                }
     
    287288            if (originalNode == pushNode) {
    288289                // clone the node for all other ways
    289                 pushNode = new Node(pushNode, true);
     290                pushNode = new Node(pushNode, true /* clear OSM ID */);
    290291                newNodes.add(pushNode);
    291292                cmds.add(new AddCommand(pushNode));
     
    307308        HashSet<String> rolesToReAdd = null;
    308309        for (Relation r : OsmPrimitive.getFilteredList(originalNode.getReferrers(), Relation.class)) {
    309             if (r.isDeleted())
     310            if (r.isDeleted()) {
    310311                continue;
     312            }
    311313            newRel = null;
    312314            rolesToReAdd = null;
  • trunk/src/org/openstreetmap/josm/data/ServerSidePreferences.java

    r2641 r2748  
    7777                System.out.println("uploading preferences to "+u);
    7878                HttpURLConnection con = (HttpURLConnection)u.openConnection();
     79                // FIXME:
     80                // - doesn't work if CredentialManager isn't JosmPreferencesCredentialManager
     81                // - doesn't work for OAuth
     82
    7983                con.addRequestProperty("Authorization", "Basic "+Base64.encode(get("osm-server.username")+":"+get("osm-server.password")));
    8084                con.setRequestMethod("POST");
  • trunk/src/org/openstreetmap/josm/data/osm/Node.java

    r2620 r2748  
    8686     */
    8787    public Node(Node clone, boolean clearId) {
    88         super(clone.getUniqueId(), true);
     88        super(clone.getUniqueId(), true /* allow negative IDs */);
    8989        cloneFrom(clone);
    9090        if (clearId) {
  • trunk/src/org/openstreetmap/josm/gui/ExceptionDialogUtil.java

    r2598 r2748  
    229229
    230230    /**
     231     * Explains a {@see OsmApiException} which was thrown because the authentication at
     232     * the OSM server failed
     233     *
     234     * @param e the exception
     235     */
     236    public static void explainAuthenticationFailed(OsmApiException e) {
     237        String authMethod = Main.pref.get("osm-server.auth-method", "basic");
     238        String msg;
     239        if (authMethod.equals("oauth")) {
     240            msg = ExceptionUtil.explainFailedOAuthAuthentication(e);
     241        } else {
     242            msg = ExceptionUtil.explainFailedBasicAuthentication(e);
     243        }
     244
     245        HelpAwareOptionPane.showOptionDialog(
     246                Main.parent,
     247                msg,
     248                tr("Authentication Failed"),
     249                JOptionPane.ERROR_MESSAGE,
     250                ht("/ErrorMessages#AuthenticationFailed")
     251        );
     252    }
     253
     254    /**
     255     * Explains a {@see OsmApiException} which was thrown because accessing a protected
     256     * resource was forbidden.
     257     *
     258     * @param e the exception
     259     */
     260    public static void explainAuthorizationFailed(OsmApiException e) {
     261        HelpAwareOptionPane.showOptionDialog(
     262                Main.parent,
     263                ExceptionUtil.explainFailedOAuthAuthorisation(e),
     264                tr("Authorisation Failed"),
     265                JOptionPane.ERROR_MESSAGE,
     266                ht("/ErrorMessages#AuthenticationFailed")
     267        );
     268    }
     269
     270
     271    /**
    231272     * Explains a {@see UnknownHostException} which has caused an {@see OsmTransferException}.
    232273     * This is most likely happening when there is an error in the API URL or when
     
    302343        if (e instanceof OsmApiException) {
    303344            OsmApiException oae = (OsmApiException) e;
    304             if (oae.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED) {
     345            switch(oae.getResponseCode()) {
     346            case HttpURLConnection.HTTP_PRECON_FAILED:
    305347                explainPreconditionFailed(oae);
    306348                return;
     349            case HttpURLConnection.HTTP_GONE:
     350                explainGoneForUnknownPrimitive(oae);
     351                return;
     352            case HttpURLConnection.HTTP_INTERNAL_ERROR:
     353                explainInternalServerError(oae);
     354                return;
     355            case HttpURLConnection.HTTP_BAD_REQUEST:
     356                explainBadRequest(oae);
     357                return;
     358            case HttpURLConnection.HTTP_NOT_FOUND:
     359                explainNotFound(oae);
     360                return;
     361            case HttpURLConnection.HTTP_CONFLICT:
     362                explainConflict(oae);
     363                return;
     364            case HttpURLConnection.HTTP_UNAUTHORIZED:
     365                explainAuthenticationFailed(oae);
     366                return;
     367            case HttpURLConnection.HTTP_FORBIDDEN:
     368                explainAuthorizationFailed(oae);
     369                return;
    307370            }
    308             if (oae.getResponseCode() == HttpURLConnection.HTTP_GONE) {
    309                 explainGoneForUnknownPrimitive(oae);
    310                 return;
    311             }
    312             if (oae.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
    313                 explainInternalServerError(oae);
    314                 return;
    315             }
    316             if (oae.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) {
    317                 explainBadRequest(oae);
    318                 return;
    319             }
    320             if (oae.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
    321                 explainNotFound(oae);
    322                 return;
    323             }
    324             if (oae.getResponseCode() == HttpURLConnection.HTTP_CONFLICT) {
    325                 explainConflict(oae);
    326                 return;
    327             }
    328 
    329         }
    330         explainGeneric(e);
     371            explainGeneric(e);
     372        }
    331373    }
    332374
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r2715 r2748  
    2121
    2222import org.openstreetmap.josm.Main;
     23import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
    2324import org.openstreetmap.josm.io.DefaultProxySelector;
    2425import org.openstreetmap.josm.io.auth.CredentialsManagerFactory;
     
    6263
    6364    /**
     65     * Displays help on the console
     66     *
     67     */
     68    public static void showHelp() {
     69        // TODO: put in a platformHook for system that have no console by default
     70        System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+
     71                tr("usage")+":\n"+
     72                "\tjava -jar josm.jar <options>...\n\n"+
     73                tr("options")+":\n"+
     74                "\t--help|-?|-h                              "+tr("Show this help")+"\n"+
     75                "\t--geometry=widthxheight(+|-)x(+|-)y       "+tr("Standard unix geometry argument")+"\n"+
     76                "\t[--download=]minlat,minlon,maxlat,maxlon  "+tr("Download the bounding box")+"\n"+
     77                "\t[--download=]<url>                        "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+
     78                "\t[--download=]<filename>                   "+tr("Open file (as raw gps, if .gpx)")+"\n"+
     79                "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+
     80                "\t--selection=<searchstring>                "+tr("Select with the given search")+"\n"+
     81                "\t--[no-]maximize                           "+tr("Launch in maximized mode")+"\n"+
     82                "\t--reset-preferences                       "+tr("Reset the preferences to default")+"\n\n"+
     83                "\t--language=<language>                     "+tr("Set the language.")+"\n\n"+
     84                tr("options provided as Java system properties")+":\n"+
     85                "\t-Djosm.home="+tr("/PATH/TO/JOSM/FOLDER/         ")+tr("Change the folder for all user settings")+"\n\n"+
     86                tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
     87                "      Java option to increase the maximum size of allocated memory")+":\n"+
     88                "\t-Xmx...m\n\n"+
     89                tr("examples")+":\n"+
     90                "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
     91                "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+
     92                "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
     93                "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
     94                "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
     95                "\tjava -Xmx400m -jar josm.jar\n\n"+
     96                tr("Parameters are read in the order they are specified, so make sure you load\n"+
     97                "some data before --selection")+"\n\n"+
     98                tr("Instead of --download=<bbox> you may specify osm://<bbox>\n"));
     99    }
     100
     101    /**
    64102     * Main application Startup
    65103     */
     
    102140        Main.pref.updateSystemProperties();
    103141
    104         Authenticator.setDefault(
    105                 new DefaultAuthenticator(
    106                         CredentialsManagerFactory.getCredentialManager()
    107                 )
    108         );
     142        DefaultAuthenticator.createInstance(CredentialsManagerFactory.getCredentialManager());
     143        Authenticator.setDefault(DefaultAuthenticator.getInstance());
    109144        ProxySelector.setDefault(new DefaultProxySelector(ProxySelector.getDefault()));
    110 
     145        OAuthAccessTokenHolder.getInstance().init(Main.pref, CredentialsManagerFactory.getCredentialManager());
     146
     147        // asking for help? show help and exit
    111148        if (argList.contains("--help") || argList.contains("-?") || argList.contains("-h")) {
    112             // TODO: put in a platformHook for system that have no console by default
    113             System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+
    114                     tr("usage")+":\n"+
    115                     "\tjava -jar josm.jar <options>...\n\n"+
    116                     tr("options")+":\n"+
    117                     "\t--help|-?|-h                              "+tr("Show this help")+"\n"+
    118                     "\t--geometry=widthxheight(+|-)x(+|-)y       "+tr("Standard unix geometry argument")+"\n"+
    119                     "\t[--download=]minlat,minlon,maxlat,maxlon  "+tr("Download the bounding box")+"\n"+
    120                     "\t[--download=]<url>                        "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+
    121                     "\t[--download=]<filename>                   "+tr("Open file (as raw gps, if .gpx)")+"\n"+
    122                     "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+
    123                     "\t--selection=<searchstring>                "+tr("Select with the given search")+"\n"+
    124                     "\t--[no-]maximize                           "+tr("Launch in maximized mode")+"\n"+
    125                     "\t--reset-preferences                       "+tr("Reset the preferences to default")+"\n\n"+
    126                     "\t--language=<language>                     "+tr("Set the language.")+"\n\n"+
    127                     tr("options provided as Java system properties")+":\n"+
    128                     "\t-Djosm.home="+tr("/PATH/TO/JOSM/FOLDER/         ")+tr("Change the folder for all user settings")+"\n\n"+
    129                     tr("note: For some tasks, JOSM needs a lot of memory. It can be necessary to add the following\n" +
    130                     "      Java option to increase the maximum size of allocated memory")+":\n"+
    131                     "\t-Xmx...m\n\n"+
    132                     tr("examples")+":\n"+
    133                     "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+
    134                     "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+
    135                     "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+
    136                     "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n"+
    137                     "\tjava -Djosm.home=/home/user/.josm_dev -jar josm.jar\n"+
    138                     "\tjava -Xmx400m -jar josm.jar\n\n"+
    139                     tr("Parameters are read in the order they are specified, so make sure you load\n"+
    140                     "some data before --selection")+"\n\n"+
    141                     tr("Instead of --download=<bbox> you may specify osm://<bbox>\n"));
     149            showHelp();
    142150            System.exit(0);
    143151        }
     
    185193    public static void removeObsoletePreferences() {
    186194        String[] obsolete = {
    187                 "sample.preference.that.does.not.exist", // sample comment, expiry date should go here
    188                 "osm-server.version", // remove this around 10/2009
    189                 "osm-server.additional-versions", // remove this around 10/2009
    190                 null
     195                "proxy.anonymous", // 01/2010 - not needed anymore. Can be removed mid 2010
     196                "proxy.enable"     // 01/2010 - not needed anymore. Can be removed mid 2010
    191197        };
    192         for (String i : obsolete) {
    193             if (i == null) {
    194                 continue;
    195             }
    196             if (Main.pref.hasKey(i)) {
    197                 Main.pref.removeFromCollection(i, Main.pref.get(i));
    198                 System.out.println(tr("Preference setting {0} has been removed since it is no longer used.", i));
     198        for (String key : obsolete) {
     199            if (Main.pref.hasKey(key)) {
     200                Main.pref.removeFromCollection(key, Main.pref.get(key));
     201                System.out.println(tr("Preference setting {0} has been removed since it is no longer used.", key));
    199202            }
    200203        }
  • trunk/src/org/openstreetmap/josm/gui/dialogs/changeset/query/AdvancedChangesetQueryPanel.java

    r2689 r2748  
    66import java.awt.BorderLayout;
    77import java.awt.Color;
    8 import java.awt.Dimension;
    98import java.awt.GridBagConstraints;
    109import java.awt.GridBagLayout;
    1110import java.awt.Insets;
    12 import java.awt.Rectangle;
    1311import java.awt.event.ItemEvent;
    1412import java.awt.event.ItemListener;
     
    2826import javax.swing.JScrollPane;
    2927import javax.swing.JTextField;
    30 import javax.swing.Scrollable;
    3128import javax.swing.text.JTextComponent;
    3229
     
    3936import org.openstreetmap.josm.gui.widgets.BoundingBoxSelectionPanel;
    4037import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
     38import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
    4139import org.openstreetmap.josm.io.ChangesetQuery;
    4240import org.openstreetmap.josm.tools.CheckParameterUtil;
     
    5957    protected JPanel buildQueryPanel() {
    6058        ItemListener stateChangeHandler = new RestrictionGroupStateChangeHandler();
    61         JPanel pnl  = new QuerySpecificationPanel();
     59        JPanel pnl  = new VerticallyScrollablePanel();
    6260        pnl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    6361        pnl.setLayout(new GridBagLayout());
     
    961959    }
    962960
    963     static private class QuerySpecificationPanel extends JPanel implements Scrollable {
    964         public Dimension getPreferredScrollableViewportSize() {
    965             return getPreferredSize();
    966         }
    967 
    968         public int getScrollableBlockIncrement(Rectangle arg0, int arg1, int arg2) {
    969             return 20;
    970         }
    971 
    972         public boolean getScrollableTracksViewportHeight() {
    973             return false;
    974         }
    975 
    976         public boolean getScrollableTracksViewportWidth() {
    977             return true;
    978         }
    979 
    980         public int getScrollableUnitIncrement(Rectangle arg0, int arg1, int arg2) {
    981             return 10;
    982         }
    983     }
    984 
    985961    /**
    986962     * Validator for user ids entered in in a {@see JTextComponent}.
  • trunk/src/org/openstreetmap/josm/io/DefaultProxySelector.java

    r2733 r2748  
    1616
    1717import org.openstreetmap.josm.Main;
    18 import org.openstreetmap.josm.gui.preferences.ProxyPreferences;
    19 import org.openstreetmap.josm.gui.preferences.ProxyPreferences.ProxyPolicy;
     18import org.openstreetmap.josm.gui.preferences.server.ProxyPreferencesPanel;
     19import org.openstreetmap.josm.gui.preferences.server.ProxyPreferencesPanel.ProxyPolicy;
     20
    2021
    2122/**
     
    99100     */
    100101    public void initFromPreferences() {
    101         String value = Main.pref.get(ProxyPreferences.PROXY_POLICY);
     102        String value = Main.pref.get(ProxyPreferencesPanel.PROXY_POLICY);
    102103        if (value.length() == 0) {
    103             System.err.println(tr("Warning: no preference ''{0}'' found.", ProxyPreferences.PROXY_POLICY));
     104            System.err.println(tr("Warning: no preference ''{0}'' found.", ProxyPreferencesPanel.PROXY_POLICY));
    104105            System.err.println(tr("The proxy will not be used."));
    105106            proxyPolicy = ProxyPolicy.NO_PROXY;
     
    107108            proxyPolicy= ProxyPolicy.fromName(value);
    108109            if (proxyPolicy == null) {
    109                 System.err.println(tr("Warning: unexpected value for preference ''{0}'' found. Got ''{1}''. Will use no proxy.", ProxyPreferences.PROXY_POLICY, value));
     110                System.err.println(tr("Warning: unexpected value for preference ''{0}'' found. Got ''{1}''. Will use no proxy.", ProxyPreferencesPanel.PROXY_POLICY, value));
    110111                proxyPolicy = ProxyPolicy.NO_PROXY;
    111112            }
    112113        }
    113         String host = Main.pref.get(ProxyPreferences.PROXY_HTTP_HOST, null);
    114         int port = parseProxyPortValue(ProxyPreferences.PROXY_HTTP_PORT, Main.pref.get(ProxyPreferences.PROXY_HTTP_PORT, null));
     114        String host = Main.pref.get(ProxyPreferencesPanel.PROXY_HTTP_HOST, null);
     115        int port = parseProxyPortValue(ProxyPreferencesPanel.PROXY_HTTP_PORT, Main.pref.get(ProxyPreferencesPanel.PROXY_HTTP_PORT, null));
    115116        if (host != null && ! host.trim().equals("") && port > 0) {
    116117            httpProxySocketAddress = new InetSocketAddress(host,port);
     
    123124        }
    124125
    125         host = Main.pref.get(ProxyPreferences.PROXY_SOCKS_HOST, null);
    126         port = parseProxyPortValue(ProxyPreferences.PROXY_SOCKS_PORT, Main.pref.get(ProxyPreferences.PROXY_SOCKS_PORT, null));
     126        host = Main.pref.get(ProxyPreferencesPanel.PROXY_SOCKS_HOST, null);
     127        port = parseProxyPortValue(ProxyPreferencesPanel.PROXY_SOCKS_PORT, Main.pref.get(ProxyPreferencesPanel.PROXY_SOCKS_PORT, null));
    127128        if (host != null && ! host.trim().equals("") && port > 0) {
    128129            socksProxySocketAddress = new InetSocketAddress(host,port);
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r2734 r2748  
    466466    }
    467467
     468    protected boolean isUsingOAuth() {
     469        String authMethod = Main.pref.get("osm-server.auth-method", "basic");
     470        return authMethod.equals("oauth");
     471    }
     472
    468473    private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor) throws OsmTransferException {
    469474        return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true);
     
    574579                case HttpURLConnection.HTTP_GONE:
    575580                    throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
    576                 case HttpURLConnection.HTTP_UNAUTHORIZED:
    577                 case HttpURLConnection.HTTP_PROXY_AUTH:
    578                     // if we get here with HTTP_UNAUTHORIZED or HTTP_PROXY_AUTH the user canceled the
    579                     // username/password dialog. Throw an OsmTransferCancelledException.
    580                     //
    581                     throw new OsmTransferCancelledException();
     581                    //                case HttpURLConnection.HTTP_UNAUTHORIZED:
     582                    //                    throw new OsmApiException(retCode, errorHeader, errorBody);
     583                    //                case HttpURLConnection.HTTP_PROXY_AUTH:
     584                    //                    throw new OsmApiException(retCode, errorHeader, errorBody);
     585                    //                case HttpURLConnection.HTTP_FORBIDDEN:
     586                    //                    throw new OsmApiException(retCode, errorHeader, errorBody);
    582587                case HttpURLConnection.HTTP_CONFLICT:
    583588                    if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
     
    585590                    else
    586591                        throw new OsmApiException(retCode, errorHeader, errorBody);
     592                case HttpURLConnection.HTTP_FORBIDDEN:
     593                    OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
     594                    e.setAccessedUrl(activeConnection.getURL().toString());
     595                    throw e;
    587596                default:
    588597                    throw new OsmApiException(retCode, errorHeader, errorBody);
  • trunk/src/org/openstreetmap/josm/io/OsmApiException.java

    r2512 r2748  
    88    private String errorHeader;
    99    private String errorBody;
     10    private String accessedUrl;
    1011
    1112    public OsmApiException() {
     
    6061        sb.append("ResponseCode=")
    6162        .append(responseCode);
    62         if (errorHeader != null && !errorBody.trim().equals("")) {
     63        if (errorHeader != null && errorBody != null && !errorBody.trim().equals("")) {
    6364            sb.append(", Error Header=<")
    6465            .append(tr(errorHeader))
     
    9596        return sb.toString();
    9697    }
     98
     99    public void setAccessedUrl(String url) {
     100        this.accessedUrl = url;
     101    }
     102
     103    public String getAccessedUrl() {
     104        return accessedUrl;
     105    }
    97106}
  • trunk/src/org/openstreetmap/josm/io/OsmConnection.java

    r2641 r2748  
    11// License: GPL. Copyright 2007 by Immanuel Scholz and others
    22package org.openstreetmap.josm.io;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    35
    46import java.net.HttpURLConnection;
     
    1113import java.util.logging.Logger;
    1214
     15import oauth.signpost.OAuthConsumer;
     16import oauth.signpost.exception.OAuthException;
     17
     18import org.openstreetmap.josm.Main;
     19import org.openstreetmap.josm.data.oauth.OAuthParameters;
     20import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
    1321import org.openstreetmap.josm.io.auth.CredentialsManagerException;
    1422import org.openstreetmap.josm.io.auth.CredentialsManagerFactory;
     
    2735    protected boolean cancel = false;
    2836    protected HttpURLConnection activeConnection;
     37    protected OAuthParameters oauthParameters;
    2938
    3039    /**
     
    5968    }
    6069
    61     protected void addAuth(HttpURLConnection con) throws OsmTransferException {
     70    /**
     71     * Adds an authentication header for basic authentication
     72     *
     73     * @param con the connection
     74     * @throws OsmTransferException thrown is something went wrong. Check for nested exceptions
     75     */
     76    protected void addBasicAuthorizationHeader(HttpURLConnection con) throws OsmTransferException {
    6277        CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    6378        CredentialsManagerResponse response;
     
    89104
    90105    /**
     106     * Signs the connection with an OAuth authentication header
     107     *
     108     * @param connection the connection
     109     *
     110     * @throws OsmTransferException thrown if there is currently no OAuth Access Token configured
     111     * @throws OsmTransferException thrown if signing fails
     112     */
     113    protected void addOAuthAuthorizationHeader(HttpURLConnection connection) throws OsmTransferException {
     114        if (oauthParameters == null) {
     115            oauthParameters = OAuthParameters.createFromPreferences(Main.pref);
     116        }
     117        OAuthConsumer consumer = oauthParameters.buildConsumer();
     118        OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
     119        if (! holder.containsAccessToken())
     120            throw new OsmTransferException(tr("Failed to add an OAuth authentication header. There is currently no OAuth Access Token configured."));
     121
     122        consumer.setTokenWithSecret(holder.getAccessTokenKey(), holder.getAccessTokenSecret());
     123        try {
     124            consumer.sign(connection);
     125        } catch(OAuthException e) {
     126            throw new OsmTransferException(tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e);
     127        }
     128    }
     129
     130    protected void addAuth(HttpURLConnection connection) throws OsmTransferException {
     131        String authMethod = Main.pref.get("osm-server.auth-method", "basic");
     132        if (authMethod.equals("basic")) {
     133            addBasicAuthorizationHeader(connection);
     134        } else if (authMethod.equals("oauth")) {
     135            addOAuthAuthorizationHeader(connection);
     136        } else {
     137            String msg = tr("Warning: unexpected value for preference ''{0}''. Got ''{1}''.", "osm-server.auth-method", authMethod);
     138            System.err.println(msg);
     139            throw new OsmTransferException(msg);
     140        }
     141    }
     142
     143    /**
    91144     * Replies true if this connection is canceled
    92145     *
  • trunk/src/org/openstreetmap/josm/io/OsmServerUserInfoReader.java

    r2688 r2748  
    2525public class OsmServerUserInfoReader extends OsmServerReader {
    2626
    27     public OsmServerUserInfoReader() {
    28         setDoAuthenticate(true);
    29     }
    30 
    31     @Override
    32     public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
    33         // not implemented
    34         return null;
    35     }
    36 
    37     protected String getAttribute(Node node, String name) {
     27    static protected String getAttribute(Node node, String name) {
    3828        return node.getAttributes().getNamedItem(name).getNodeValue();
    3929    }
    4030
    41     protected UserInfo buildFromXML(Document document) throws OsmDataParsingException{
     31    static public UserInfo buildFromXML(Document document) throws OsmDataParsingException{
    4232        try {
    4333            XPathFactory factory = XPathFactory.newInstance();
     
    121111    }
    122112
     113    public OsmServerUserInfoReader() {
     114        setDoAuthenticate(true);
     115    }
     116
     117    @Override
     118    public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
     119        // not implemented
     120        return null;
     121    }
     122
     123
     124
    123125    public UserInfo fetchUserInfo(ProgressMonitor monitor) throws OsmTransferException {
    124126        try {
    125             monitor.beginTask("Reading user info ...");
     127            monitor.beginTask(tr("Reading user info ..."));
    126128            InputStream in = getInputStream("user/details", monitor.createSubTaskMonitor(1, true));
    127129            return buildFromXML(
  • trunk/src/org/openstreetmap/josm/io/auth/CredentialsManager.java

    r2711 r2748  
    44import java.net.PasswordAuthentication;
    55import java.net.Authenticator.RequestorType;
     6
     7import org.openstreetmap.josm.data.oauth.OAuthToken;
    68
    79/**
     
    1315 *   optional HTTP proxy server a user may use</li>
    1416 *  </ul>
     17 *
     18 *  In addition, it manages an OAuth Access Token for accessing the OSM server.
    1519 */
    1620public interface CredentialsManager {
     
    4650     */
    4751    public CredentialsManagerResponse getCredentials(RequestorType requestorType, boolean noSuccessWithLastResponse) throws CredentialsManagerException;
     52
     53
     54    /**
     55     * Lookup the current OAuth Access Token to access the OSM server. Replies null, if no
     56     * Access Token is currently managed by this CredentialManager.
     57     *
     58     * @return the current OAuth Access Token to access the OSM server.
     59     * @throws CredentialsManagerException thrown if something goes wrong
     60     */
     61    public OAuthToken lookupOAuthAccessToken() throws CredentialsManagerException;
     62
     63    /**
     64     * Stores the OAuth Access Token <code>accessToken</code>.
     65     *
     66     * @param accessToken the access Token. null, to remove the Access Token.
     67     * @throws CredentialsManagerException thrown if something goes wrong
     68     */
     69    public void storeOAuthAccessToken(OAuthToken accessToken) throws CredentialsManagerException;
    4870}
  • trunk/src/org/openstreetmap/josm/io/auth/DefaultAuthenticator.java

    r2711 r2748  
    88import java.util.logging.Logger;
    99
     10import org.openstreetmap.josm.Main;
     11
    1012/**
    1113 * This is the default authenticator used in JOSM. It delegates lookup of credentials
     
    1618public  class DefaultAuthenticator extends Authenticator {
    1719    private static final Logger logger = Logger.getLogger(DefaultAuthenticator.class.getName());
     20    private static DefaultAuthenticator instance;
     21
     22    public static DefaultAuthenticator getInstance() {
     23        return instance;
     24    }
     25
     26    public static void createInstance(CredentialsManager credentialManager) {
     27        instance = new DefaultAuthenticator(credentialManager);
     28    }
    1829
    1930    private CredentialsManager credentialManager;
    2031    private final Map<RequestorType, Boolean> credentialsTried = new HashMap<RequestorType, Boolean>();
     32    private boolean enabled = true;
    2133
    2234    /**
     
    2436     * @param credentialManager the credential manager
    2537     */
    26     public DefaultAuthenticator(CredentialsManager credentialManager) {
     38    private DefaultAuthenticator(CredentialsManager credentialManager) {
    2739        this.credentialManager = credentialManager;
    2840    }
     41
     42
    2943
    3044    /**
     
    3448     */
    3549    @Override protected PasswordAuthentication getPasswordAuthentication() {
     50        if (!enabled)
     51            return null;
    3652        try {
     53            if (getRequestorType().equals(Authenticator.RequestorType.SERVER)) {
     54                // if we are working with OAuth we don't prompt for a password
     55                //
     56                String authMethod = Main.pref.get("osm-server.auth-method", "basic");
     57                if (authMethod.equals("oauth"))
     58                    return null;
     59            }
    3760            boolean tried = credentialsTried.get(getRequestorType()) != null;
    3861            CredentialsManagerResponse response = credentialManager.getCredentials(getRequestorType(), tried);
     
    4669        }
    4770    }
     71
     72    public boolean isEnabled() {
     73        return enabled;
     74    }
     75
     76    public void setEnabled(boolean enabled) {
     77        this.enabled = enabled;
     78    }
    4879}
  • trunk/src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialManager.java

    r2711 r2748  
    66
    77import org.openstreetmap.josm.Main;
     8import org.openstreetmap.josm.data.oauth.OAuthToken;
    89import org.openstreetmap.josm.gui.io.CredentialDialog;
    9 import org.openstreetmap.josm.gui.preferences.ProxyPreferences;
     10import org.openstreetmap.josm.gui.preferences.server.ProxyPreferencesPanel;
    1011
    1112/**
     
    3233            return new PasswordAuthentication(user, password == null ? new char[0] : password.toCharArray());
    3334        case PROXY:
    34             user = Main.pref.get(ProxyPreferences.PROXY_USER, null);
    35             password = Main.pref.get(ProxyPreferences.PROXY_PASS, null);
     35            user = Main.pref.get(ProxyPreferencesPanel.PROXY_USER, null);
     36            password = Main.pref.get(ProxyPreferencesPanel.PROXY_PASS, null);
    3637            if (user == null)
    3738                return null;
     
    5758            break;
    5859        case PROXY:
    59             Main.pref.put("proxy.username", credentials.getUserName());
     60            Main.pref.put(ProxyPreferencesPanel.PROXY_USER, credentials.getUserName());
    6061            if (credentials.getPassword() == null) {
    61                 Main.pref.put("proxy.password", null);
     62                Main.pref.put(ProxyPreferencesPanel.PROXY_PASS, null);
    6263            } else {
    63                 Main.pref.put("proxy.password", String.valueOf(credentials.getPassword()));
     64                Main.pref.put(ProxyPreferencesPanel.PROXY_PASS, String.valueOf(credentials.getPassword()));
    6465            }
    6566            break;
     
    104105        return response;
    105106    }
     107
     108
     109    /**
     110     * Lookup the current OAuth Access Token to access the OSM server. Replies null, if no
     111     * Access Token is currently managed by this CredentialManager.
     112     *
     113     * @return the current OAuth Access Token to access the OSM server.
     114     * @throws CredentialsManagerException thrown if something goes wrong
     115     */
     116    public OAuthToken lookupOAuthAccessToken() throws CredentialsManagerException {
     117        String accessTokenKey = Main.pref.get("oauth.access-token.key", null);
     118        String accessTokenSecret = Main.pref.get("oauth.access-token.secret", null);
     119        if (accessTokenKey == null && accessTokenSecret == null)
     120            return null;
     121        return new OAuthToken(accessTokenKey, accessTokenSecret);
     122    }
     123
     124    /**
     125     * Stores the OAuth Access Token <code>accessToken</code>.
     126     *
     127     * @param accessToken the access Token. null, to remove the Access Token.
     128     * @throws CredentialsManagerException thrown if something goes wrong
     129     */
     130    public void storeOAuthAccessToken(OAuthToken accessToken) throws CredentialsManagerException {
     131        if (accessToken == null) {
     132            Main.pref.put("oauth.access-token.key", null);
     133            Main.pref.put("oauth.access-token.secret", null);
     134        } else {
     135            Main.pref.put("oauth.access-token.key", accessToken.getKey());
     136            Main.pref.put("oauth.access-token.secret", accessToken.getSecret());
     137        }
     138    }
    106139}
  • trunk/src/org/openstreetmap/josm/tools/ExceptionUtil.java

    r2512 r2748  
    1919
    2020import org.openstreetmap.josm.Main;
     21import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
    2122import org.openstreetmap.josm.io.ChangesetClosedException;
    2223import org.openstreetmap.josm.io.OsmApi;
     
    8788    }
    8889
     90    public static String explainFailedBasicAuthentication(OsmApiException e) {
     91        e.printStackTrace();
     92        return tr("<html>"
     93                + "Authentication at the OSM server with the username ''{0}'' failed.<br>"
     94                + "Please check the username and the password in the JOSM preferences."
     95                + "</html>",
     96                Main.pref.get("osm-server.username")
     97        );
     98    }
     99
     100    public static String explainFailedOAuthAuthentication(OsmApiException e) {
     101        e.printStackTrace();
     102        return tr("<html>"
     103                + "Authentication at the OSM server with the OAuth token ''{0}'' failed.<br>"
     104                + "Please launch the preferences dialog and retrieve another OAuth token."
     105                + "</html>",
     106                OAuthAccessTokenHolder.getInstance().getAccessTokenKey()
     107        );
     108    }
     109
     110    public static String explainFailedOAuthAuthorisation(OsmApiException e) {
     111        e.printStackTrace();
     112        return tr("<html>"
     113                + "Authorisation at the OSM server with the OAuth token ''{0}'' failed.<br>"
     114                + "The token is not authorised to access the protected resource<br>"
     115                + "''{1}''.<br>"
     116                + "Please launch the preferences dialog and retrieve another OAuth token."
     117                + "</html>",
     118                OAuthAccessTokenHolder.getInstance().getAccessTokenKey(),
     119                e.getAccessedUrl() == null ? tr("unknown") : e.getAccessedUrl()
     120        );
     121    }
    89122    /**
    90123     * Explains an error due to a 409 conflict
  • trunk/src/org/openstreetmap/josm/tools/OpenBrowser.java

    r1169 r2748  
    11// License: GPL. Copyright 2007 by Immanuel Scholz and others
    22package org.openstreetmap.josm.tools;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    35
    46import java.io.IOException;
     
    2123    /**
    2224     * @return <code>null</code> for success or a string in case of an error.
     25     * @throws IllegalStateException thrown if no platform is set to which opening the URL can be dispatched,
     26     * {@see Main#platform}
    2327     */
    24     public static String displayUrl(String url) {
     28    public static String displayUrl(String url) throws IllegalStateException {
    2529        if (Main.applet) {
    2630            try {
     
    3337        }
    3438
     39        if (Main.platform == null)
     40            throw new IllegalStateException(tr("Failed to open URL. There is currently no platform set. Please set a platform first."));
    3541        try {
    3642            Main.platform.openUrl(url);
  • trunk/test/config/test-functional-env.properties

    r1806 r2748  
    99# This is the home directory for JOSM plugins: ${josm.home}\plugins\*.jar
    1010#
    11 josm.home=C:\\data\\projekte\\osm\\tag-editor-plugin
     11josm.home=C:\\data\\projekte\\osm\\josm-dev
    1212
    1313
     
    1616#   temporary results
    1717#
    18 test.functional.tempdir=C:\\data\\projekte\\eclipse-3.4.1-ws\\JOSM-1769\\test\\data\\temp
     18test.functional.tempdir=C:\\data\\projekte\\osm\\josm-dev\\temp
    1919
  • trunk/test/functional/org/openstreetmap/josm/fixtures/JOSMFixture.java

    r2600 r2748  
    1414import org.openstreetmap.josm.data.projection.Mercator;
    1515import org.openstreetmap.josm.io.OsmApi;
     16import org.openstreetmap.josm.tools.I18n;
    1617
    1718public class JOSMFixture {
     
    4243        } catch(Exception e){
    4344            logger.log(Level.SEVERE, MessageFormat.format("failed to load property file ''{0}''", testPropertiesResourceName));
    44             fail(MessageFormat.format("failed to load property file ''{0}''", testPropertiesResourceName));
     45            fail(MessageFormat.format("failed to load property file ''{0}''. \nMake sure the path ''$project_root/test/config'' is on the classpath.", testPropertiesResourceName));
    4546        }
    4647
     
    5354            File f = new File(josmHome);
    5455            if (! f.exists() || ! f.canRead()) {
    55                 fail(MessageFormat.format("property ''{0}'' points to ''{1}'' which is either not existing or not readable", "josm.home", josmHome));
     56                fail(MessageFormat.format("property ''{0}'' points to ''{1}'' which is either not existing or not readable.\nEdit ''{2}'' and update the value ''josm.home''. ", "josm.home", josmHome,testPropertiesResourceName ));
    5657            }
    5758        }
    5859        System.setProperty("josm.home", josmHome);
     60        I18n.init();
     61        // initialize the plaform hook, and
     62        Main.determinePlatformHook();
     63        // call the really early hook before we anything else
     64        Main.platform.preStartupHook();
     65
    5966        Main.pref.init(false);
    6067
Note: See TracChangeset for help on using the changeset viewer.