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

Last change on this file since 2025 was 2025, checked in by Gubaer, 15 years ago

new: improved dialog for uploading/saving modified layers on exit
new: improved dialog for uploading/saving modified layers if layers are deleted
new: new progress monitor which can delegate rendering to any Swing component
more setters/getters for properties in OSM data classes (fields are @deprecated); started to update references in the code base

  • Property svn:eol-style set to native
File size: 9.2 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.Collection;
8import java.util.LinkedList;
9import java.util.List;
10import java.util.logging.Logger;
11
12import org.openstreetmap.josm.Main;
13import org.openstreetmap.josm.actions.UploadAction;
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.progress.ProgressMonitor;
18
19/**
20 * Class that uploads all changes to the osm server.
21 *
22 * This is done like this: - All objects with id = 0 are uploaded as new, except
23 * those in deleted, which are ignored - All objects in deleted list are
24 * deleted. - All remaining objects with modified flag set are updated.
25 */
26public class OsmServerWriter {
27 static private final Logger logger = Logger.getLogger(OsmServerWriter.class.getName());
28
29 /**
30 * This list contains all successfully processed objects. The caller of
31 * upload* has to check this after the call and update its dataset.
32 *
33 * If a server connection error occurs, this may contain fewer entries
34 * than where passed in the list to upload*.
35 */
36 private Collection<OsmPrimitive> processed;
37
38 private OsmApi api = OsmApi.getOsmApi();
39
40 private static final int MSECS_PER_SECOND = 1000;
41 private static final int SECONDS_PER_MINUTE = 60;
42 private static final int MSECS_PER_MINUTE = MSECS_PER_SECOND * SECONDS_PER_MINUTE;
43
44 long uploadStartTime;
45
46 public String timeLeft(int progress, int list_size) {
47 long now = System.currentTimeMillis();
48 long elapsed = now - uploadStartTime;
49 if (elapsed == 0) {
50 elapsed = 1;
51 }
52 float uploads_per_ms = (float)progress / elapsed;
53 float uploads_left = list_size - progress;
54 int ms_left = (int)(uploads_left / uploads_per_ms);
55 int minutes_left = ms_left / MSECS_PER_MINUTE;
56 int seconds_left = (ms_left / MSECS_PER_SECOND) % SECONDS_PER_MINUTE ;
57 String time_left_str = Integer.toString(minutes_left) + ":";
58 if (seconds_left < 10) {
59 time_left_str += "0";
60 }
61 time_left_str += Integer.toString(seconds_left);
62 return time_left_str;
63 }
64
65 /**
66 * retrieves the most recent changeset comment from the preferences
67 *
68 * @return the most recent changeset comment
69 */
70 protected String getChangesetComment() {
71 String cmt = "";
72 List<String> history = new LinkedList<String>(
73 Main.pref.getCollection(UploadAction.HISTORY_KEY, new LinkedList<String>()));
74 if(history.size() > 0) {
75 cmt = history.get(0);
76 }
77 return cmt;
78 }
79
80 /**
81 * Uploads the changes individually. Invokes one API call per uploaded primitmive.
82 *
83 * @param primitives the collection of primitives to upload
84 * @param progressMonitor the progress monitor
85 * @throws OsmTransferException thrown if an exception occurs
86 */
87 protected void uploadChangesIndividually(Collection<OsmPrimitive> primitives, ProgressMonitor progressMonitor) throws OsmTransferException {
88 try {
89 progressMonitor.setTicksCount(primitives.size());
90 api.createChangeset(getChangesetComment(), progressMonitor.createSubTaskMonitor(0, false));
91 uploadStartTime = System.currentTimeMillis();
92 for (OsmPrimitive osm : primitives) {
93 int progress = progressMonitor.getTicks();
94 String time_left_str = timeLeft(progress, primitives.size());
95 String msg = "";
96 switch(OsmPrimitiveType.from(osm)) {
97 case NODE: msg = marktr("{0}% ({1}/{2}), {3} left. Uploading node ''{4}'' (id: {5})"); break;
98 case WAY: msg = marktr("{0}% ({1}/{2}), {3} left. Uploading way ''{4}'' (id: {5})"); break;
99 case RELATION: msg = marktr("{0}% ({1}/{2}), {3} left. Uploading relation ''{4}'' (id: {5})"); break;
100 }
101 progressMonitor.subTask(
102 tr(msg,
103 Math.round(100.0*progress/primitives.size()),
104 progress,
105 primitives.size(),
106 time_left_str,
107 osm.getName() == null ? osm.getId() : osm.getName(),
108 osm.getId()));
109 makeApiRequest(osm,progressMonitor);
110 processed.add(osm);
111 progressMonitor.worked(1);
112 }
113 } catch(OsmTransferException e) {
114 throw e;
115 } catch(Exception e) {
116 throw new OsmTransferException(e);
117 } finally {
118 try {
119 // starting the changeset may have failed, for instance because the user
120 // cancelled the upload task. Only close the changeset if we currently have
121 // an open changeset
122
123 if (api.getCurrentChangeset() != null && api.getCurrentChangeset().getId() > 0) {
124 api.stopChangeset(progressMonitor.createSubTaskMonitor(0, false));
125 }
126 } catch(Exception e) {
127 Changeset changeset = api.getCurrentChangeset();
128 String changesetId = (changeset == null ? tr("unknown") : Long.toString(changeset.getId()));
129 logger.warning(tr("Failed to close changeset {0}, will be closed by server after timeout. Exception was: {1}",
130 changesetId, e.toString()));
131 }
132 }
133 }
134
135 /**
136 * Upload all changes in one diff upload
137 *
138 * @param primitives the collection of primitives to upload
139 * @param progressMonitor the progress monitor
140 * @throws OsmTransferException thrown if an exception occurs
141 */
142 protected void uploadChangesAsDiffUpload(Collection<OsmPrimitive> primitives, ProgressMonitor progressMonitor) throws OsmTransferException {
143 // upload everything in one changeset
144 //
145 try {
146 api.createChangeset(getChangesetComment(), progressMonitor.createSubTaskMonitor(0, false));
147 processed.addAll(api.uploadDiff(primitives, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)));
148 } catch(OsmTransferException e) {
149 throw e;
150 } catch(Exception e) {
151 throw new OsmTransferException(e);
152 } finally {
153 try {
154 api.stopChangeset(progressMonitor.createSubTaskMonitor(0, false));
155 } catch (Exception ee) {
156 Changeset changeset = api.getCurrentChangeset();
157 String changesetId = (changeset == null ? tr("unknown") : Long.toString(changeset.getId()));
158 logger.warning(tr("Failed to close changeset {0}, will be closed by server after timeout. Exception was: {1}",
159 changesetId, ee.toString()));
160 }
161 }
162 }
163
164 /**
165 * Send the dataset to the server.
166 *
167 * @param apiVersion version of the data set
168 * @param primitives list of objects to send
169 */
170 public void uploadOsm(String apiVersion, Collection<OsmPrimitive> primitives, ProgressMonitor progressMonitor) throws OsmTransferException {
171 processed = new LinkedList<OsmPrimitive>();
172
173 api.initialize();
174
175 try {
176 // check whether we can use changeset
177 //
178 boolean canUseChangeset = api.hasChangesetSupport();
179 boolean useChangeset = Main.pref.getBoolean("osm-server.atomic-upload", apiVersion.compareTo("0.6")>=0);
180 if (useChangeset && ! canUseChangeset) {
181 System.out.println(tr("WARNING: preference ''{0}'' or api version ''{1}'' of dataset requires to use changesets, but API is not able to handle them. Ignoring changesets.", "osm-server.atomic-upload", apiVersion));
182 useChangeset = false;
183 }
184
185 if (useChangeset) {
186 progressMonitor.beginTask(tr("Starting to upload in one request ..."));
187 uploadChangesAsDiffUpload(primitives, progressMonitor);
188 } else {
189 progressMonitor.beginTask(tr("Starting to upload with one request per primitive ..."));
190 uploadChangesIndividually(primitives, progressMonitor);
191 }
192 } finally {
193 progressMonitor.finishTask();
194 }
195 }
196
197 void makeApiRequest(OsmPrimitive osm, ProgressMonitor progressMonitor) throws OsmTransferException {
198 if (osm.isDeleted()) {
199 api.deletePrimitive(osm, progressMonitor);
200 } else if (osm.getId() == 0) {
201 api.createPrimitive(osm);
202 } else {
203 api.modifyPrimitive(osm);
204 }
205 }
206
207 public void disconnectActiveConnection() {
208 if (api != null && api.activeConnection != null) {
209 api.activeConnection.disconnect();
210 }
211 }
212
213 /**
214 * Replies the collection of successfully processed primitives
215 *
216 * @return the collection of successfully processed primitives
217 */
218 public Collection<OsmPrimitive> getProcessedPrimitives() {
219 return processed;
220 }
221}
Note: See TracBrowser for help on using the repository browser.