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