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