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