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

Last change on this file since 10616 was 10611, checked in by Don-vip, 8 years ago

see #11390 - sonar - squid:S1604 - Java 8: Anonymous inner classes containing only one method should become lambdas

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