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