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

Last change on this file since 3461 was 2990, checked in by jttt, 14 years ago

Fix some eclipse warnings

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