7ef136b83eea70062ae19b467236a6530e1c85c0
[debian/openrocket] / core / src / net / sf / openrocket / file / openrocket / importt / OpenRocketLoader.java
1 package net.sf.openrocket.file.openrocket.importt;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.InvocationTargetException;
7 import java.util.ArrayList;
8 import java.util.HashMap;
9 import java.util.List;
10 import java.util.Locale;
11 import java.util.regex.Matcher;
12 import java.util.regex.Pattern;
13
14 import net.sf.openrocket.aerodynamics.Warning;
15 import net.sf.openrocket.aerodynamics.WarningSet;
16 import net.sf.openrocket.database.Databases;
17 import net.sf.openrocket.document.OpenRocketDocument;
18 import net.sf.openrocket.document.Simulation;
19 import net.sf.openrocket.document.Simulation.Status;
20 import net.sf.openrocket.document.StorageOptions;
21 import net.sf.openrocket.file.AbstractRocketLoader;
22 import net.sf.openrocket.file.MotorFinder;
23 import net.sf.openrocket.file.RocketLoadException;
24 import net.sf.openrocket.file.simplesax.AbstractElementHandler;
25 import net.sf.openrocket.file.simplesax.ElementHandler;
26 import net.sf.openrocket.file.simplesax.PlainTextHandler;
27 import net.sf.openrocket.file.simplesax.SimpleSAX;
28 import net.sf.openrocket.logging.LogHelper;
29 import net.sf.openrocket.material.Material;
30 import net.sf.openrocket.motor.Motor;
31 import net.sf.openrocket.preset.ComponentPreset;
32 import net.sf.openrocket.rocketcomponent.BodyComponent;
33 import net.sf.openrocket.rocketcomponent.BodyTube;
34 import net.sf.openrocket.rocketcomponent.Bulkhead;
35 import net.sf.openrocket.rocketcomponent.CenteringRing;
36 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
37 import net.sf.openrocket.rocketcomponent.Clusterable;
38 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
39 import net.sf.openrocket.rocketcomponent.EngineBlock;
40 import net.sf.openrocket.rocketcomponent.ExternalComponent;
41 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
42 import net.sf.openrocket.rocketcomponent.FinSet;
43 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
44 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
45 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
46 import net.sf.openrocket.rocketcomponent.InnerTube;
47 import net.sf.openrocket.rocketcomponent.InternalComponent;
48 import net.sf.openrocket.rocketcomponent.LaunchLug;
49 import net.sf.openrocket.rocketcomponent.MassComponent;
50 import net.sf.openrocket.rocketcomponent.MassObject;
51 import net.sf.openrocket.rocketcomponent.MotorMount;
52 import net.sf.openrocket.rocketcomponent.NoseCone;
53 import net.sf.openrocket.rocketcomponent.Parachute;
54 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
55 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
56 import net.sf.openrocket.rocketcomponent.ReferenceType;
57 import net.sf.openrocket.rocketcomponent.RingComponent;
58 import net.sf.openrocket.rocketcomponent.Rocket;
59 import net.sf.openrocket.rocketcomponent.RocketComponent;
60 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
61 import net.sf.openrocket.rocketcomponent.ShockCord;
62 import net.sf.openrocket.rocketcomponent.Stage;
63 import net.sf.openrocket.rocketcomponent.Streamer;
64 import net.sf.openrocket.rocketcomponent.StructuralComponent;
65 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
66 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
67 import net.sf.openrocket.rocketcomponent.Transition;
68 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
69 import net.sf.openrocket.rocketcomponent.TubeCoupler;
70 import net.sf.openrocket.simulation.CustomExpression;
71 import net.sf.openrocket.simulation.FlightData;
72 import net.sf.openrocket.simulation.FlightDataBranch;
73 import net.sf.openrocket.simulation.FlightDataType;
74 import net.sf.openrocket.simulation.FlightEvent;
75 import net.sf.openrocket.simulation.FlightEvent.Type;
76 import net.sf.openrocket.simulation.SimulationOptions;
77 import net.sf.openrocket.startup.Application;
78 import net.sf.openrocket.unit.UnitGroup;
79 import net.sf.openrocket.util.BugException;
80 import net.sf.openrocket.util.Color;
81 import net.sf.openrocket.util.Coordinate;
82 import net.sf.openrocket.util.GeodeticComputationStrategy;
83 import net.sf.openrocket.util.LineStyle;
84 import net.sf.openrocket.util.Reflection;
85
86 import org.xml.sax.InputSource;
87 import org.xml.sax.SAXException;
88
89
90 /**
91  * Class that loads a rocket definition from an OpenRocket rocket file.
92  * <p>
93  * This class uses SAX to read the XML file format.  The 
94  * #loadFromStream(InputStream) method simply sets the system up and 
95  * starts the parsing, while the actual logic is in the private inner class
96  * <code>OpenRocketHandler</code>.
97  * 
98  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
99  */
100 public class OpenRocketLoader extends AbstractRocketLoader {
101         private static final LogHelper log = Application.getLogger();
102
103
104         @Override
105         public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException,
106         IOException {
107                 log.info("Loading .ork file");
108                 DocumentLoadingContext context = new DocumentLoadingContext();
109                 context.setMotorFinder(motorFinder);
110
111                 InputSource xmlSource = new InputSource(source);
112                 OpenRocketHandler handler = new OpenRocketHandler(context);
113
114
115                 try {
116                         SimpleSAX.readXML(xmlSource, handler, warnings);
117                 } catch (SAXException e) {
118                         log.warn("Malformed XML in input");
119                         throw new RocketLoadException("Malformed XML in input.", e);
120                 }
121
122
123                 OpenRocketDocument doc = handler.getDocument();
124                 doc.getDefaultConfiguration().setAllStages();
125
126                 // Deduce suitable time skip
127                 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
128                 for (Simulation s : doc.getSimulations()) {
129                         if (s.getStatus() == Simulation.Status.EXTERNAL ||
130                                         s.getStatus() == Simulation.Status.NOT_SIMULATED)
131                                 continue;
132                         if (s.getSimulatedData() == null)
133                                 continue;
134                         if (s.getSimulatedData().getBranchCount() == 0)
135                                 continue;
136                         FlightDataBranch branch = s.getSimulatedData().getBranch(0);
137                         if (branch == null)
138                                 continue;
139                         List<Double> list = branch.get(FlightDataType.TYPE_TIME);
140                         if (list == null)
141                                 continue;
142
143                         double previousTime = Double.NaN;
144                         for (double time : list) {
145                                 if (time - previousTime < timeSkip)
146                                         timeSkip = time - previousTime;
147                                 previousTime = time;
148                         }
149                 }
150                 // Round value
151                 timeSkip = Math.rint(timeSkip * 100) / 100;
152
153                 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
154                 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
155                 doc.getDefaultStorageOptions().setExplicitlySet(false);
156
157                 doc.clearUndo();
158                 log.info("Loading done");
159                 return doc;
160         }
161
162 }
163
164
165
166 class DocumentConfig {
167
168         /* Remember to update OpenRocketSaver as well! */
169         public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4", "1.5" };
170
171         /**
172          * Divisor used in converting an integer version to the point-represented version.
173          * The integer version divided by this value is the major version and the remainder is
174          * the minor version.  For example 101 corresponds to file version "1.1".
175          */
176         public static final int FILE_VERSION_DIVISOR = 100;
177
178
179         ////////  Component constructors
180         static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
181         static {
182                 try {
183                         // External components
184                         constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
185                         constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
186                         constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
187                         constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
188                         constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
189                         constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
190                         constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
191
192                         // Internal components
193                         constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
194                         constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
195                         constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
196                         constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
197                         constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
198
199                         constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
200                         constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
201                         constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
202                         constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
203
204                         // Other
205                         constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
206
207                 } catch (NoSuchMethodException e) {
208                         throw new BugException(
209                                         "Error in constructing the 'constructors' HashMap.");
210                 }
211         }
212
213
214         ////////  Parameter setters
215         /*
216          * The keys are of the form Class:param, where Class is the class name and param
217          * the element name.  Setters are searched for in descending class order.
218          * A setter of null means setting the parameter is not allowed.
219          */
220         static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
221         static {
222                 // RocketComponent
223                 setters.put("RocketComponent:name", new StringSetter(
224                                 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
225                 setters.put("RocketComponent:color", new ColorSetter(
226                                 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
227                 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
228                                 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
229                                 LineStyle.class));
230                 setters.put("RocketComponent:position", new PositionSetter());
231                 setters.put("RocketComponent:overridemass", new OverrideSetter(
232                                 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
233                                 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
234                 setters.put("RocketComponent:overridecg", new OverrideSetter(
235                                 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
236                                 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
237                 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
238                                 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
239                 setters.put("RocketComponent:comment", new StringSetter(
240                                 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
241                 setters.put("RocketComponent:preset", new ComponentPresetSetter(
242                                 Reflection.findMethod(RocketComponent.class, "loadPreset", ComponentPreset.class)));
243
244                 // ExternalComponent
245                 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
246                                 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
247                                 Finish.class));
248                 setters.put("ExternalComponent:material", new MaterialSetter(
249                                 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
250                                 Material.Type.BULK));
251
252                 // BodyComponent
253                 setters.put("BodyComponent:length", new DoubleSetter(
254                                 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
255
256                 // SymmetricComponent
257                 setters.put("SymmetricComponent:thickness", new DoubleSetter(
258                                 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
259                                 "filled",
260                                 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
261
262                 // BodyTube
263                 setters.put("BodyTube:radius", new DoubleSetter(
264                                 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
265                                 "auto",
266                                 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
267
268                 // Transition
269                 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
270                                 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
271                                 Transition.Shape.class));
272                 setters.put("Transition:shapeclipped", new BooleanSetter(
273                                 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
274                 setters.put("Transition:shapeparameter", new DoubleSetter(
275                                 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
276
277                 setters.put("Transition:foreradius", new DoubleSetter(
278                                 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
279                                 "auto",
280                                 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
281                 setters.put("Transition:aftradius", new DoubleSetter(
282                                 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
283                                 "auto",
284                                 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
285
286                 setters.put("Transition:foreshoulderradius", new DoubleSetter(
287                                 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
288                 setters.put("Transition:foreshoulderlength", new DoubleSetter(
289                                 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
290                 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
291                                 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
292                 setters.put("Transition:foreshouldercapped", new BooleanSetter(
293                                 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
294
295                 setters.put("Transition:aftshoulderradius", new DoubleSetter(
296                                 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
297                 setters.put("Transition:aftshoulderlength", new DoubleSetter(
298                                 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
299                 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
300                                 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
301                 setters.put("Transition:aftshouldercapped", new BooleanSetter(
302                                 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
303
304                 // NoseCone - disable disallowed elements
305                 setters.put("NoseCone:foreradius", null);
306                 setters.put("NoseCone:foreshoulderradius", null);
307                 setters.put("NoseCone:foreshoulderlength", null);
308                 setters.put("NoseCone:foreshoulderthickness", null);
309                 setters.put("NoseCone:foreshouldercapped", null);
310
311                 // FinSet
312                 setters.put("FinSet:fincount", new IntSetter(
313                                 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
314                 setters.put("FinSet:rotation", new DoubleSetter(
315                                 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
316                 setters.put("FinSet:thickness", new DoubleSetter(
317                                 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
318                 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
319                                 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
320                                 FinSet.CrossSection.class));
321                 setters.put("FinSet:cant", new DoubleSetter(
322                                 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
323                 setters.put("FinSet:tabheight", new DoubleSetter(
324                                 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
325                 setters.put("FinSet:tablength", new DoubleSetter(
326                                 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
327                 setters.put("FinSet:tabposition", new FinTabPositionSetter());
328
329                 // TrapezoidFinSet
330                 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
331                                 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
332                 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
333                                 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
334                 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
335                                 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
336                 setters.put("TrapezoidFinSet:height", new DoubleSetter(
337                                 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
338
339                 // EllipticalFinSet
340                 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
341                                 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
342                 setters.put("EllipticalFinSet:height", new DoubleSetter(
343                                 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
344
345                 // FreeformFinSet points handled as a special handler
346
347                 // LaunchLug
348                 setters.put("LaunchLug:radius", new DoubleSetter(
349                                 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
350                 setters.put("LaunchLug:length", new DoubleSetter(
351                                 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
352                 setters.put("LaunchLug:thickness", new DoubleSetter(
353                                 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
354                 setters.put("LaunchLug:radialdirection", new DoubleSetter(
355                                 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
356                                 Math.PI / 180.0));
357
358                 // InternalComponent - nothing
359
360                 // StructuralComponent
361                 setters.put("StructuralComponent:material", new MaterialSetter(
362                                 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
363                                 Material.Type.BULK));
364
365                 // RingComponent
366                 setters.put("RingComponent:length", new DoubleSetter(
367                                 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
368                 setters.put("RingComponent:radialposition", new DoubleSetter(
369                                 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
370                 setters.put("RingComponent:radialdirection", new DoubleSetter(
371                                 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
372                                 Math.PI / 180.0));
373
374                 // ThicknessRingComponent - radius on separate components due to differing automatics
375                 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
376                                 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
377
378                 // EngineBlock
379                 setters.put("EngineBlock:outerradius", new DoubleSetter(
380                                 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
381                                 "auto",
382                                 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
383
384                 // TubeCoupler
385                 setters.put("TubeCoupler:outerradius", new DoubleSetter(
386                                 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
387                                 "auto",
388                                 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
389
390                 // InnerTube
391                 setters.put("InnerTube:outerradius", new DoubleSetter(
392                                 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
393                 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
394                 setters.put("InnerTube:clusterscale", new DoubleSetter(
395                                 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
396                 setters.put("InnerTube:clusterrotation", new DoubleSetter(
397                                 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
398                                 Math.PI / 180.0));
399
400                 // RadiusRingComponent
401
402                 // Bulkhead
403                 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
404                                 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
405                 setters.put("Bulkhead:outerradius", new DoubleSetter(
406                                 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
407                                 "auto",
408                                 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
409
410                 // CenteringRing
411                 setters.put("CenteringRing:innerradius", new DoubleSetter(
412                                 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
413                                 "auto",
414                                 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
415                 setters.put("CenteringRing:outerradius", new DoubleSetter(
416                                 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
417                                 "auto",
418                                 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
419
420
421                 // MassObject
422                 setters.put("MassObject:packedlength", new DoubleSetter(
423                                 Reflection.findMethod(MassObject.class, "setLength", double.class)));
424                 setters.put("MassObject:packedradius", new DoubleSetter(
425                                 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
426                 setters.put("MassObject:radialposition", new DoubleSetter(
427                                 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
428                 setters.put("MassObject:radialdirection", new DoubleSetter(
429                                 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
430                                 Math.PI / 180.0));
431
432                 // MassComponent
433                 setters.put("MassComponent:mass", new DoubleSetter(
434                                 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
435
436                 // ShockCord
437                 setters.put("ShockCord:cordlength", new DoubleSetter(
438                                 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
439                 setters.put("ShockCord:material", new MaterialSetter(
440                                 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
441                                 Material.Type.LINE));
442
443                 // RecoveryDevice
444                 setters.put("RecoveryDevice:cd", new DoubleSetter(
445                                 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
446                                 "auto",
447                                 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
448                 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
449                                 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
450                                 RecoveryDevice.DeployEvent.class));
451                 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
452                                 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
453                 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
454                                 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
455                 setters.put("RecoveryDevice:material", new MaterialSetter(
456                                 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
457                                 Material.Type.SURFACE));
458
459                 // Parachute
460                 setters.put("Parachute:diameter", new DoubleSetter(
461                                 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
462                 setters.put("Parachute:linecount", new IntSetter(
463                                 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
464                 setters.put("Parachute:linelength", new DoubleSetter(
465                                 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
466                 setters.put("Parachute:linematerial", new MaterialSetter(
467                                 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
468                                 Material.Type.LINE));
469
470                 // Streamer
471                 setters.put("Streamer:striplength", new DoubleSetter(
472                                 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
473                 setters.put("Streamer:stripwidth", new DoubleSetter(
474                                 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
475
476                 // Rocket
477                 // <motorconfiguration> handled by separate handler
478                 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
479                                 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
480                                 ReferenceType.class));
481                 setters.put("Rocket:customreference", new DoubleSetter(
482                                 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
483                 setters.put("Rocket:designer", new StringSetter(
484                                 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
485                 setters.put("Rocket:revision", new StringSetter(
486                                 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
487
488                 // Stage
489                 setters.put("Stage:separationevent", new EnumSetter<Stage.SeparationEvent>(
490                                 Reflection.findMethod(Stage.class, "setSeparationEvent", Stage.SeparationEvent.class),
491                                 Stage.SeparationEvent.class));
492                 setters.put("Stage:separationdelay", new DoubleSetter(
493                                 Reflection.findMethod(Stage.class, "setSeparationDelay", double.class)));
494
495         }
496
497
498         /**
499          * Search for a enum value that has the corresponding name as an XML value.  The current
500          * conversion from enum name to XML value is to lowercase the name and strip out all 
501          * underscore characters.  This method returns a match to these criteria, or <code>null</code>
502          * if no such enum exists.
503          * 
504          * @param <T>                   then enum type.
505          * @param name                  the XML value, null ok.
506          * @param enumClass             the class of the enum.
507          * @return                              the found enum value, or <code>null</code>.
508          */
509         public static <T extends Enum<T>> Enum<T> findEnum(String name,
510                         Class<? extends Enum<T>> enumClass) {
511
512                 if (name == null)
513                         return null;
514                 name = name.trim();
515                 for (Enum<T> e : enumClass.getEnumConstants()) {
516                         if (e.name().toLowerCase(Locale.ENGLISH).replace("_", "").equals(name)) {
517                                 return e;
518                         }
519                 }
520                 return null;
521         }
522
523
524         /**
525          * Convert a string to a double including formatting specifications of the OpenRocket
526          * file format.  This accepts all formatting that is valid for 
527          * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
528          * 
529          * @param s             the string to parse.
530          * @return              the numerical value.
531          * @throws NumberFormatException        the the string cannot be parsed.
532          */
533         public static double stringToDouble(String s) throws NumberFormatException {
534                 if (s == null)
535                         throw new NumberFormatException("null string");
536                 if (s.equalsIgnoreCase("NaN"))
537                         return Double.NaN;
538                 if (s.equalsIgnoreCase("Inf"))
539                         return Double.POSITIVE_INFINITY;
540                 if (s.equalsIgnoreCase("-Inf"))
541                         return Double.NEGATIVE_INFINITY;
542                 return Double.parseDouble(s);
543         }
544 }
545
546
547
548
549
550 /**
551  * The starting point of the handlers.  Accepts a single <openrocket> element and hands
552  * the contents to be read by a OpenRocketContentsHandler.
553  */
554 class OpenRocketHandler extends AbstractElementHandler {
555         private final DocumentLoadingContext context;
556         private OpenRocketContentHandler handler = null;
557
558         public OpenRocketHandler(DocumentLoadingContext context) {
559                 this.context = context;
560         }
561
562         /**
563          * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
564          * has not been read yet.
565          * 
566          * @return      the document read, or null.
567          */
568         public OpenRocketDocument getDocument() {
569                 return handler.getDocument();
570         }
571
572         @Override
573         public ElementHandler openElement(String element, HashMap<String, String> attributes,
574                         WarningSet warnings) {
575
576                 // Check for unknown elements
577                 if (!element.equals("openrocket")) {
578                         warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
579                         return null;
580                 }
581
582                 // Check for first call
583                 if (handler != null) {
584                         warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
585                                         + "ones."));
586                         return null;
587                 }
588
589                 // Check version number
590                 String version = null;
591                 String creator = attributes.remove("creator");
592                 String docVersion = attributes.remove("version");
593                 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
594                         if (v.equals(docVersion)) {
595                                 version = v;
596                                 break;
597                         }
598                 }
599                 if (version == null) {
600                         String str = "Unsupported document version";
601                         if (docVersion != null)
602                                 str += " " + docVersion;
603                         if (creator != null && !creator.trim().equals(""))
604                                 str += " (written using '" + creator.trim() + "')";
605                         str += ", attempting to read file anyway.";
606                         warnings.add(str);
607                 }
608
609                 context.setFileVersion(parseVersion(docVersion));
610
611                 handler = new OpenRocketContentHandler(context);
612                 return handler;
613         }
614
615
616         private int parseVersion(String docVersion) {
617                 if (docVersion == null)
618                         return 0;
619
620                 Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion);
621                 if (m.matches()) {
622                         int major = Integer.parseInt(m.group(1));
623                         int minor = Integer.parseInt(m.group(2));
624                         return major * DocumentConfig.FILE_VERSION_DIVISOR + minor;
625                 } else {
626                         return 0;
627                 }
628         }
629
630         @Override
631         public void closeElement(String element, HashMap<String, String> attributes,
632                         String content, WarningSet warnings) throws SAXException {
633                 attributes.remove("version");
634                 attributes.remove("creator");
635                 super.closeElement(element, attributes, content, warnings);
636         }
637
638
639 }
640
641
642 /**
643  * Handles the content of the <openrocket> tag.
644  */
645 class OpenRocketContentHandler extends AbstractElementHandler {
646         private final DocumentLoadingContext context;
647         private final OpenRocketDocument doc;
648         private final Rocket rocket;
649
650         private boolean rocketDefined = false;
651         private boolean simulationsDefined = false;
652
653         public OpenRocketContentHandler(DocumentLoadingContext context) {
654                 this.context = context;
655                 this.rocket = new Rocket();
656                 this.doc = new OpenRocketDocument(rocket);
657         }
658
659
660         public OpenRocketDocument getDocument() {
661                 if (!rocketDefined)
662                         return null;
663                 return doc;
664         }
665
666         @Override
667         public ElementHandler openElement(String element, HashMap<String, String> attributes,
668                         WarningSet warnings) {
669
670                 if (element.equals("rocket")) {
671                         if (rocketDefined) {
672                                 warnings.add(Warning
673                                                 .fromString("Multiple rocket designs within one document, "
674                                                                 + "ignoring later ones."));
675                                 return null;
676                         }
677                         rocketDefined = true;
678                         return new ComponentParameterHandler(rocket, context);
679                 }
680
681                 if (element.equals("simulations")) {
682                         if (simulationsDefined) {
683                                 warnings.add(Warning
684                                                 .fromString("Multiple simulation definitions within one document, "
685                                                                 + "ignoring later ones."));
686                                 return null;
687                         }
688                         simulationsDefined = true;
689                         return new SimulationsHandler(doc, context);
690                 }
691
692                 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
693
694                 return null;
695         }
696 }
697
698
699
700
701 /**
702  * A handler that creates components from the corresponding elements.  The control of the
703  * contents is passed on to ComponentParameterHandler.
704  */
705 class ComponentHandler extends AbstractElementHandler {
706         private final DocumentLoadingContext context;
707         private final RocketComponent parent;
708
709         public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) {
710                 this.parent = parent;
711                 this.context = context;
712         }
713
714         @Override
715         public ElementHandler openElement(String element, HashMap<String, String> attributes,
716                         WarningSet warnings) {
717
718                 // Attempt to construct new component
719                 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
720                                 .get(element);
721                 if (constructor == null) {
722                         warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
723                         return null;
724                 }
725
726                 RocketComponent c;
727                 try {
728                         c = constructor.newInstance();
729                 } catch (InstantiationException e) {
730                         throw new BugException("Error constructing component.", e);
731                 } catch (IllegalAccessException e) {
732                         throw new BugException("Error constructing component.", e);
733                 } catch (InvocationTargetException e) {
734                         throw Reflection.handleWrappedException(e);
735                 }
736
737                 parent.addChild(c);
738
739                 return new ComponentParameterHandler(c, context);
740         }
741 }
742
743
744 /**
745  * A handler that populates the parameters of a previously constructed rocket component.
746  * This uses the setters, or delegates the handling to another handler for specific
747  * elements.
748  */
749 class ComponentParameterHandler extends AbstractElementHandler {
750         private final DocumentLoadingContext context;
751         private final RocketComponent component;
752
753         public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) {
754                 this.component = c;
755                 this.context = context;
756         }
757
758         @Override
759         public ElementHandler openElement(String element, HashMap<String, String> attributes,
760                         WarningSet warnings) {
761
762                 // Check for specific elements that contain other elements
763                 if (element.equals("subcomponents")) {
764                         return new ComponentHandler(component, context);
765                 }
766                 if (element.equals("motormount")) {
767                         if (!(component instanceof MotorMount)) {
768                                 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
769                                 return null;
770                         }
771                         return new MotorMountHandler((MotorMount) component, context);
772                 }
773                 if (element.equals("finpoints")) {
774                         if (!(component instanceof FreeformFinSet)) {
775                                 warnings.add(Warning.fromString("Illegal component defined for fin points."));
776                                 return null;
777                         }
778                         return new FinSetPointHandler((FreeformFinSet) component, context);
779                 }
780                 if (element.equals("motorconfiguration")) {
781                         if (!(component instanceof Rocket)) {
782                                 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
783                                 return null;
784                         }
785                         return new MotorConfigurationHandler((Rocket) component, context);
786                 }
787
788
789                 return PlainTextHandler.INSTANCE;
790         }
791
792         @Override
793         public void closeElement(String element, HashMap<String, String> attributes,
794                         String content, WarningSet warnings) {
795
796                 if (element.equals("subcomponents") || element.equals("motormount") ||
797                                 element.equals("finpoints") || element.equals("motorconfiguration")) {
798                         return;
799                 }
800
801                 // Search for the correct setter class
802
803                 Class<?> c;
804                 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
805                         String setterKey = c.getSimpleName() + ":" + element;
806                         Setter s = DocumentConfig.setters.get(setterKey);
807                         if (s != null) {
808                                 // Setter found
809                                 s.set(component, content, attributes, warnings);
810                                 break;
811                         }
812                         if (DocumentConfig.setters.containsKey(setterKey)) {
813                                 // Key exists but is null -> invalid parameter
814                                 c = null;
815                                 break;
816                         }
817                 }
818                 if (c == null) {
819                         warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
820                                         + component.getComponentName() + ", ignoring."));
821                 }
822         }
823 }
824
825
826 /**
827  * A handler that reads the <point> specifications within the freeformfinset's
828  * <finpoints> elements.
829  */
830 class FinSetPointHandler extends AbstractElementHandler {
831         @SuppressWarnings("unused")
832         private final DocumentLoadingContext context;
833         private final FreeformFinSet finset;
834         private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
835
836         public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) {
837                 this.finset = finset;
838                 this.context = context;
839         }
840
841         @Override
842         public ElementHandler openElement(String element, HashMap<String, String> attributes,
843                         WarningSet warnings) {
844                 return PlainTextHandler.INSTANCE;
845         }
846
847
848         @Override
849         public void closeElement(String element, HashMap<String, String> attributes,
850                         String content, WarningSet warnings) throws SAXException {
851
852                 String strx = attributes.remove("x");
853                 String stry = attributes.remove("y");
854                 if (strx == null || stry == null) {
855                         warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
856                         return;
857                 }
858                 try {
859                         double x = Double.parseDouble(strx);
860                         double y = Double.parseDouble(stry);
861                         coordinates.add(new Coordinate(x, y));
862                 } catch (NumberFormatException e) {
863                         warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
864                         return;
865                 }
866
867                 super.closeElement(element, attributes, content, warnings);
868         }
869
870         @Override
871         public void endHandler(String element, HashMap<String, String> attributes,
872                         String content, WarningSet warnings) {
873                 try {
874                         finset.setPoints(coordinates.toArray(new Coordinate[0]));
875                 } catch (IllegalFinPointException e) {
876                         warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
877                 }
878         }
879 }
880
881
882 class MotorMountHandler extends AbstractElementHandler {
883         private final DocumentLoadingContext context;
884         private final MotorMount mount;
885         private MotorHandler motorHandler;
886
887         public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) {
888                 this.mount = mount;
889                 this.context = context;
890                 mount.setMotorMount(true);
891         }
892
893         @Override
894         public ElementHandler openElement(String element, HashMap<String, String> attributes,
895                         WarningSet warnings) {
896
897                 if (element.equals("motor")) {
898                         motorHandler = new MotorHandler(context);
899                         return motorHandler;
900                 }
901
902                 if (element.equals("ignitionevent") ||
903                                 element.equals("ignitiondelay") ||
904                                 element.equals("overhang")) {
905                         return PlainTextHandler.INSTANCE;
906                 }
907
908                 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
909                 return null;
910         }
911
912
913
914         @Override
915         public void closeElement(String element, HashMap<String, String> attributes,
916                         String content, WarningSet warnings) throws SAXException {
917
918                 if (element.equals("motor")) {
919                         String id = attributes.get("configid");
920                         if (id == null || id.equals("")) {
921                                 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
922                                 return;
923                         }
924
925                         Motor motor = motorHandler.getMotor(warnings);
926                         mount.setMotor(id, motor);
927                         mount.setMotorDelay(id, motorHandler.getDelay(warnings));
928                         return;
929                 }
930
931                 if (element.equals("ignitionevent")) {
932                         MotorMount.IgnitionEvent event = null;
933                         for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
934                                 if (e.name().toLowerCase(Locale.ENGLISH).replaceAll("_", "").equals(content)) {
935                                         event = e;
936                                         break;
937                                 }
938                         }
939                         if (event == null) {
940                                 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
941                                 return;
942                         }
943                         mount.setIgnitionEvent(event);
944                         return;
945                 }
946
947                 if (element.equals("ignitiondelay")) {
948                         double d;
949                         try {
950                                 d = Double.parseDouble(content);
951                         } catch (NumberFormatException nfe) {
952                                 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
953                                 return;
954                         }
955                         mount.setIgnitionDelay(d);
956                         return;
957                 }
958
959                 if (element.equals("overhang")) {
960                         double d;
961                         try {
962                                 d = Double.parseDouble(content);
963                         } catch (NumberFormatException nfe) {
964                                 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
965                                 return;
966                         }
967                         mount.setMotorOverhang(d);
968                         return;
969                 }
970
971                 super.closeElement(element, attributes, content, warnings);
972         }
973 }
974
975
976
977
978 class MotorConfigurationHandler extends AbstractElementHandler {
979         @SuppressWarnings("unused")
980         private final DocumentLoadingContext context;
981         private final Rocket rocket;
982         private String name = null;
983         private boolean inNameElement = false;
984
985         public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) {
986                 this.rocket = rocket;
987                 this.context = context;
988         }
989
990         @Override
991         public ElementHandler openElement(String element, HashMap<String, String> attributes,
992                         WarningSet warnings) {
993
994                 if (inNameElement || !element.equals("name")) {
995                         warnings.add(Warning.FILE_INVALID_PARAMETER);
996                         return null;
997                 }
998                 inNameElement = true;
999
1000                 return PlainTextHandler.INSTANCE;
1001         }
1002
1003         @Override
1004         public void closeElement(String element, HashMap<String, String> attributes,
1005                         String content, WarningSet warnings) {
1006                 name = content;
1007         }
1008
1009         @Override
1010         public void endHandler(String element, HashMap<String, String> attributes,
1011                         String content, WarningSet warnings) throws SAXException {
1012
1013                 String configid = attributes.remove("configid");
1014                 if (configid == null || configid.equals("")) {
1015                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1016                         return;
1017                 }
1018
1019                 if (!rocket.addMotorConfigurationID(configid)) {
1020                         warnings.add("Duplicate motor configuration ID used.");
1021                         return;
1022                 }
1023
1024                 if (name != null && name.trim().length() > 0) {
1025                         rocket.setMotorConfigurationName(configid, name);
1026                 }
1027
1028                 if ("true".equals(attributes.remove("default"))) {
1029                         rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
1030                 }
1031
1032                 super.closeElement(element, attributes, content, warnings);
1033         }
1034 }
1035
1036
1037 class MotorHandler extends AbstractElementHandler {
1038         /** File version where latest digest format was introduced */
1039         private static final int MOTOR_DIGEST_VERSION = 104;
1040
1041         private final DocumentLoadingContext context;
1042         private Motor.Type type = null;
1043         private String manufacturer = null;
1044         private String designation = null;
1045         private String digest = null;
1046         private double diameter = Double.NaN;
1047         private double length = Double.NaN;
1048         private double delay = Double.NaN;
1049
1050         public MotorHandler(DocumentLoadingContext context) {
1051                 this.context = context;
1052         }
1053
1054
1055         @Override
1056         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1057                         WarningSet warnings) {
1058                 return PlainTextHandler.INSTANCE;
1059         }
1060
1061
1062         /**
1063          * Return the motor to use, or null.
1064          */
1065         public Motor getMotor(WarningSet warnings) {
1066                 return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings);
1067         }
1068
1069         /**
1070          * Return the delay to use for the motor.
1071          */
1072         public double getDelay(WarningSet warnings) {
1073                 if (Double.isNaN(delay)) {
1074                         warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1075                         return Motor.PLUGGED;
1076                 }
1077                 return delay;
1078         }
1079
1080
1081         @Override
1082         public void closeElement(String element, HashMap<String, String> attributes,
1083                         String content, WarningSet warnings) throws SAXException {
1084
1085                 content = content.trim();
1086
1087                 if (element.equals("type")) {
1088
1089                         // Motor type
1090                         type = null;
1091                         for (Motor.Type t : Motor.Type.values()) {
1092                                 if (t.name().toLowerCase(Locale.ENGLISH).equals(content.trim())) {
1093                                         type = t;
1094                                         break;
1095                                 }
1096                         }
1097                         if (type == null) {
1098                                 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1099                         }
1100
1101                 } else if (element.equals("manufacturer")) {
1102
1103                         // Manufacturer
1104                         manufacturer = content.trim();
1105
1106                 } else if (element.equals("designation")) {
1107
1108                         // Designation
1109                         designation = content.trim();
1110
1111                 } else if (element.equals("digest")) {
1112
1113                         // Digest is used only for file versions saved using the same digest algorithm
1114                         if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) {
1115                                 digest = content.trim();
1116                         }
1117
1118                 } else if (element.equals("diameter")) {
1119
1120                         // Diameter
1121                         diameter = Double.NaN;
1122                         try {
1123                                 diameter = Double.parseDouble(content.trim());
1124                         } catch (NumberFormatException e) {
1125                                 // Ignore
1126                         }
1127                         if (Double.isNaN(diameter)) {
1128                                 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1129                         }
1130
1131                 } else if (element.equals("length")) {
1132
1133                         // Length
1134                         length = Double.NaN;
1135                         try {
1136                                 length = Double.parseDouble(content.trim());
1137                         } catch (NumberFormatException ignore) {
1138                         }
1139
1140                         if (Double.isNaN(length)) {
1141                                 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1142                         }
1143
1144                 } else if (element.equals("delay")) {
1145
1146                         // Delay
1147                         delay = Double.NaN;
1148                         if (content.equals("none")) {
1149                                 delay = Motor.PLUGGED;
1150                         } else {
1151                                 try {
1152                                         delay = Double.parseDouble(content.trim());
1153                                 } catch (NumberFormatException ignore) {
1154                                 }
1155
1156                                 if (Double.isNaN(delay)) {
1157                                         warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1158                                 }
1159
1160                         }
1161
1162                 } else {
1163                         super.closeElement(element, attributes, content, warnings);
1164                 }
1165         }
1166
1167 }
1168
1169
1170
1171 class SimulationsHandler extends AbstractElementHandler {
1172         private final DocumentLoadingContext context;
1173         private final OpenRocketDocument doc;
1174         private SingleSimulationHandler handler;
1175
1176         public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1177                 this.doc = doc;
1178                 this.context = context;
1179         }
1180
1181         @Override
1182         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1183                         WarningSet warnings) {
1184
1185                 if (!element.equals("simulation")) {
1186                         warnings.add("Unknown element '" + element + "', ignoring.");
1187                         return null;
1188                 }
1189
1190                 handler = new SingleSimulationHandler(doc, context);
1191                 return handler;
1192         }
1193
1194         @Override
1195         public void closeElement(String element, HashMap<String, String> attributes,
1196                         String content, WarningSet warnings) throws SAXException {
1197                 attributes.remove("status");
1198                 super.closeElement(element, attributes, content, warnings);
1199         }
1200
1201
1202 }
1203
1204 class SingleSimulationHandler extends AbstractElementHandler {
1205
1206         private final DocumentLoadingContext context;
1207
1208         private final OpenRocketDocument doc;
1209
1210         private String name;
1211
1212         private SimulationConditionsHandler conditionHandler;
1213         private FlightDataHandler dataHandler;
1214         private CustomExpressionsHandler customExpressionsHandler;
1215
1216         private ArrayList<CustomExpression> customExpressions = new ArrayList<CustomExpression>();
1217         private final List<String> listeners = new ArrayList<String>();
1218
1219         public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1220                 this.doc = doc;
1221                 this.context = context;
1222         }
1223
1224         public void setCustomExpressions(ArrayList<CustomExpression> expressions){
1225                 this.customExpressions = expressions;
1226         }
1227
1228         public ArrayList<CustomExpression> getCustomExpressions(){
1229                 return customExpressions;
1230         }
1231
1232         @Override
1233         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1234                         WarningSet warnings) {
1235
1236                 if (element.equals("name") || element.equals("simulator") ||
1237                                 element.equals("calculator") || element.equals("listener")) {
1238                         return PlainTextHandler.INSTANCE;
1239                 } else if (element.equals("customexpressions")) {
1240                         customExpressionsHandler = new CustomExpressionsHandler(this, context);
1241                         return customExpressionsHandler;
1242                 } else if (element.equals("conditions")) {
1243                         conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context);
1244                         return conditionHandler;
1245                 } else if (element.equals("flightdata")) {
1246                         dataHandler = new FlightDataHandler(this, context);
1247                         return dataHandler;
1248                 } else {
1249                         warnings.add("Unknown element '" + element + "', ignoring.");
1250                         return null;
1251                 }
1252         }
1253
1254         @Override
1255         public void closeElement(String element, HashMap<String, String> attributes,
1256                         String content, WarningSet warnings) {
1257
1258                 if (element.equals("name")) {
1259                         name = content;
1260                 } else if (element.equals("simulator")) {
1261                         if (!content.trim().equals("RK4Simulator")) {
1262                                 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1263                         }
1264                 } else if (element.equals("calculator")) {
1265                         if (!content.trim().equals("BarrowmanCalculator")) {
1266                                 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1267                         }
1268                 } else if (element.equals("listener") && content.trim().length() > 0) {
1269                         listeners.add(content.trim());
1270                 }
1271
1272         }
1273
1274         @Override
1275         public void endHandler(String element, HashMap<String, String> attributes,
1276                         String content, WarningSet warnings) {
1277
1278                 String s = attributes.get("status");
1279                 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1280                 if (status == null) {
1281                         warnings.add("Simulation status unknown, assuming outdated.");
1282                         status = Simulation.Status.OUTDATED;
1283                 }
1284
1285                 SimulationOptions conditions;
1286                 if (conditionHandler != null) {
1287                         conditions = conditionHandler.getConditions();
1288                 } else {
1289                         warnings.add("Simulation conditions not defined, using defaults.");
1290                         conditions = new SimulationOptions(doc.getRocket());
1291                 }
1292
1293                 if (name == null)
1294                         name = "Simulation";
1295
1296                 FlightData data;
1297                 if (dataHandler == null)
1298                         data = null;
1299                 else
1300                         data = dataHandler.getFlightData();
1301
1302                 Simulation simulation = new Simulation(doc, doc.getRocket(), status, name,
1303                                 conditions, listeners, data);
1304
1305                 // Note : arraylist implementation in simulation different from standard one
1306                 for (CustomExpression exp : customExpressions){
1307                         exp.setSimulation(simulation);
1308                         if (exp.checkAll())
1309                                 simulation.addCustomExpression(exp);
1310                 }
1311
1312                 doc.addSimulation(simulation);
1313         }
1314 }
1315
1316 class CustomExpressionsHandler extends AbstractElementHandler {
1317         private final DocumentLoadingContext context;
1318         private final SingleSimulationHandler simHandler;
1319         public CustomExpression currentExpression = new CustomExpression();
1320         private final ArrayList<CustomExpression> customExpressions = new ArrayList<CustomExpression>();
1321
1322
1323         public CustomExpressionsHandler(SingleSimulationHandler simHandler, DocumentLoadingContext context) {
1324                 this.context = context;
1325                 this.simHandler = simHandler;
1326         }
1327
1328         @Override
1329         public ElementHandler openElement(String element,
1330                         HashMap<String, String> attributes, WarningSet warnings)
1331                                         throws SAXException {
1332
1333                 if (element.equals("expression")){
1334                         currentExpression = new CustomExpression();
1335                 }
1336
1337                 return this;
1338         }
1339
1340         @Override
1341         public void closeElement(String element, HashMap<String, String> attributes,
1342                         String content, WarningSet warnings) {
1343
1344                 if (element.equals("expression"))
1345                         customExpressions.add(currentExpression);
1346
1347                 if (element.equals("name"))
1348                         currentExpression.setName(content);
1349
1350                 else if (element.equals("symbol"))
1351                         currentExpression.setSymbol(content);
1352
1353                 else if (element.equals("unit"))
1354                         currentExpression.setUnit(content);
1355
1356                 else if (element.equals("expressionstring"))
1357                         currentExpression.setExpression(content);
1358
1359         }
1360
1361         @Override
1362         public void endHandler(String element, HashMap<String, String> attributes,
1363                         String content, WarningSet warnings) {
1364                 simHandler.setCustomExpressions(customExpressions);
1365         }
1366 }
1367
1368 class SimulationConditionsHandler extends AbstractElementHandler {
1369         private final DocumentLoadingContext context;
1370         private SimulationOptions conditions;
1371         private AtmosphereHandler atmosphereHandler;
1372
1373         public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) {
1374                 this.context = context;
1375                 conditions = new SimulationOptions(rocket);
1376                 // Set up default loading settings (which may differ from the new defaults)
1377                 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1378         }
1379
1380         public SimulationOptions getConditions() {
1381                 return conditions;
1382         }
1383
1384         @Override
1385         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1386                         WarningSet warnings) {
1387                 if (element.equals("atmosphere")) {
1388                         atmosphereHandler = new AtmosphereHandler(attributes.get("model"), context);
1389                         return atmosphereHandler;
1390                 }
1391                 return PlainTextHandler.INSTANCE;
1392         }
1393
1394         @Override
1395         public void closeElement(String element, HashMap<String, String> attributes,
1396                         String content, WarningSet warnings) {
1397
1398                 double d = Double.NaN;
1399                 try {
1400                         d = Double.parseDouble(content);
1401                 } catch (NumberFormatException ignore) {
1402                 }
1403
1404
1405                 if (element.equals("configid")) {
1406                         if (content.equals("")) {
1407                                 conditions.setMotorConfigurationID(null);
1408                         } else {
1409                                 conditions.setMotorConfigurationID(content);
1410                         }
1411                 } else if (element.equals("launchrodlength")) {
1412                         if (Double.isNaN(d)) {
1413                                 warnings.add("Illegal launch rod length defined, ignoring.");
1414                         } else {
1415                                 conditions.setLaunchRodLength(d);
1416                         }
1417                 } else if (element.equals("launchrodangle")) {
1418                         if (Double.isNaN(d)) {
1419                                 warnings.add("Illegal launch rod angle defined, ignoring.");
1420                         } else {
1421                                 conditions.setLaunchRodAngle(d * Math.PI / 180);
1422                         }
1423                 } else if (element.equals("launchroddirection")) {
1424                         if (Double.isNaN(d)) {
1425                                 warnings.add("Illegal launch rod direction defined, ignoring.");
1426                         } else {
1427                                 conditions.setLaunchRodDirection(d * Math.PI / 180);
1428                         }
1429                 } else if (element.equals("windaverage")) {
1430                         if (Double.isNaN(d)) {
1431                                 warnings.add("Illegal average windspeed defined, ignoring.");
1432                         } else {
1433                                 conditions.setWindSpeedAverage(d);
1434                         }
1435                 } else if (element.equals("windturbulence")) {
1436                         if (Double.isNaN(d)) {
1437                                 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1438                         } else {
1439                                 conditions.setWindTurbulenceIntensity(d);
1440                         }
1441                 } else if (element.equals("launchaltitude")) {
1442                         if (Double.isNaN(d)) {
1443                                 warnings.add("Illegal launch altitude defined, ignoring.");
1444                         } else {
1445                                 conditions.setLaunchAltitude(d);
1446                         }
1447                 } else if (element.equals("launchlatitude")) {
1448                         if (Double.isNaN(d)) {
1449                                 warnings.add("Illegal launch latitude defined, ignoring.");
1450                         } else {
1451                                 conditions.setLaunchLatitude(d);
1452                         }
1453                 } else if (element.equals("launchlongitude")) {
1454                         if (Double.isNaN(d)) {
1455                                 warnings.add("Illegal launch longitude.");
1456                         } else {
1457                                 conditions.setLaunchLongitude(d);
1458                         }
1459                 } else if (element.equals("geodeticmethod")) {
1460                         GeodeticComputationStrategy gcs =
1461                                         (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1462                         if (gcs != null) {
1463                                 conditions.setGeodeticComputation(gcs);
1464                         } else {
1465                                 warnings.add("Unknown geodetic computation method '" + content + "'");
1466                         }
1467                 } else if (element.equals("atmosphere")) {
1468                         atmosphereHandler.storeSettings(conditions, warnings);
1469                 } else if (element.equals("timestep")) {
1470                         if (Double.isNaN(d)) {
1471                                 warnings.add("Illegal time step defined, ignoring.");
1472                         } else {
1473                                 conditions.setTimeStep(d);
1474                         }
1475                 }
1476         }
1477 }
1478
1479
1480 class AtmosphereHandler extends AbstractElementHandler {
1481         @SuppressWarnings("unused")
1482         private final DocumentLoadingContext context;
1483         private final String model;
1484         private double temperature = Double.NaN;
1485         private double pressure = Double.NaN;
1486
1487         public AtmosphereHandler(String model, DocumentLoadingContext context) {
1488                 this.model = model;
1489                 this.context = context;
1490         }
1491
1492         @Override
1493         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1494                         WarningSet warnings) {
1495                 return PlainTextHandler.INSTANCE;
1496         }
1497
1498         @Override
1499         public void closeElement(String element, HashMap<String, String> attributes,
1500                         String content, WarningSet warnings) throws SAXException {
1501
1502                 double d = Double.NaN;
1503                 try {
1504                         d = Double.parseDouble(content);
1505                 } catch (NumberFormatException ignore) {
1506                 }
1507
1508                 if (element.equals("basetemperature")) {
1509                         if (Double.isNaN(d)) {
1510                                 warnings.add("Illegal base temperature specified, ignoring.");
1511                         }
1512                         temperature = d;
1513                 } else if (element.equals("basepressure")) {
1514                         if (Double.isNaN(d)) {
1515                                 warnings.add("Illegal base pressure specified, ignoring.");
1516                         }
1517                         pressure = d;
1518                 } else {
1519                         super.closeElement(element, attributes, content, warnings);
1520                 }
1521         }
1522
1523
1524         public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1525                 if (!Double.isNaN(pressure)) {
1526                         cond.setLaunchPressure(pressure);
1527                 }
1528                 if (!Double.isNaN(temperature)) {
1529                         cond.setLaunchTemperature(temperature);
1530                 }
1531
1532                 if ("isa".equals(model)) {
1533                         cond.setISAAtmosphere(true);
1534                 } else if ("extendedisa".equals(model)) {
1535                         cond.setISAAtmosphere(false);
1536                 } else {
1537                         cond.setISAAtmosphere(true);
1538                         warnings.add("Unknown atmospheric model, using ISA.");
1539                 }
1540         }
1541
1542 }
1543
1544
1545 class FlightDataHandler extends AbstractElementHandler {
1546         private final DocumentLoadingContext context;
1547
1548         private FlightDataBranchHandler dataHandler;
1549         private WarningSet warningSet = new WarningSet();
1550         private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1551
1552         private SingleSimulationHandler simHandler;
1553         private FlightData data;
1554
1555
1556         public FlightDataHandler(SingleSimulationHandler simHandler, DocumentLoadingContext context) {
1557                 this.context = context;
1558                 this.simHandler = simHandler;
1559         }
1560
1561         public FlightData getFlightData() {
1562                 return data;
1563         }
1564
1565         @Override
1566         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1567                         WarningSet warnings) {
1568
1569                 if (element.equals("warning")) {
1570                         return PlainTextHandler.INSTANCE;
1571                 }
1572                 if (element.equals("databranch")) {
1573                         if (attributes.get("name") == null || attributes.get("types") == null) {
1574                                 warnings.add("Illegal flight data definition, ignoring.");
1575                                 return null;
1576                         }
1577                         dataHandler = new FlightDataBranchHandler(      attributes.get("name"),
1578                                         attributes.get("typekeys"),
1579                                         attributes.get("types"), 
1580                                         simHandler, context);
1581                         return dataHandler;
1582                 }
1583
1584                 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1585                 return null;
1586         }
1587
1588
1589         @Override
1590         public void closeElement(String element, HashMap<String, String> attributes,
1591                         String content, WarningSet warnings) {
1592
1593                 if (element.equals("databranch")) {
1594                         FlightDataBranch branch = dataHandler.getBranch();
1595                         if (branch.getLength() > 0) {
1596                                 branches.add(branch);
1597                         }
1598                 } else if (element.equals("warning")) {
1599                         warningSet.add(Warning.fromString(content));
1600                 }
1601         }
1602
1603
1604         @Override
1605         public void endHandler(String element, HashMap<String, String> attributes,
1606                         String content, WarningSet warnings) {
1607
1608                 if (branches.size() > 0) {
1609                         data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1610                 } else {
1611                         double maxAltitude = Double.NaN;
1612                         double maxVelocity = Double.NaN;
1613                         double maxAcceleration = Double.NaN;
1614                         double maxMach = Double.NaN;
1615                         double timeToApogee = Double.NaN;
1616                         double flightTime = Double.NaN;
1617                         double groundHitVelocity = Double.NaN;
1618                         double launchRodVelocity = Double.NaN;
1619                         double deploymentVelocity = Double.NaN;
1620
1621                         try {
1622                                 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1623                         } catch (NumberFormatException ignore) {
1624                         }
1625                         try {
1626                                 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1627                         } catch (NumberFormatException ignore) {
1628                         }
1629                         try {
1630                                 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1631                         } catch (NumberFormatException ignore) {
1632                         }
1633                         try {
1634                                 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1635                         } catch (NumberFormatException ignore) {
1636                         }
1637                         try {
1638                                 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1639                         } catch (NumberFormatException ignore) {
1640                         }
1641                         try {
1642                                 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1643                         } catch (NumberFormatException ignore) {
1644                         }
1645                         try {
1646                                 groundHitVelocity =
1647                                                 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1648                         } catch (NumberFormatException ignore) {
1649                         }
1650                         try {
1651                                 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1652                         } catch (NumberFormatException ignore) {
1653                         }
1654                         try {
1655                                 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1656                         } catch (NumberFormatException ignore) {
1657                         }
1658
1659                         data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1660                                         timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1661                 }
1662
1663                 data.getWarningSet().addAll(warningSet);
1664                 data.immute();
1665         }
1666
1667
1668 }
1669
1670
1671 class FlightDataBranchHandler extends AbstractElementHandler {
1672         @SuppressWarnings("unused")
1673         private final DocumentLoadingContext context;
1674         private final FlightDataType[] types;
1675         private final FlightDataBranch branch;
1676
1677         private static final LogHelper log = Application.getLogger();
1678         private final SingleSimulationHandler simHandler;
1679
1680         public FlightDataBranchHandler(String name, String typeKeyList, String typeList, SingleSimulationHandler simHandler, DocumentLoadingContext context) {
1681                 this.simHandler = simHandler;
1682                 this.context = context;
1683                 String[] typeNames = typeList.split(",");
1684                 String[] typeKeys = null;
1685                 if ( typeKeyList != null ) {
1686                         typeKeys = typeKeyList.split(",");
1687                 }
1688                 types = new FlightDataType[typeNames.length];
1689                 for (int i = 0; i < typeNames.length; i++) {
1690                         String typeName = typeNames[i];
1691                         String typeKey = (typeKeys != null ) ? typeKeys[i] : null ;
1692                         FlightDataType matching = findFlightDataType(typeKey, typeName);
1693                         types[i] = matching;
1694                         //types[i] = FlightDataType.getType(typeName, matching.getSymbol(), matching.getUnitGroup());
1695                 }
1696
1697                 // TODO: LOW: May throw an IllegalArgumentException
1698                 branch = new FlightDataBranch(name, types);
1699         }
1700
1701         // Find the full flight data type given name only
1702         // Note: this way of doing it requires that custom expressions always come before flight data in the file,
1703         // not the nicest but this is always the case anyway.
1704         private FlightDataType findFlightDataType(String key, String name){
1705
1706                 // Look in built in types by key.
1707                 if ( key != null ) {
1708                         for (FlightDataType t : FlightDataType.ALL_TYPES){
1709                                 if (t.getKey().equals(key) ){
1710                                         return t;
1711                                 }
1712                         }
1713                 }
1714                 // Look in built in types by name.
1715                 for (FlightDataType t : FlightDataType.ALL_TYPES){
1716                         if (t.getName().equals(name) ){
1717                                 return t;
1718                         }
1719                 }
1720
1721                 // Look in custom expressions
1722                 for (CustomExpression exp : simHandler.getCustomExpressions()){
1723                         if (exp.getName().equals(name) ){
1724                                 return exp.getType();
1725                         }
1726                 }
1727
1728                 // Look in custom expressions, meanwhile set priority based on order in file
1729                 /*
1730                 int totalExpressions = simHandler.getCustomExpressions().size();
1731                 for (int i=0; i<totalExpressions; i++){
1732                         CustomExpression exp = simHandler.getCustomExpressions().get(i);                        
1733                         if (exp.getName().equals(name) ){
1734                                 FlightDataType t = exp.getType();
1735                                 t.setPriority(-1*(totalExpressions-i));
1736                                 return exp.getType();
1737                         }
1738                 }
1739                  */
1740
1741                 log.warn("Could not find the flight data type '"+name+"' used in the XML file. Substituted type with unknown symbol and units.");
1742                 return FlightDataType.getType(name, "Unknown", UnitGroup.UNITS_NONE);
1743         }
1744
1745         public FlightDataBranch getBranch() {
1746                 branch.immute();
1747                 return branch;
1748         }
1749
1750         @Override
1751         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1752                         WarningSet warnings) {
1753
1754                 if (element.equals("datapoint"))
1755                         return PlainTextHandler.INSTANCE;
1756                 if (element.equals("event"))
1757                         return PlainTextHandler.INSTANCE;
1758
1759                 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1760                 return null;
1761         }
1762
1763
1764         @Override
1765         public void closeElement(String element, HashMap<String, String> attributes,
1766                         String content, WarningSet warnings) {
1767
1768                 if (element.equals("event")) {
1769                         double time;
1770                         FlightEvent.Type type;
1771
1772                         try {
1773                                 time = DocumentConfig.stringToDouble(attributes.get("time"));
1774                         } catch (NumberFormatException e) {
1775                                 warnings.add("Illegal event specification, ignoring.");
1776                                 return;
1777                         }
1778
1779                         type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1780                         if (type == null) {
1781                                 warnings.add("Illegal event specification, ignoring.");
1782                                 return;
1783                         }
1784
1785                         branch.addEvent(new FlightEvent(type, time));
1786                         return;
1787                 }
1788
1789                 if (!element.equals("datapoint")) {
1790                         warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1791                         return;
1792                 }
1793
1794                 // element == "datapoint"
1795
1796
1797                 // Check line format
1798                 String[] split = content.split(",");
1799                 if (split.length != types.length) {
1800                         warnings.add("Data point did not contain correct amount of values, ignoring point.");
1801                         return;
1802                 }
1803
1804                 // Parse the doubles
1805                 double[] values = new double[split.length];
1806                 for (int i = 0; i < values.length; i++) {
1807                         try {
1808                                 values[i] = DocumentConfig.stringToDouble(split[i]);
1809                         } catch (NumberFormatException e) {
1810                                 warnings.add("Data point format error, ignoring point.");
1811                                 return;
1812                         }
1813                 }
1814
1815                 // Add point to branch
1816                 branch.addPoint();
1817                 for (int i = 0; i < types.length; i++) {
1818                         branch.setValue(types[i], values[i]);
1819                 }
1820         }
1821 }
1822
1823
1824
1825
1826
1827 /////////////////    Setters implementation
1828
1829
1830 ////  Interface
1831 interface Setter {
1832         /**
1833          * Set the specified value to the given component.
1834          * 
1835          * @param component             the component to which to set.
1836          * @param value                 the value within the element.
1837          * @param attributes    attributes for the element.
1838          * @param warnings              the warning set to use.
1839          */
1840         public void set(RocketComponent component, String value,
1841                         HashMap<String, String> attributes, WarningSet warnings);
1842 }
1843
1844
1845 ////  StringSetter - sets the value to the contained String
1846 class StringSetter implements Setter {
1847         private final Reflection.Method setMethod;
1848
1849         public StringSetter(Reflection.Method set) {
1850                 setMethod = set;
1851         }
1852
1853         @Override
1854         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1855                         WarningSet warnings) {
1856                 setMethod.invoke(c, s);
1857         }
1858 }
1859
1860 ////  IntSetter - set an integer value
1861 class IntSetter implements Setter {
1862         private final Reflection.Method setMethod;
1863
1864         public IntSetter(Reflection.Method set) {
1865                 setMethod = set;
1866         }
1867
1868         @Override
1869         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1870                         WarningSet warnings) {
1871                 try {
1872                         int n = Integer.parseInt(s);
1873                         setMethod.invoke(c, n);
1874                 } catch (NumberFormatException e) {
1875                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1876                 }
1877         }
1878 }
1879
1880
1881 //// BooleanSetter - set a boolean value
1882 class BooleanSetter implements Setter {
1883         private final Reflection.Method setMethod;
1884
1885         public BooleanSetter(Reflection.Method set) {
1886                 setMethod = set;
1887         }
1888
1889         @Override
1890         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1891                         WarningSet warnings) {
1892
1893                 s = s.trim();
1894                 if (s.equalsIgnoreCase("true")) {
1895                         setMethod.invoke(c, true);
1896                 } else if (s.equalsIgnoreCase("false")) {
1897                         setMethod.invoke(c, false);
1898                 } else {
1899                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1900                 }
1901         }
1902 }
1903
1904
1905
1906 ////  DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1907 ////  calls a setXXX(boolean) method.
1908 class DoubleSetter implements Setter {
1909         private final Reflection.Method setMethod;
1910         private final String specialString;
1911         private final Reflection.Method specialMethod;
1912         private final double multiplier;
1913
1914         /**
1915          * Set only the double value.
1916          * @param set   set method for the double value. 
1917          */
1918         public DoubleSetter(Reflection.Method set) {
1919                 this.setMethod = set;
1920                 this.specialString = null;
1921                 this.specialMethod = null;
1922                 this.multiplier = 1.0;
1923         }
1924
1925         /**
1926          * Multiply with the given multiplier and set the double value.
1927          * @param set   set method for the double value.
1928          * @param mul   multiplier.
1929          */
1930         public DoubleSetter(Reflection.Method set, double mul) {
1931                 this.setMethod = set;
1932                 this.specialString = null;
1933                 this.specialMethod = null;
1934                 this.multiplier = mul;
1935         }
1936
1937         /**
1938          * Set the double value, or if the value equals the special string, use the
1939          * special setter and set it to true.
1940          * 
1941          * @param set                   double setter.
1942          * @param special               special string
1943          * @param specialMethod boolean setter.
1944          */
1945         public DoubleSetter(Reflection.Method set, String special,
1946                         Reflection.Method specialMethod) {
1947                 this.setMethod = set;
1948                 this.specialString = special;
1949                 this.specialMethod = specialMethod;
1950                 this.multiplier = 1.0;
1951         }
1952
1953
1954         @Override
1955         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1956                         WarningSet warnings) {
1957
1958                 s = s.trim();
1959
1960                 // Check for special case
1961                 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1962                         specialMethod.invoke(c, true);
1963                         return;
1964                 }
1965
1966                 // Normal case
1967                 try {
1968                         double d = Double.parseDouble(s);
1969                         setMethod.invoke(c, d * multiplier);
1970                 } catch (NumberFormatException e) {
1971                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1972                 }
1973         }
1974 }
1975
1976
1977 class OverrideSetter implements Setter {
1978         private final Reflection.Method setMethod;
1979         private final Reflection.Method enabledMethod;
1980
1981         public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1982                 this.setMethod = set;
1983                 this.enabledMethod = enabledMethod;
1984         }
1985
1986         @Override
1987         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1988                         WarningSet warnings) {
1989
1990                 try {
1991                         double d = Double.parseDouble(s);
1992                         setMethod.invoke(c, d);
1993                         enabledMethod.invoke(c, true);
1994                 } catch (NumberFormatException e) {
1995                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1996                 }
1997         }
1998 }
1999
2000 ////  EnumSetter  -  sets a generic enum type
2001 class EnumSetter<T extends Enum<T>> implements Setter {
2002         private final Reflection.Method setter;
2003         private final Class<T> enumClass;
2004
2005         public EnumSetter(Reflection.Method set, Class<T> enumClass) {
2006                 this.setter = set;
2007                 this.enumClass = enumClass;
2008         }
2009
2010         @Override
2011         public void set(RocketComponent c, String name, HashMap<String, String> attributes,
2012                         WarningSet warnings) {
2013
2014                 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
2015                 if (setEnum == null) {
2016                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2017                         return;
2018                 }
2019
2020                 setter.invoke(c, setEnum);
2021         }
2022 }
2023
2024
2025 ////  ColorSetter  -  sets a Color value
2026 class ColorSetter implements Setter {
2027         private final Reflection.Method setMethod;
2028
2029         public ColorSetter(Reflection.Method set) {
2030                 setMethod = set;
2031         }
2032
2033         @Override
2034         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2035                         WarningSet warnings) {
2036
2037                 String red = attributes.get("red");
2038                 String green = attributes.get("green");
2039                 String blue = attributes.get("blue");
2040
2041                 if (red == null || green == null || blue == null) {
2042                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2043                         return;
2044                 }
2045
2046                 int r, g, b;
2047                 try {
2048                         r = Integer.parseInt(red);
2049                         g = Integer.parseInt(green);
2050                         b = Integer.parseInt(blue);
2051                 } catch (NumberFormatException e) {
2052                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2053                         return;
2054                 }
2055
2056                 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
2057                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2058                         return;
2059                 }
2060
2061                 Color color = new Color(r, g, b);
2062                 setMethod.invoke(c, color);
2063
2064                 if (!s.trim().equals("")) {
2065                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2066                 }
2067         }
2068 }
2069
2070 ////ComponentPresetSetter  -  sets a ComponentPreset value
2071 class ComponentPresetSetter implements Setter {
2072         private final Reflection.Method setMethod;
2073
2074         public ComponentPresetSetter(Reflection.Method set) {
2075                 this.setMethod = set;
2076         }
2077
2078         @Override
2079         public void set(RocketComponent c, String name, HashMap<String, String> attributes,
2080                         WarningSet warnings) {
2081                 // FIXME - probably need more data in the warning messages - like what component preset...
2082                 String manufacturerName = attributes.get("manufacturer");
2083                 if ( manufacturerName == null ) {
2084                         warnings.add(Warning.fromString("Invalid ComponentPreset, no manufacturer specified.  Ignored"));
2085                         return;
2086                 }
2087
2088                 String productNo = attributes.get("partno");
2089                 if ( productNo == null ) {
2090                         warnings.add(Warning.fromString("Invalid ComponentPreset, no partno specified.  Ignored"));
2091                         return;
2092                 }
2093
2094                 String digest = attributes.get("digest");
2095                 if ( digest == null ) {
2096                         warnings.add(Warning.fromString("Invalid ComponentPreset, no digest specified."));
2097                 }
2098
2099                 String type = attributes.get("type");
2100                 if ( type == null ) {
2101                         warnings.add(Warning.fromString("Invalid ComponentPreset, no type specified."));
2102                 }
2103
2104                 List<ComponentPreset> presets = Application.getComponentPresetDao().find( manufacturerName, productNo );
2105
2106                 ComponentPreset matchingPreset = null;
2107
2108                 for( ComponentPreset preset: presets ) {
2109                         if ( digest != null && preset.getDigest().equals(digest) ) {
2110                                 // Found one with matching digest.  Take it.
2111                                 matchingPreset = preset;
2112                                 break;
2113                         }
2114                         if ( type != null && preset.getType().name().equals(type) && matchingPreset != null) {
2115                                 // Found the first one with matching type.
2116                                 matchingPreset = preset;
2117                         }
2118                 }
2119
2120                 // Was any found?
2121                 if ( matchingPreset == null ) {
2122                         warnings.add(Warning.fromString("No matching ComponentPreset found " + manufacturerName + " " + productNo));
2123                         return;
2124                 }
2125
2126                 if ( digest != null && !matchingPreset.getDigest().equals(digest) ) {
2127                         warnings.add(Warning.fromString("ComponentPreset has wrong digest"));
2128                 }
2129
2130                 setMethod.invoke(c, matchingPreset);
2131         }
2132 }
2133
2134
2135 ////MaterialSetter  -  sets a Material value
2136 class MaterialSetter implements Setter {
2137         private final Reflection.Method setMethod;
2138         private final Material.Type type;
2139
2140         public MaterialSetter(Reflection.Method set, Material.Type type) {
2141                 this.setMethod = set;
2142                 this.type = type;
2143         }
2144
2145         @Override
2146         public void set(RocketComponent c, String name, HashMap<String, String> attributes,
2147                         WarningSet warnings) {
2148
2149                 Material mat;
2150
2151                 // Check name != ""
2152                 name = name.trim();
2153                 if (name.equals("")) {
2154                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2155                         return;
2156                 }
2157
2158                 // Parse density
2159                 double density;
2160                 String str;
2161                 str = attributes.remove("density");
2162                 if (str == null) {
2163                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2164                         return;
2165                 }
2166                 try {
2167                         density = Double.parseDouble(str);
2168                 } catch (NumberFormatException e) {
2169                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2170                         return;
2171                 }
2172
2173                 // Parse thickness
2174                 //              double thickness = 0;
2175                 //              str = attributes.remove("thickness");
2176                 //              try {
2177                 //                      if (str != null)
2178                 //                              thickness = Double.parseDouble(str);
2179                 //              } catch (NumberFormatException e){
2180                 //                      warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2181                 //                      return;
2182                 //              }
2183
2184                 // Check type if specified
2185                 str = attributes.remove("type");
2186                 if (str != null && !type.name().toLowerCase(Locale.ENGLISH).equals(str)) {
2187                         warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
2188                         return;
2189                 }
2190
2191                 String key = attributes.remove("key");
2192
2193                 mat = Databases.findMaterial(type, key, name, density);
2194
2195                 setMethod.invoke(c, mat);
2196         }
2197 }
2198
2199
2200
2201
2202 class PositionSetter implements Setter {
2203
2204         @Override
2205         public void set(RocketComponent c, String value, HashMap<String, String> attributes,
2206                         WarningSet warnings) {
2207
2208                 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
2209                                 RocketComponent.Position.class);
2210                 if (type == null) {
2211                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2212                         return;
2213                 }
2214
2215                 double pos;
2216                 try {
2217                         pos = Double.parseDouble(value);
2218                 } catch (NumberFormatException e) {
2219                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2220                         return;
2221                 }
2222
2223                 if (c instanceof FinSet) {
2224                         ((FinSet) c).setRelativePosition(type);
2225                         c.setPositionValue(pos);
2226                 } else if (c instanceof LaunchLug) {
2227                         ((LaunchLug) c).setRelativePosition(type);
2228                         c.setPositionValue(pos);
2229                 } else if (c instanceof InternalComponent) {
2230                         ((InternalComponent) c).setRelativePosition(type);
2231                         c.setPositionValue(pos);
2232                 } else {
2233                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2234                 }
2235
2236         }
2237 }
2238
2239
2240 class FinTabPositionSetter extends DoubleSetter {
2241
2242         public FinTabPositionSetter() {
2243                 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2244         }
2245
2246         @Override
2247         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2248                         WarningSet warnings) {
2249
2250                 if (!(c instanceof FinSet)) {
2251                         throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2252                 }
2253
2254                 String relative = attributes.get("relativeto");
2255                 FinSet.TabRelativePosition position =
2256                                 (TabRelativePosition) DocumentConfig.findEnum(relative,
2257                                                 FinSet.TabRelativePosition.class);
2258
2259                 if (position != null) {
2260
2261                         ((FinSet) c).setTabRelativePosition(position);
2262
2263                 } else {
2264                         if (relative == null) {
2265                                 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2266                         } else {
2267                                 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2268                         }
2269                 }
2270
2271                 super.set(c, s, attributes, warnings);
2272         }
2273
2274
2275 }
2276
2277
2278 class ClusterConfigurationSetter implements Setter {
2279
2280         @Override
2281         public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2282                         WarningSet warnings) {
2283
2284                 if (!(component instanceof Clusterable)) {
2285                         warnings.add("Illegal component defined as cluster.");
2286                         return;
2287                 }
2288
2289                 ClusterConfiguration config = null;
2290                 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2291                         if (c.getXMLName().equals(value)) {
2292                                 config = c;
2293                                 break;
2294                         }
2295                 }
2296
2297                 if (config == null) {
2298                         warnings.add("Illegal cluster configuration specified.");
2299                         return;
2300                 }
2301
2302                 ((Clusterable) component).setClusterConfiguration(config);
2303         }
2304 }