Ignore:
Timestamp:
2009-06-15T20:22:46+02:00 (17 years ago)
Author:
Gubaer
Message:

fixed: bug in OsmApi.getOsmApi()
cleanup: exception handling in interfacing with OSM API
new: new action for updating individual elements with the their current state on the server (including new menu item in the file menu)
new: improved user feedback in case of conflicts
new: handles 410 Gone conflicts when uploading a changeset
new: undoable command for "purging" a primitive from the current dataset (necessary if the primitive is already deleted on the server and the user wants to remove it from its local dataset)
new: undoable command for "undeleting" an already deleted primitive on the server (kind of "cloning")
new: after a full upload, checks whether there are primitives in the local dataset which might be deleted on the server.
new: data structures for history data
new: history download support in io package

Location:
trunk/src/org/openstreetmap/josm/io
Files:
2 added
9 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/io/BoundingBoxDownloader.java

    r1465 r1670  
    5050                Main.pleaseWaitDlg.currentAction.setText(tr("Downloading points {0} to {1}...", i * 5000, ((i + 1) * 5000)));
    5151                InputStream in = getInputStream(url+i, Main.pleaseWaitDlg);
    52                 if (in == null)
     52                if (in == null) {
    5353                    break;
     54                }
    5455                GpxData currentGpx = new GpxReader(in, null).data;
    5556                if (result == null) {
     
    8990     * @return A data set containing all data retrieved from that url
    9091     */
    91     public DataSet parseOsm() throws SAXException, IOException {
     92    @Override
     93    public DataSet parseOsm() throws OsmTransferException {
    9294        try {
    9395            Main.pleaseWaitDlg.progress.setValue(0);
     
    106108            if (cancel)
    107109                return null;
    108             throw e;
     110            throw new OsmTransferException(e);
    109111        } catch (SAXException e) {
     112            throw new OsmTransferException(e);
     113        } catch(OsmTransferException e) {
    110114            throw e;
    111115        } catch (Exception e) {
    112116            if (cancel)
    113117                return null;
    114             if (e instanceof RuntimeException)
    115                 throw (RuntimeException)e;
    116             throw new RuntimeException(e);
     118            throw new OsmTransferException(e);
    117119        }
    118120    }
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r1667 r1670  
    2929import org.openstreetmap.josm.Main;
    3030import org.openstreetmap.josm.data.osm.Changeset;
    31 import org.openstreetmap.josm.data.osm.Node;
    3231import org.openstreetmap.josm.data.osm.OsmPrimitive;
    33 import org.openstreetmap.josm.data.osm.Relation;
    34 import org.openstreetmap.josm.data.osm.Way;
     32import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
    3533import org.openstreetmap.josm.data.osm.visitor.CreateOsmChangeVisitor;
    3634import org.xml.sax.Attributes;
     
    6765        if (api == null) {
    6866            api = new OsmApi(serverUrl);
     67            instances.put(serverUrl,api);
    6968        }
    7069        return api;
     
    8079        String serverUrl = Main.pref.get("osm-server.url");
    8180        if (serverUrl == null)
    82             throw new IllegalStateException(tr("preference {0} missing. Can't initialize OsmApi", "osm-server.url"));
     81            throw new IllegalStateException(tr("preference ''{0}'' missing. Can't initialize OsmApi", "osm-server.url"));
    8382        return getOsmApi(serverUrl);
    8483    }
     
    9695     */
    9796    private String version = null;
    98 
    99     /**
    100      * Maximum downloadable area from server (degrees squared), from capabilities response
    101      * FIXME: make download dialog use this, instead of hard-coded default.
    102      */
    103     private String maxArea = null;
    10497
    10598    /** the api capabilities */
     
    143136
    144137    /**
    145      * creates an instance of the OSM API. Initializes the server URL with the
    146      * value of the preference <code>osm-server.url</code>
    147      *
    148      * @exception IllegalStateException thrown, if the preference <code>osm-server.url</code> is not set
    149      */
    150     protected OsmApi() {
    151         this.serverUrl = Main.pref.get("osm-server.url");
    152         if (serverUrl == null)
    153             throw new IllegalStateException(tr("preference {0} missing. Can't initialize OsmApi", "osm-server.url"));
    154     }
    155 
    156     /**
    157      * Helper that returns the lower-case type name of an OsmPrimitive
    158      * @param o the primitive
    159      * @return "node", "way", "relation", or "changeset"
    160      */
    161     public static String which(OsmPrimitive o) {
    162         if (o instanceof Node) return "node";
    163         if (o instanceof Way) return "way";
    164         if (o instanceof Relation) return "relation";
    165         if (o instanceof Changeset) return "changeset";
    166         return "";
    167     }
    168 
    169     /**
    170138     * Returns the OSM protocol version we use to talk to the server.
    171139     * @return protocol version, or null if not yet negotiated.
     
    185153    /**
    186154     * Initializes this component by negotiating a protocol version with the server.
    187      *
    188      * @exception UnknownHostException thrown, if the API host is unknown
    189      * @exception SocketTimeoutException thrown, if the connection to the API host  times out
    190      * @exception ConnectException throw, if the connection to the API host fails
    191      * @exception Exception any other exception
     155     *
     156     * @exception OsmApiInitializationException thrown, if an exception occurs
    192157     */
    193158    public void initialize() throws OsmApiInitializationException {
     
    238203
    239204    /**
    240      * Helper that makes an int from the first whitespace separated token in a string.
    241      * @param s the string
    242      * @return the integer represenation of the first token in the string
    243      * @throws OsmTransferException if the string is empty or does not represent a number
    244      */
    245     public static int parseInt(String s) throws OsmTransferException {
    246         StringTokenizer t = new StringTokenizer(s);
    247         try {
    248             return Integer.parseInt(t.nextToken());
    249         } catch (Exception x) {
    250             throw new OsmTransferException(tr("Cannot read numeric value from response"));
    251         }
    252     }
    253 
    254     /**
    255      * Helper that makes a long from the first whitespace separated token in a string.
    256      * @param s the string
    257      * @return the long represenation of the first token in the string
    258      * @throws OsmTransferException if the string is empty or does not represent a number
    259      */
    260     public static long parseLong(String s) throws OsmTransferException {
    261         StringTokenizer t = new StringTokenizer(s);
    262         try {
    263             return Long.parseLong(t.nextToken());
    264         } catch (Exception x) {
    265             throw new OsmTransferException(tr("Cannot read numeric value from response"));
    266         }
    267     }
    268 
    269     /**
    270205     * Returns the base URL for API requests, including the negotiated version number.
    271206     * @return base URL string
     
    293228    public void createPrimitive(OsmPrimitive osm) throws OsmTransferException {
    294229        initialize();
    295         osm.id = parseLong(sendRequest("PUT", which(osm)+"/create", toXml(osm, true)));
    296         osm.version = 1;
     230        String ret = "";
     231        try {
     232            ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true));
     233            osm.id = Long.parseLong(ret.trim());
     234            osm.version = 1;
     235        } catch(NumberFormatException e){
     236            throw new OsmTransferException(tr("unexpected format of id replied by the server, got ''{0}''", ret));
     237        }
    297238    }
    298239
     
    309250        if (version.equals("0.5")) {
    310251            // legacy mode does not return the new object version.
    311             sendRequest("PUT", which(osm)+"/" + osm.id, toXml(osm, true));
     252            sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.id, toXml(osm, true));
    312253        } else {
     254            String ret = null;
    313255            // normal mode (0.6 and up) returns new object version.
    314             osm.version = parseInt(sendRequest("PUT", which(osm)+"/" + osm.id, toXml(osm, true)));
     256            try {
     257                ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.id, toXml(osm, true));
     258                osm.version = Integer.parseInt(ret.trim());
     259            } catch(NumberFormatException e) {
     260                throw new OsmTransferException(tr("unexpected format of new version of modified primitive ''{0}'', got ''{1}''", osm.id, ret));
     261            }
    315262        }
    316263    }
     
    324271        initialize();
    325272        // legacy mode does not require payload. normal mode (0.6 and up) requires payload for version matching.
    326         sendRequest("DELETE", which(osm)+"/" + osm.id, version.equals("0.5") ? null : toXml(osm, false));
     273        sendRequest("DELETE", OsmPrimitiveType.from(osm).getAPIName()+"/" + osm.id, version.equals("0.5") ? null : toXml(osm, false));
    327274    }
    328275
     
    334281    public void createChangeset(String comment) throws OsmTransferException {
    335282        changeset = new Changeset();
    336         Main.pleaseWaitDlg.currentAction.setText(tr("Opening changeset..."));
     283        notifyStatusMessage(tr("Opening changeset..."));
    337284        Properties sysProp = System.getProperties();
    338285        Object ua = sysProp.get("http.agent");
     
    349296    public void stopChangeset() throws OsmTransferException {
    350297        initialize();
    351         Main.pleaseWaitDlg.currentAction.setText(tr("Closing changeset..."));
     298        notifyStatusMessage(tr("Closing changeset..."));
    352299        sendRequest("PUT", "changeset" + "/" + changeset.id + "/close", null);
    353300        changeset = null;
     
    372319        CreateOsmChangeVisitor duv = new CreateOsmChangeVisitor(changeset, OsmApi.this);
    373320
     321        notifyStatusMessage(tr("Preparing..."));
    374322        for (OsmPrimitive osm : list) {
    375             int progress = Main.pleaseWaitDlg.progress.getValue();
    376             Main.pleaseWaitDlg.currentAction.setText(tr("Preparing..."));
    377323            osm.visit(duv);
    378             Main.pleaseWaitDlg.progress.setValue(progress+1);
    379         }
    380 
    381         Main.pleaseWaitDlg.currentAction.setText(tr("Uploading..."));
     324            notifyRelativeProgress(1);
     325        }
     326        notifyStatusMessage(tr("Uploading..."));
    382327
    383328        String diff = duv.getDocument();
     
    517462        }
    518463    }
     464
     465    /**
     466     * notifies any listeners about the current state of this API. Currently just
     467     * displays the message in the global progress dialog, see {@see Main#pleaseWaitDlg}
     468     *
     469     * @param message a status message.
     470     */
     471    protected void notifyStatusMessage(String message) {
     472        Main.pleaseWaitDlg.currentAction.setText(message);
     473    }
     474
     475    /**
     476     * notifies any listeners about the current about a relative progress. Currently just
     477     * increments the progress monitor in the in the global progress dialog, see {@see Main#pleaseWaitDlg}
     478     *
     479     * @param int the delta
     480     */
     481    protected void notifyRelativeProgress(int delta) {
     482        int current= Main.pleaseWaitDlg.progress.getValue();
     483        Main.pleaseWaitDlg.progress.setValue(current + delta);
     484    }
    519485}
  • trunk/src/org/openstreetmap/josm/io/OsmConnection.java

    r1523 r1670  
    2222
    2323import org.openstreetmap.josm.Main;
    24 import org.openstreetmap.josm.gui.ExtendedDialog; 
     24import org.openstreetmap.josm.gui.ExtendedDialog;
    2525import org.openstreetmap.josm.tools.Base64;
    2626import org.openstreetmap.josm.tools.GBC;
     
    3333 */
    3434public class OsmConnection {
    35 
    36     public static class OsmParseException extends Exception {
    37         public OsmParseException() {super();}
    38         public OsmParseException(String message, Throwable cause) {super(message, cause);}
    39         public OsmParseException(String message) {super(message);}
    40         public OsmParseException(Throwable cause) {super(cause);}
    41     }
    4235
    4336    protected boolean cancel = false;
     
    7770            if (passwordtried || username.equals("") || password.equals("")) {
    7871                JPanel p = new JPanel(new GridBagLayout());
    79                 if (!username.equals("") && !password.equals(""))
     72                if (!username.equals("") && !password.equals("")) {
    8073                    p.add(new JLabel(tr("Incorrect password or username.")), GBC.eop());
     74                }
    8175                p.add(new JLabel(tr("Username")), GBC.std().insets(0,0,10,0));
    8276                JTextField usernameField = new JTextField(username, 20);
     
    9286                p.add(savePassword, GBC.eop());
    9387
    94                 int choice = new ExtendedDialog(Main.parent, 
    95                         tr("Enter Password"), 
     88                int choice = new ExtendedDialog(Main.parent,
     89                        tr("Enter Password"),
    9690                        p,
    97                         new String[] {tr("Login"), tr("Cancel")}, 
    98                         new String[] {"ok.png", "cancel.png"}).getValue(); 
    99                
     91                        new String[] {tr("Login"), tr("Cancel")},
     92                        new String[] {"ok.png", "cancel.png"}).getValue();
     93
    10094                if (choice != 1) {
    10195                    authCancelled = true;
  • trunk/src/org/openstreetmap/josm/io/OsmServerLocationReader.java

    r1523 r1670  
    2222     * Method to download OSM files from somewhere
    2323     */
    24     public DataSet parseOsm() throws SAXException, IOException {
     24    @Override
     25    public DataSet parseOsm() throws OsmTransferException {
    2526        try {
    2627            Main.pleaseWaitDlg.progress.setValue(0);
     
    3233            Main.pleaseWaitDlg.currentAction.setText(tr("Downloading OSM data..."));
    3334            final DataSet data = OsmReader.parseDataSet(in, null, Main.pleaseWaitDlg);
    34 //          Bounds bounds = new Bounds(new LatLon(lat1, lon1), new LatLon(lat2, lon2));
    35 //          DataSource src = new DataSource(bounds, origin);
    36 //          data.dataSources.add(src);
    3735            in.close();
    3836            activeConnection = null;
     
    4139            if (cancel)
    4240                return null;
    43             throw e;
     41            throw new OsmTransferException(e);
    4442        } catch (SAXException e) {
     43            throw new OsmTransferException(e);
     44        } catch(OsmTransferException e) {
    4545            throw e;
    4646        } catch (Exception e) {
    4747            if (cancel)
    4848                return null;
    49             if (e instanceof RuntimeException)
    50                 throw (RuntimeException)e;
    51             throw new RuntimeException(e);
     49            throw new OsmTransferException(e);
    5250        }
    5351    }
  • trunk/src/org/openstreetmap/josm/io/OsmServerObjectReader.java

    r1523 r1670  
    77import java.io.InputStream;
    88
     9import javax.swing.JOptionPane;
     10
    911import org.openstreetmap.josm.Main;
    1012import org.openstreetmap.josm.data.osm.DataSet;
     13import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
    1114import org.xml.sax.SAXException;
    12 
    13 import javax.swing.JOptionPane;
    1415
    1516public class OsmServerObjectReader extends OsmServerReader {
    1617
    17     public final static  String TYPE_WAY = "way";
    18     public final static  String TYPE_REL = "relation";
    19     public final static  String TYPE_NODE = "node";
    20 
    2118    long id;
    22     String type;
     19    OsmPrimitiveType type;
    2320    boolean full;
    2421
    25     public OsmServerObjectReader(long id, String type, boolean full) {
     22    public OsmServerObjectReader(long id, OsmPrimitiveType type, boolean full) {
    2623        this.id = id;
    2724        this.type = type;
     
    3431     * @throws IOException
    3532     */
    36     public DataSet parseOsm() throws SAXException, IOException {
     33    @Override
     34    public DataSet parseOsm() throws OsmTransferException {
    3735        try {
    3836            Main.pleaseWaitDlg.progress.setValue(0);
    3937            Main.pleaseWaitDlg.currentAction.setText(tr("Contacting OSM Server..."));
    4038            StringBuffer sb = new StringBuffer();
    41             sb.append(type);
     39            sb.append(type.getAPIName());
    4240            sb.append("/");
    4341            sb.append(id);
    44             if (full)
     42            if (full && ! type.equals(OsmPrimitiveType.NODE)) {
    4543                sb.append("/full");
     44            }
    4645
    4746            final InputStream in = getInputStream(sb.toString(), Main.pleaseWaitDlg);
     
    5251            final DataSet data = osm.getDs();
    5352
    54 //          Bounds bounds = new Bounds(new LatLon(lat1, lon1), new LatLon(lat2, lon2));
    55 //          DataSource src = new DataSource(bounds, origin);
    56 //          data.dataSources.add(src);
    5753            if (osm.getParseNotes().length() != 0) {
    5854                JOptionPane.showMessageDialog(Main.parent, osm.getParseNotes());
     
    6460            if (cancel)
    6561                return null;
    66             throw e;
     62            throw new OsmTransferException(e);
    6763        } catch (SAXException e) {
     64            throw new OsmTransferException(e);
     65        } catch(OsmTransferException e) {
    6866            throw e;
    6967        } catch (Exception e) {
    7068            if (cancel)
    7169                return null;
    72             if (e instanceof RuntimeException)
    73                 throw (RuntimeException)e;
    74             throw new RuntimeException(e);
     70            throw new OsmTransferException(e);
    7571        }
    7672    }
  • trunk/src/org/openstreetmap/josm/io/OsmServerReader.java

    r1664 r1670  
    44import static org.openstreetmap.josm.tools.I18n.tr;
    55
    6 import java.io.IOException;
     6import java.io.BufferedReader;
    77import java.io.InputStream;
     8import java.io.InputStreamReader;
    89import java.net.HttpURLConnection;
     10import java.net.MalformedURLException;
    911import java.net.URL;
     12import java.util.zip.GZIPInputStream;
    1013import java.util.zip.Inflater;
    1114import java.util.zip.InflaterInputStream;
    12 import java.util.zip.GZIPInputStream;
    1315
    1416import javax.swing.JOptionPane;
     
    1719import org.openstreetmap.josm.data.osm.DataSet;
    1820import org.openstreetmap.josm.gui.PleaseWaitDialog;
    19 import org.xml.sax.SAXException;
    2021
    2122/**
     
    3940     * @return An reader reading the input stream (servers answer) or <code>null</code>.
    4041     */
    41     protected InputStream getInputStream(String urlStr, PleaseWaitDialog pleaseWaitDlg) throws IOException {
    42 
    43         // initialize API. Abort download in case of configuration or network
    44         // errors
    45         //
    46         try {
    47             api.initialize();
    48         } catch(Exception e) {
    49             JOptionPane.showMessageDialog(
    50                     null,
    51                     tr(   "Failed to initialize communication with the OSM server {0}.\n"
    52                             + "Check the server URL in your preferences and your internet connection.",
    53                             Main.pref.get("osm-server.url")
    54                     ),
    55                     tr("Error"),
    56                     JOptionPane.ERROR_MESSAGE
    57             );
    58             e.printStackTrace();
    59             return null;
    60         }
    61 
     42    protected InputStream getInputStream(String urlStr, PleaseWaitDialog pleaseWaitDlg) throws OsmTransferException  {
     43        api.initialize();
    6244        urlStr = api.getBaseUrl() + urlStr;
    6345        return getInputStreamRaw(urlStr, pleaseWaitDlg);
    6446    }
    6547
    66     protected InputStream getInputStreamRaw(String urlStr, PleaseWaitDialog pleaseWaitDlg) throws IOException {
    67 
    68         //        System.out.println("download: "+urlStr);
    69         URL url = new URL(urlStr);
    70         activeConnection = (HttpURLConnection)url.openConnection();
     48    protected InputStream getInputStreamRaw(String urlStr, PleaseWaitDialog pleaseWaitDlg) throws OsmTransferException {
     49        URL url = null;
     50        try {
     51            url = new URL(urlStr);
     52        } catch(MalformedURLException e) {
     53            throw new OsmTransferException(e);
     54        }
     55        try {
     56            activeConnection = (HttpURLConnection)url.openConnection();
     57        } catch(Exception e) {
     58            throw new OsmTransferException(tr("Failed to open connection to API {0}", url.toExternalForm()), e);
     59        }
    7160        if (cancel) {
    7261            activeConnection.disconnect();
     
    8170
    8271        try {
     72            System.out.println("GET " + url);
    8373            activeConnection.connect();
     74        } catch (Exception e) {
     75            throw new OsmTransferException(tr("Couldn't connect to the osm server. Please check your internet connection."), e);
    8476        }
    85         catch (Exception e) {
    86             throw new IOException(tr("Couldn't connect to the osm server. Please check your internet connection."));
     77        try {
     78            if (isAuthCancelled() && activeConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
     79                throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED,null,null);
     80
     81            if (activeConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
     82                String errorHeader = activeConnection.getHeaderField("Error");
     83                InputStream i = null;
     84                i = activeConnection.getErrorStream();
     85                StringBuilder errorBody = new StringBuilder();
     86                if (i != null) {
     87                    BufferedReader in = new BufferedReader(new InputStreamReader(i));
     88                    String s;
     89                    while((s = in.readLine()) != null) {
     90                        errorBody.append(s);
     91                        errorBody.append("\n");
     92                    }
     93                }
     94
     95                throw new OsmApiException(activeConnection.getResponseCode(), errorHeader, errorBody.toString());
     96            }
     97
     98            String encoding = activeConnection.getContentEncoding();
     99            InputStream inputStream = new ProgressInputStream(activeConnection, pleaseWaitDlg);
     100            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
     101                inputStream = new GZIPInputStream(inputStream);
     102            }
     103            else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
     104                inputStream = new InflaterInputStream(inputStream, new Inflater(true));
     105            }
     106            return inputStream;
     107        } catch(Exception e) {
     108            if (e instanceof OsmTransferException)
     109                throw (OsmTransferException)e;
     110            else
     111                throw new OsmTransferException(e);
     112
    87113        }
    88 
    89         if (isAuthCancelled() && activeConnection.getResponseCode() == 401)
    90             return null;
    91         if (activeConnection.getResponseCode() == 500)
    92             throw new IOException(tr("Server returned internal error. Try a reduced area or retry after waiting some time."));
    93 
    94         String encoding = activeConnection.getContentEncoding();
    95         InputStream inputStream = new ProgressInputStream(activeConnection, pleaseWaitDlg);
    96         if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
    97             inputStream = new GZIPInputStream(inputStream);
    98         }
    99         else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
    100             inputStream = new InflaterInputStream(inputStream, new Inflater(true));
    101         }
    102         return inputStream;
    103114    }
    104115
    105     public abstract DataSet parseOsm() throws SAXException, IOException;
     116    public abstract DataSet parseOsm() throws OsmTransferException;
    106117
    107118}
  • trunk/src/org/openstreetmap/josm/io/OsmServerWriter.java

    r1664 r1670  
    101101        boolean useChangeset = Main.pref.getBoolean("osm-server.atomic-upload", apiVersion.compareTo("0.6")>=0);
    102102        if (useChangeset && ! canUseChangeset) {
    103             System.out.println(tr("WARNING: preference '{0}' or api version {1} of dataset requires to use changesets, but API is not handle them. Ignoring changesets.", "osm-server.atomic-upload", apiVersion));
     103            System.out.println(tr("WARNING: preference ''{0}'' or api version ''{1}'' of dataset requires to use changesets, but API is not handle them. Ignoring changesets.", "osm-server.atomic-upload", apiVersion));
    104104            useChangeset = false;
    105105        }
  • trunk/src/org/openstreetmap/josm/io/OsmWriter.java

    r1640 r1670  
    1111import org.openstreetmap.josm.data.osm.Node;
    1212import org.openstreetmap.josm.data.osm.OsmPrimitive;
     13import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
    1314import org.openstreetmap.josm.data.osm.Relation;
    1415import org.openstreetmap.josm.data.osm.RelationMember;
     
    2526
    2627    public final String DEFAULT_API_VERSION = "0.6";
    27    
     28
    2829    /**
    2930     * The counter for newly created objects. Starts at -1 and goes down.
    3031     */
    3132    private long newIdCounter = -1;
    32  
     33
    3334    /**
    3435     * All newly created ids and their primitive that uses it. This is a back reference
     
    4142    private String version;
    4243    private Changeset changeset;
    43    
     44
    4445    public OsmWriter(PrintWriter out, boolean osmConform, String version) {
    4546        super(out);
     
    4748        this.version = (version == null ? DEFAULT_API_VERSION : version);
    4849    }
    49    
     50
    5051    public void setWithBody(boolean wb) {
    5152        this.withBody = wb;
     
    5758        this.version = v;
    5859    }
    59    
     60
    6061    public void header() {
    6162        out.println("<?xml version='1.0' encoding='UTF-8'?>");
     
    7071    public void writeContent(DataSet ds) {
    7172        for (Node n : ds.nodes)
    72             if (shouldWrite(n))
     73            if (shouldWrite(n)) {
    7374                visit(n);
     75            }
    7476        for (Way w : ds.ways)
    75             if (shouldWrite(w))
     77            if (shouldWrite(w)) {
    7678                visit(w);
     79            }
    7780        for (Relation e : ds.relations)
    78             if (shouldWrite(e))
     81            if (shouldWrite(e)) {
    7982                visit(e);
     83            }
    8084    }
    8185
     
    100104        out.print(" lat='"+n.getCoor().lat()+"' lon='"+n.getCoor().lon()+"'");
    101105        if (!withBody) {
    102             out.println("/>"); 
     106            out.println("/>");
    103107        } else {
    104108            addTags(n, "node", true);
     
    110114        addCommon(w, "way");
    111115        if (!withBody) {
    112             out.println("/>"); 
     116            out.println("/>");
    113117        } else {
    114118            out.println(">");
    115             for (Node n : w.nodes)
     119            for (Node n : w.nodes) {
    116120                out.println("    <nd ref='"+getUsedId(n)+"' />");
     121            }
    117122            addTags(w, "way", false);
    118123        }
     
    123128        addCommon(e, "relation");
    124129        if (!withBody) {
    125             out.println("/>"); 
     130            out.println("/>");
    126131        } else {
    127132            out.println(">");
    128133            for (RelationMember em : e.members) {
    129134                out.print("    <member type='");
    130                 out.print(OsmApi.which(em.member));
     135                out.print(OsmPrimitiveType.from(em.member).getAPIName());
    131136                out.println("' ref='"+getUsedId(em.member)+"' role='" +
    132137                        XmlWriter.encode(em.role == null ? "" : em.role) + "' />");
     
    160165    private void addTags(OsmPrimitive osm, String tagname, boolean tagOpen) {
    161166        if (osm.keys != null) {
    162             if (tagOpen)
     167            if (tagOpen) {
    163168                out.println(">");
    164             for (Entry<String, String> e : osm.keys.entrySet())
     169            }
     170            for (Entry<String, String> e : osm.keys.entrySet()) {
    165171                out.println("    <tag k='"+ XmlWriter.encode(e.getKey()) +
    166172                        "' v='"+XmlWriter.encode(e.getValue())+ "' />");
     173            }
    167174            out.println("  </" + tagname + ">");
    168         } else if (tagOpen)
     175        } else if (tagOpen) {
    169176            out.println(" />");
    170         else
     177        } else {
    171178            out.println("  </" + tagname + ">");
     179        }
    172180    }
    173181
     
    180188        out.print("  <"+tagname);
    181189        if (id != 0) {
    182              out.print(" id='"+getUsedId(osm)+"'");
     190            out.print(" id='"+getUsedId(osm)+"'");
    183191        }
    184192        if (!osmConform) {
    185193            String action = null;
    186             if (osm.deleted)
     194            if (osm.deleted) {
    187195                action = "delete";
    188             else if (osm.modified)
     196            } else if (osm.modified) {
    189197                action = "modify";
    190             if (action != null)
     198            }
     199            if (action != null) {
    191200                out.print(" action='"+action+"'");
     201            }
    192202        }
    193203        if (!osm.isTimestampEmpty()) {
     
    199209        }
    200210        out.print(" visible='"+osm.visible+"'");
    201         if (osm.version != -1)
     211        if (osm.version != -1) {
    202212            out.print(" version='"+osm.version+"'");
    203         if (this.changeset != null && this.changeset.id != 0)
     213        }
     214        if (this.changeset != null && this.changeset.id != 0) {
    204215            out.print(" changeset='"+this.changeset.id+"'" );
    205     }
    206    
     216        }
     217    }
     218
    207219    public void close() {
    208220        out.close();
    209221    }
    210    
     222
    211223    public void flush() {
    212224        out.flush();
  • trunk/src/org/openstreetmap/josm/io/ProgressInputStream.java

    r1169 r1670  
    2222    private PleaseWaitDialog pleaseWaitDlg;
    2323
    24     public class OsmServerException extends IOException {
    25         private OsmServerException(String e) {
    26             super(e);
    27         }
    28     }
    29 
    30     public ProgressInputStream(URLConnection con, PleaseWaitDialog pleaseWaitDlg) throws IOException, OsmServerException {
     24    public ProgressInputStream(URLConnection con, PleaseWaitDialog pleaseWaitDlg) throws OsmTransferException {
    3125        this.connection = con;
    3226
     
    3529        } catch (IOException e) {
    3630            if (con.getHeaderField("Error") != null)
    37                 throw new OsmServerException(tr(con.getHeaderField("Error")));
    38             throw e;
     31                throw new OsmTransferException(tr(con.getHeaderField("Error")));
     32            throw new OsmTransferException(e);
    3933        }
    4034
     
    4337        if (pleaseWaitDlg == null)
    4438            return;
    45         if (contentLength > 0)
     39        if (contentLength > 0) {
    4640            pleaseWaitDlg.progress.setMaximum(contentLength);
    47         else
     41        } else {
    4842            pleaseWaitDlg.progress.setMaximum(0);
     43        }
    4944        pleaseWaitDlg.progress.setValue(0);
    5045    }
     
    5651    @Override public int read(byte[] b, int off, int len) throws IOException {
    5752        int read = in.read(b, off, len);
    58         if (read != -1)
     53        if (read != -1) {
    5954            advanceTicker(read);
     55        }
    6056        return read;
    6157    }
     
    6359    @Override public int read() throws IOException {
    6460        int read = in.read();
    65         if (read != -1)
     61        if (read != -1) {
    6662            advanceTicker(1);
     63        }
    6764        return read;
    6865    }
     
    7673            return;
    7774
    78         if (pleaseWaitDlg.progress.getMaximum() == 0 && connection.getContentLength() != -1)
     75        if (pleaseWaitDlg.progress.getMaximum() == 0 && connection.getContentLength() != -1) {
    7976            pleaseWaitDlg.progress.setMaximum(connection.getContentLength());
     77        }
    8078
    8179        readSoFar += amount;
     
    8987            String cur = pleaseWaitDlg.currentAction.getText();
    9088            int i = cur.indexOf(' ');
    91             if (i != -1)
     89            if (i != -1) {
    9290                cur = cur.substring(0, i) + progStr;
    93             else
     91            } else {
    9492                cur += progStr;
     93            }
    9594            pleaseWaitDlg.currentAction.setText(cur);
    9695        }
Note: See TracChangeset for help on using the changeset viewer.