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

Last change on this file since 2719 was 2711, checked in by stoecker, 14 years ago

fix bad line endings

  • Property svn:eol-style set to native
File size: 10.1 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 } catch(Exception e) {
124 throw new OsmTransferException(e);
125 } finally {
126 progressMonitor.finishTask();
127 }
128 }
129
130 /**
131 * Upload all changes in one diff upload
132 *
133 * @param primitives the collection of primitives to upload
134 * @param progressMonitor the progress monitor
135 * @param chunkSize the size of the individual upload chunks. > 0 required.
136 * @throws IllegalArgumentException thrown if chunkSize <= 0
137 * @throws OsmTransferException thrown if an exception occurs
138 */
139 protected void uploadChangesInChunks(Collection<OsmPrimitive> primitives, ProgressMonitor progressMonitor, int chunkSize) throws OsmTransferException, IllegalArgumentException {
140 if (chunkSize <=0)
141 throw new IllegalArgumentException(tr("Value >0 expected for parameter ''{0}'', got {1}", "chunkSize", chunkSize));
142 try {
143 progressMonitor.beginTask(tr("Starting to upload in chunks..."));
144 List<OsmPrimitive> chunk = new ArrayList<OsmPrimitive>(chunkSize);
145 Iterator<OsmPrimitive> it = primitives.iterator();
146 int numChunks = (int)Math.ceil((double)primitives.size() / (double)chunkSize);
147 int i= 0;
148 while(it.hasNext()) {
149 i++;
150 if (canceled) return;
151 int j = 0;
152 chunk.clear();
153 while(it.hasNext() && j < chunkSize) {
154 if (canceled) return;
155 j++;
156 chunk.add(it.next());
157 }
158 progressMonitor.setCustomText(tr("({0}/{1}) Uploading {2} objects...", i,numChunks,chunk.size()));
159 processed.addAll(api.uploadDiff(chunk, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)));
160 }
161 } catch(OsmTransferException e) {
162 throw e;
163 } catch(Exception e) {
164 throw new OsmTransferException(e);
165 } finally {
166 progressMonitor.finishTask();
167 }
168 }
169
170 /**
171 * Send the dataset to the server.
172 *
173 * @param strategy the upload strategy. Must not be null.
174 * @param primitives list of objects to send
175 * @param changeset the changeset the data is uploaded to. Must not be null.
176 * @param monitor the progress monitor. If null, assumes {@see NullProgressMonitor#INSTANCE}
177 * @throws IllegalArgumentException thrown if changeset is null
178 * @throws IllegalArgumentException thrown if strategy is null
179 * @throws OsmTransferException thrown if something goes wrong
180 */
181 public void uploadOsm(UploadStrategySpecification strategy, Collection<OsmPrimitive> primitives, Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
182 if (changeset == null)
183 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be null", "changeset"));
184 processed = new LinkedList<OsmPrimitive>();
185 monitor = monitor == null ? NullProgressMonitor.INSTANCE : monitor;
186 monitor.beginTask(tr("Uploading data ..."));
187 try {
188 api.initialize(monitor);
189 // check whether we can use diff upload
190 if (changeset.getId() == 0) {
191 api.openChangeset(changeset,monitor.createSubTaskMonitor(0, false));
192 } else {
193 api.updateChangeset(changeset,monitor.createSubTaskMonitor(0, false));
194 }
195 api.setChangeset(changeset);
196 switch(strategy.getStrategy()) {
197 case SINGLE_REQUEST_STRATEGY:
198 uploadChangesAsDiffUpload(primitives,monitor.createSubTaskMonitor(0,false));
199 break;
200 case INDIVIDUAL_OBJECTS_STRATEGY:
201 uploadChangesIndividually(primitives,monitor.createSubTaskMonitor(0,false));
202 break;
203 case CHUNKED_DATASET_STRATEGY:
204 uploadChangesInChunks(primitives,monitor.createSubTaskMonitor(0,false), strategy.getChunkSize());
205 break;
206 }
207 } catch(OsmTransferException e) {
208 throw e;
209 } catch(Exception e) {
210 throw new OsmTransferException(e);
211 } finally {
212 monitor.finishTask();
213 api.setChangeset(null);
214 }
215 }
216
217 void makeApiRequest(OsmPrimitive osm, ProgressMonitor progressMonitor) throws OsmTransferException {
218 if (osm.isDeleted()) {
219 api.deletePrimitive(osm, progressMonitor);
220 } else if (osm.isNew()) {
221 api.createPrimitive(osm, progressMonitor);
222 } else {
223 api.modifyPrimitive(osm,progressMonitor);
224 }
225 }
226
227 public void cancel() {
228 this.canceled = true;
229 if (api != null) {
230 api.cancel();
231 }
232 }
233
234 /**
235 * Replies the collection of successfully processed primitives
236 *
237 * @return the collection of successfully processed primitives
238 */
239 public Collection<OsmPrimitive> getProcessedPrimitives() {
240 return processed;
241 }
242}
Note: See TracBrowser for help on using the repository browser.