source: josm/trunk/src/org/openstreetmap/josm/io/OsmServerWriter.java@ 2828

Last change on this file since 2828 was 2825, checked in by Gubaer, 14 years ago

fixed #4328: No visible error message when trying to upload to a closed changeset

  • Property svn:eol-style set to native
File size: 9.9 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.util.ArrayList;
8import java.util.Collection;
9import java.util.Iterator;
10import java.util.LinkedList;
11import java.util.List;
12import java.util.logging.Logger;
13
14import org.openstreetmap.josm.data.osm.Changeset;
15import org.openstreetmap.josm.data.osm.OsmPrimitive;
16import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
17import org.openstreetmap.josm.gui.io.UploadStrategySpecification;
18import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
19import org.openstreetmap.josm.gui.progress.ProgressMonitor;
20
21/**
22 * Class that uploads all changes to the osm server.
23 *
24 * This is done like this: - All objects with id = 0 are uploaded as new, except
25 * those in deleted, which are ignored - All objects in deleted list are
26 * deleted. - All remaining objects with modified flag set are updated.
27 */
28public class OsmServerWriter {
29 static private final Logger logger = Logger.getLogger(OsmServerWriter.class.getName());
30
31 /**
32 * This list contains all successfully processed objects. The caller of
33 * upload* has to check this after the call and update its dataset.
34 *
35 * If a server connection error occurs, this may contain fewer entries
36 * than where passed in the list to upload*.
37 */
38 private Collection<OsmPrimitive> processed;
39
40 private OsmApi api = OsmApi.getOsmApi();
41 private boolean canceled = false;
42
43 private static final int MSECS_PER_SECOND = 1000;
44 private static final int SECONDS_PER_MINUTE = 60;
45 private static final int MSECS_PER_MINUTE = MSECS_PER_SECOND * SECONDS_PER_MINUTE;
46
47 long uploadStartTime;
48
49 public String timeLeft(int progress, int list_size) {
50 long now = System.currentTimeMillis();
51 long elapsed = now - uploadStartTime;
52 if (elapsed == 0) {
53 elapsed = 1;
54 }
55 float uploads_per_ms = (float)progress / elapsed;
56 float uploads_left = list_size - progress;
57 int ms_left = (int)(uploads_left / uploads_per_ms);
58 int minutes_left = ms_left / MSECS_PER_MINUTE;
59 int seconds_left = (ms_left / MSECS_PER_SECOND) % SECONDS_PER_MINUTE ;
60 String time_left_str = Integer.toString(minutes_left) + ":";
61 if (seconds_left < 10) {
62 time_left_str += "0";
63 }
64 time_left_str += Integer.toString(seconds_left);
65 return time_left_str;
66 }
67
68 /**
69 * Uploads the changes individually. Invokes one API call per uploaded primitmive.
70 *
71 * @param primitives the collection of primitives to upload
72 * @param progressMonitor the progress monitor
73 * @throws OsmTransferException thrown if an exception occurs
74 */
75 protected void uploadChangesIndividually(Collection<OsmPrimitive> primitives, ProgressMonitor progressMonitor) throws OsmTransferException {
76 try {
77 progressMonitor.beginTask(tr("Starting to upload with one request per primitive ..."));
78 progressMonitor.setTicksCount(primitives.size());
79 uploadStartTime = System.currentTimeMillis();
80 for (OsmPrimitive osm : primitives) {
81 int progress = progressMonitor.getTicks();
82 String time_left_str = timeLeft(progress, primitives.size());
83 String msg = "";
84 switch(OsmPrimitiveType.from(osm)) {
85 case NODE: msg = marktr("{0}% ({1}/{2}), {3} left. Uploading node ''{4}'' (id: {5})"); break;
86 case WAY: msg = marktr("{0}% ({1}/{2}), {3} left. Uploading way ''{4}'' (id: {5})"); break;
87 case RELATION: msg = marktr("{0}% ({1}/{2}), {3} left. Uploading relation ''{4}'' (id: {5})"); break;
88 }
89 progressMonitor.subTask(
90 tr(msg,
91 Math.round(100.0*progress/primitives.size()),
92 progress,
93 primitives.size(),
94 time_left_str,
95 osm.getName() == null ? osm.getId() : osm.getName(),
96 osm.getId()));
97 makeApiRequest(osm,progressMonitor);
98 processed.add(osm);
99 progressMonitor.worked(1);
100 }
101 } catch(OsmTransferException e) {
102 throw e;
103 } catch(Exception e) {
104 throw new OsmTransferException(e);
105 } finally {
106 progressMonitor.finishTask();
107 }
108 }
109
110 /**
111 * Upload all changes in one diff upload
112 *
113 * @param primitives the collection of primitives to upload
114 * @param progressMonitor the progress monitor
115 * @throws OsmTransferException thrown if an exception occurs
116 */
117 protected void uploadChangesAsDiffUpload(Collection<OsmPrimitive> primitives, ProgressMonitor progressMonitor) throws OsmTransferException {
118 try {
119 progressMonitor.beginTask(tr("Starting to upload in one request ..."));
120 processed.addAll(api.uploadDiff(primitives, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)));
121 } catch(OsmTransferException e) {
122 throw e;
123 } finally {
124 progressMonitor.finishTask();
125 }
126 }
127
128 /**
129 * Upload all changes in one diff upload
130 *
131 * @param primitives the collection of primitives to upload
132 * @param progressMonitor the progress monitor
133 * @param chunkSize the size of the individual upload chunks. > 0 required.
134 * @throws IllegalArgumentException thrown if chunkSize <= 0
135 * @throws OsmTransferException thrown if an exception occurs
136 */
137 protected void uploadChangesInChunks(Collection<OsmPrimitive> primitives, ProgressMonitor progressMonitor, int chunkSize) throws OsmTransferException, IllegalArgumentException {
138 if (chunkSize <=0)
139 throw new IllegalArgumentException(tr("Value >0 expected for parameter ''{0}'', got {1}", "chunkSize", chunkSize));
140 try {
141 progressMonitor.beginTask(tr("Starting to upload in chunks..."));
142 List<OsmPrimitive> chunk = new ArrayList<OsmPrimitive>(chunkSize);
143 Iterator<OsmPrimitive> it = primitives.iterator();
144 int numChunks = (int)Math.ceil((double)primitives.size() / (double)chunkSize);
145 int i= 0;
146 while(it.hasNext()) {
147 i++;
148 if (canceled) return;
149 int j = 0;
150 chunk.clear();
151 while(it.hasNext() && j < chunkSize) {
152 if (canceled) return;
153 j++;
154 chunk.add(it.next());
155 }
156 progressMonitor.setCustomText(tr("({0}/{1}) Uploading {2} objects...", i,numChunks,chunk.size()));
157 processed.addAll(api.uploadDiff(chunk, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)));
158 }
159 } catch(OsmTransferException e) {
160 throw e;
161 } finally {
162 progressMonitor.finishTask();
163 }
164 }
165
166 /**
167 * Send the dataset to the server.
168 *
169 * @param strategy the upload strategy. Must not be null.
170 * @param primitives list of objects to send
171 * @param changeset the changeset the data is uploaded to. Must not be null.
172 * @param monitor the progress monitor. If null, assumes {@see NullProgressMonitor#INSTANCE}
173 * @throws IllegalArgumentException thrown if changeset is null
174 * @throws IllegalArgumentException thrown if strategy is null
175 * @throws OsmTransferException thrown if something goes wrong
176 */
177 public void uploadOsm(UploadStrategySpecification strategy, Collection<OsmPrimitive> primitives, Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
178 if (changeset == null)
179 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be null", "changeset"));
180 processed = new LinkedList<OsmPrimitive>();
181 monitor = monitor == null ? NullProgressMonitor.INSTANCE : monitor;
182 monitor.beginTask(tr("Uploading data ..."));
183 try {
184 api.initialize(monitor);
185 // check whether we can use diff upload
186 if (changeset.getId() == 0) {
187 api.openChangeset(changeset,monitor.createSubTaskMonitor(0, false));
188 } else {
189 api.updateChangeset(changeset,monitor.createSubTaskMonitor(0, false));
190 }
191 api.setChangeset(changeset);
192 switch(strategy.getStrategy()) {
193 case SINGLE_REQUEST_STRATEGY:
194 uploadChangesAsDiffUpload(primitives,monitor.createSubTaskMonitor(0,false));
195 break;
196 case INDIVIDUAL_OBJECTS_STRATEGY:
197 uploadChangesIndividually(primitives,monitor.createSubTaskMonitor(0,false));
198 break;
199 case CHUNKED_DATASET_STRATEGY:
200 uploadChangesInChunks(primitives,monitor.createSubTaskMonitor(0,false), strategy.getChunkSize());
201 break;
202 }
203 } catch(OsmTransferException e) {
204 throw e;
205 } finally {
206 monitor.finishTask();
207 api.setChangeset(null);
208 }
209 }
210
211 void makeApiRequest(OsmPrimitive osm, ProgressMonitor progressMonitor) throws OsmTransferException {
212 if (osm.isDeleted()) {
213 api.deletePrimitive(osm, progressMonitor);
214 } else if (osm.isNew()) {
215 api.createPrimitive(osm, progressMonitor);
216 } else {
217 api.modifyPrimitive(osm,progressMonitor);
218 }
219 }
220
221 public void cancel() {
222 this.canceled = true;
223 if (api != null) {
224 api.cancel();
225 }
226 }
227
228 /**
229 * Replies the collection of successfully processed primitives
230 *
231 * @return the collection of successfully processed primitives
232 */
233 public Collection<OsmPrimitive> getProcessedPrimitives() {
234 return processed;
235 }
236}
Note: See TracBrowser for help on using the repository browser.