source: josm/trunk/src/org/openstreetmap/josm/gui/io/UploadPrimitivesTask.java@ 6248

Last change on this file since 6248 was 6248, checked in by Don-vip, 11 years ago

Rework console output:

  • new log level "error"
  • Replace nearly all calls to system.out and system.err to Main.(error|warn|info|debug)
  • Remove some unnecessary debug output
  • Some messages are modified (removal of "Info", "Warning", "Error" from the message itself -> notable i18n impact but limited to console error messages not seen by the majority of users, so that's ok)
  • Property svn:eol-style set to native
File size: 16.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.io;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.CheckParameterUtil.ensureParameterNotNull;
6import static org.openstreetmap.josm.tools.I18n.tr;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
9import java.io.IOException;
10import java.lang.reflect.InvocationTargetException;
11import java.util.HashSet;
12
13import javax.swing.JOptionPane;
14import javax.swing.SwingUtilities;
15
16import org.openstreetmap.josm.Main;
17import org.openstreetmap.josm.data.APIDataSet;
18import org.openstreetmap.josm.data.osm.Changeset;
19import org.openstreetmap.josm.data.osm.ChangesetCache;
20import org.openstreetmap.josm.data.osm.IPrimitive;
21import org.openstreetmap.josm.data.osm.Node;
22import org.openstreetmap.josm.data.osm.OsmPrimitive;
23import org.openstreetmap.josm.data.osm.Relation;
24import org.openstreetmap.josm.data.osm.Way;
25import org.openstreetmap.josm.gui.DefaultNameFormatter;
26import org.openstreetmap.josm.gui.HelpAwareOptionPane;
27import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
28import org.openstreetmap.josm.gui.Notification;
29import org.openstreetmap.josm.gui.layer.OsmDataLayer;
30import org.openstreetmap.josm.gui.progress.ProgressMonitor;
31import org.openstreetmap.josm.gui.util.GuiHelper;
32import org.openstreetmap.josm.io.ChangesetClosedException;
33import org.openstreetmap.josm.io.OsmApi;
34import org.openstreetmap.josm.io.OsmApiPrimitiveGoneException;
35import org.openstreetmap.josm.io.OsmServerWriter;
36import org.openstreetmap.josm.io.OsmTransferCanceledException;
37import org.openstreetmap.josm.io.OsmTransferException;
38import org.openstreetmap.josm.tools.ImageProvider;
39import org.xml.sax.SAXException;
40
41/**
42 * The task for uploading a collection of primitives
43 *
44 */
45public class UploadPrimitivesTask extends AbstractUploadTask {
46 private boolean uploadCanceled = false;
47 private Exception lastException = null;
48 private APIDataSet toUpload;
49 private OsmServerWriter writer;
50 private OsmDataLayer layer;
51 private Changeset changeset;
52 private HashSet<IPrimitive> processedPrimitives;
53 private UploadStrategySpecification strategy;
54
55 /**
56 * Creates the task
57 *
58 * @param strategy the upload strategy. Must not be null.
59 * @param layer the OSM data layer for which data is uploaded. Must not be null.
60 * @param toUpload the collection of primitives to upload. Set to the empty collection if null.
61 * @param changeset the changeset to use for uploading. Must not be null. changeset.getId()
62 * can be 0 in which case the upload task creates a new changeset
63 * @throws IllegalArgumentException thrown if layer is null
64 * @throws IllegalArgumentException thrown if toUpload is null
65 * @throws IllegalArgumentException thrown if strategy is null
66 * @throws IllegalArgumentException thrown if changeset is null
67 */
68 public UploadPrimitivesTask(UploadStrategySpecification strategy, OsmDataLayer layer, APIDataSet toUpload, Changeset changeset) {
69 super(tr("Uploading data for layer ''{0}''", layer.getName()),false /* don't ignore exceptions */);
70 ensureParameterNotNull(layer,"layer");
71 ensureParameterNotNull(strategy, "strategy");
72 ensureParameterNotNull(changeset, "changeset");
73 this.toUpload = toUpload;
74 this.layer = layer;
75 this.changeset = changeset;
76 this.strategy = strategy;
77 this.processedPrimitives = new HashSet<IPrimitive>();
78 }
79
80 protected MaxChangesetSizeExceededPolicy askMaxChangesetSizeExceedsPolicy() {
81 ButtonSpec[] specs = new ButtonSpec[] {
82 new ButtonSpec(
83 tr("Continue uploading"),
84 ImageProvider.get("upload"),
85 tr("Click to continue uploading to additional new changesets"),
86 null /* no specific help text */
87 ),
88 new ButtonSpec(
89 tr("Go back to Upload Dialog"),
90 ImageProvider.get("dialogs", "uploadproperties"),
91 tr("Click to return to the Upload Dialog"),
92 null /* no specific help text */
93 ),
94 new ButtonSpec(
95 tr("Abort"),
96 ImageProvider.get("cancel"),
97 tr("Click to abort uploading"),
98 null /* no specific help text */
99 )
100 };
101 int numObjectsToUploadLeft = toUpload.getSize() - processedPrimitives.size();
102 String msg1 = tr("The server reported that the current changeset was closed.<br>"
103 + "This is most likely because the changesets size exceeded the max. size<br>"
104 + "of {0} objects on the server ''{1}''.",
105 OsmApi.getOsmApi().getCapabilities().getMaxChangesetSize(),
106 OsmApi.getOsmApi().getBaseUrl()
107 );
108 String msg2 = trn(
109 "There is {0} object left to upload.",
110 "There are {0} objects left to upload.",
111 numObjectsToUploadLeft,
112 numObjectsToUploadLeft
113 );
114 String msg3 = tr(
115 "Click ''<strong>{0}</strong>'' to continue uploading to additional new changesets.<br>"
116 + "Click ''<strong>{1}</strong>'' to return to the upload dialog.<br>"
117 + "Click ''<strong>{2}</strong>'' to abort uploading and return to map editing.<br>",
118 specs[0].text,
119 specs[1].text,
120 specs[2].text
121 );
122 String msg = "<html>" + msg1 + "<br><br>" + msg2 +"<br><br>" + msg3 + "</html>";
123 int ret = HelpAwareOptionPane.showOptionDialog(
124 Main.parent,
125 msg,
126 tr("Changeset is full"),
127 JOptionPane.WARNING_MESSAGE,
128 null, /* no special icon */
129 specs,
130 specs[0],
131 ht("/Action/Upload#ChangesetFull")
132 );
133 switch(ret) {
134 case 0: return MaxChangesetSizeExceededPolicy.AUTOMATICALLY_OPEN_NEW_CHANGESETS;
135 case 1: return MaxChangesetSizeExceededPolicy.FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG;
136 case 2: return MaxChangesetSizeExceededPolicy.ABORT;
137 case JOptionPane.CLOSED_OPTION: return MaxChangesetSizeExceededPolicy.ABORT;
138 }
139 // should not happen
140 return null;
141 }
142
143 protected void openNewChangeset() {
144 // make sure the current changeset is removed from the upload dialog.
145 //
146 ChangesetCache.getInstance().update(changeset);
147 Changeset newChangeSet = new Changeset();
148 newChangeSet.setKeys(this.changeset.getKeys());
149 this.changeset = newChangeSet;
150 }
151
152 protected boolean recoverFromChangesetFullException() {
153 if (toUpload.getSize() - processedPrimitives.size() == 0) {
154 strategy.setPolicy(MaxChangesetSizeExceededPolicy.ABORT);
155 return false;
156 }
157 if (strategy.getPolicy() == null || strategy.getPolicy().equals(MaxChangesetSizeExceededPolicy.ABORT)) {
158 MaxChangesetSizeExceededPolicy policy = askMaxChangesetSizeExceedsPolicy();
159 strategy.setPolicy(policy);
160 }
161 switch(strategy.getPolicy()) {
162 case ABORT:
163 // don't continue - finish() will send the user back to map editing
164 //
165 return false;
166 case FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG:
167 // don't continue - finish() will send the user back to the upload dialog
168 //
169 return false;
170 case AUTOMATICALLY_OPEN_NEW_CHANGESETS:
171 // prepare the state of the task for a next iteration in uploading.
172 //
173 openNewChangeset();
174 toUpload.removeProcessed(processedPrimitives);
175 return true;
176 }
177 // should not happen
178 return false;
179 }
180
181 /**
182 * Retries to recover the upload operation from an exception which was thrown because
183 * an uploaded primitive was already deleted on the server.
184 *
185 * @param e the exception throw by the API
186 * @param monitor a progress monitor
187 * @throws OsmTransferException thrown if we can't recover from the exception
188 */
189 protected void recoverFromGoneOnServer(OsmApiPrimitiveGoneException e, ProgressMonitor monitor) throws OsmTransferException{
190 if (!e.isKnownPrimitive()) throw e;
191 OsmPrimitive p = layer.data.getPrimitiveById(e.getPrimitiveId(), e.getPrimitiveType());
192 if (p == null) throw e;
193 if (p.isDeleted()) {
194 // we tried to delete an already deleted primitive.
195 final String msg;
196 final String displayName = p.getDisplayName(DefaultNameFormatter.getInstance());
197 if (p instanceof Node) {
198 msg = tr("Node ''{0}'' is already deleted. Skipping object in upload.", displayName);
199 } else if (p instanceof Way) {
200 msg = tr("Way ''{0}'' is already deleted. Skipping object in upload.", displayName);
201 } else if (p instanceof Relation) {
202 msg = tr("Relation ''{0}'' is already deleted. Skipping object in upload.", displayName);
203 } else {
204 msg = tr("Object ''{0}'' is already deleted. Skipping object in upload.", displayName);
205 }
206 monitor.appendLogMessage(msg);
207 Main.warn(msg);
208 processedPrimitives.addAll(writer.getProcessedPrimitives());
209 processedPrimitives.add(p);
210 toUpload.removeProcessed(processedPrimitives);
211 return;
212 }
213 // exception was thrown because we tried to *update* an already deleted
214 // primitive. We can't resolve this automatically. Re-throw exception,
215 // a conflict is going to be created later.
216 throw e;
217 }
218
219 protected void cleanupAfterUpload() {
220 // we always clean up the data, even in case of errors. It's possible the data was
221 // partially uploaded. Better run on EDT.
222 //
223 Runnable r = new Runnable() {
224 @Override
225 public void run() {
226 layer.cleanupAfterUpload(processedPrimitives);
227 layer.onPostUploadToServer();
228 ChangesetCache.getInstance().update(changeset);
229 }
230 };
231
232 try {
233 SwingUtilities.invokeAndWait(r);
234 } catch(InterruptedException e) {
235 lastException = e;
236 } catch(InvocationTargetException e) {
237 lastException = new OsmTransferException(e.getCause());
238 }
239 }
240
241 @Override protected void realRun() throws SAXException, IOException {
242 try {
243 uploadloop:while(true) {
244 try {
245 getProgressMonitor().subTask(trn("Uploading {0} object...", "Uploading {0} objects...", toUpload.getSize(), toUpload.getSize()));
246 synchronized(this) {
247 writer = new OsmServerWriter();
248 }
249 writer.uploadOsm(strategy, toUpload.getPrimitives(), changeset, getProgressMonitor().createSubTaskMonitor(1, false));
250
251 // if we get here we've successfully uploaded the data. Exit the loop.
252 //
253 break;
254 } catch(OsmTransferCanceledException e) {
255 e.printStackTrace();
256 uploadCanceled = true;
257 break uploadloop;
258 } catch(OsmApiPrimitiveGoneException e) {
259 // try to recover from 410 Gone
260 //
261 recoverFromGoneOnServer(e, getProgressMonitor());
262 } catch(ChangesetClosedException e) {
263 processedPrimitives.addAll(writer.getProcessedPrimitives()); // OsmPrimitive in => OsmPrimitive out
264 changeset.setOpen(false);
265 switch(e.getSource()) {
266 case UNSPECIFIED:
267 throw e;
268 case UPDATE_CHANGESET:
269 // The changeset was closed when we tried to update it. Probably, our
270 // local list of open changesets got out of sync with the server state.
271 // The user will have to select another open changeset.
272 // Rethrow exception - this will be handled later.
273 //
274 throw e;
275 case UPLOAD_DATA:
276 // Most likely the changeset is full. Try to recover and continue
277 // with a new changeset, but let the user decide first (see
278 // recoverFromChangesetFullException)
279 //
280 if (recoverFromChangesetFullException()) {
281 continue;
282 }
283 lastException = e;
284 break uploadloop;
285 }
286 } finally {
287 if (writer != null) {
288 processedPrimitives.addAll(writer.getProcessedPrimitives());
289 }
290 synchronized(this) {
291 writer = null;
292 }
293 }
294 }
295 // if required close the changeset
296 //
297 if (strategy.isCloseChangesetAfterUpload() && changeset != null && !changeset.isNew() && changeset.isOpen()) {
298 OsmApi.getOsmApi().closeChangeset(changeset, progressMonitor.createSubTaskMonitor(0, false));
299 }
300 } catch (Exception e) {
301 if (uploadCanceled) {
302 Main.info(tr("Ignoring caught exception because upload is canceled. Exception is: {0}", e.toString()));
303 } else {
304 lastException = e;
305 }
306 }
307 if (uploadCanceled && processedPrimitives.isEmpty()) return;
308 cleanupAfterUpload();
309 }
310
311 @Override protected void finish() {
312 if (uploadCanceled)
313 return;
314
315 // depending on the success of the upload operation and on the policy for
316 // multi changeset uploads this will sent the user back to the appropriate
317 // place in JOSM, either
318 // - to an error dialog
319 // - to the Upload Dialog
320 // - to map editing
321 GuiHelper.runInEDT(new Runnable() {
322 @Override
323 public void run() {
324 // if the changeset is still open after this upload we want it to
325 // be selected on the next upload
326 //
327 ChangesetCache.getInstance().update(changeset);
328 if (changeset != null && changeset.isOpen()) {
329 UploadDialog.getUploadDialog().setSelectedChangesetForNextUpload(changeset);
330 }
331 if (lastException == null) {
332 new Notification(
333 "<h3>" + tr("Upload successful!") + "</h3>")
334 .setIcon(ImageProvider.get("misc", "check_large"))
335 .show();
336 return;
337 }
338 if (lastException instanceof ChangesetClosedException) {
339 ChangesetClosedException e = (ChangesetClosedException)lastException;
340 if (e.getSource().equals(ChangesetClosedException.Source.UPDATE_CHANGESET)) {
341 handleFailedUpload(lastException);
342 return;
343 }
344 if (strategy.getPolicy() == null)
345 /* do nothing if unknown policy */
346 return;
347 if (e.getSource().equals(ChangesetClosedException.Source.UPLOAD_DATA)) {
348 switch(strategy.getPolicy()) {
349 case ABORT:
350 break; /* do nothing - we return to map editing */
351 case AUTOMATICALLY_OPEN_NEW_CHANGESETS:
352 break; /* do nothing - we return to map editing */
353 case FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG:
354 // return to the upload dialog
355 //
356 toUpload.removeProcessed(processedPrimitives);
357 UploadDialog.getUploadDialog().setUploadedPrimitives(toUpload);
358 UploadDialog.getUploadDialog().setVisible(true);
359 break;
360 }
361 } else {
362 handleFailedUpload(lastException);
363 }
364 } else {
365 handleFailedUpload(lastException);
366 }
367 }
368 });
369 }
370
371 @Override protected void cancel() {
372 uploadCanceled = true;
373 synchronized(this) {
374 if (writer != null) {
375 writer.cancel();
376 }
377 }
378 }
379}
Note: See TracBrowser for help on using the repository browser.