7719e0e2c4fbed9fe14d67430aea934464435426
[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.Simulation.Status;
18 import net.sf.openrocket.document.StorageOptions;
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.ExternalComponent.Finish;
39 import net.sf.openrocket.rocketcomponent.FinSet;
40 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
41 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
42 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
43 import net.sf.openrocket.rocketcomponent.InnerTube;
44 import net.sf.openrocket.rocketcomponent.InternalComponent;
45 import net.sf.openrocket.rocketcomponent.LaunchLug;
46 import net.sf.openrocket.rocketcomponent.MassComponent;
47 import net.sf.openrocket.rocketcomponent.MassObject;
48 import net.sf.openrocket.rocketcomponent.MotorMount;
49 import net.sf.openrocket.rocketcomponent.NoseCone;
50 import net.sf.openrocket.rocketcomponent.Parachute;
51 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
52 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
53 import net.sf.openrocket.rocketcomponent.ReferenceType;
54 import net.sf.openrocket.rocketcomponent.RingComponent;
55 import net.sf.openrocket.rocketcomponent.Rocket;
56 import net.sf.openrocket.rocketcomponent.RocketComponent;
57 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
58 import net.sf.openrocket.rocketcomponent.ShockCord;
59 import net.sf.openrocket.rocketcomponent.Stage;
60 import net.sf.openrocket.rocketcomponent.Streamer;
61 import net.sf.openrocket.rocketcomponent.StructuralComponent;
62 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
63 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
64 import net.sf.openrocket.rocketcomponent.Transition;
65 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
66 import net.sf.openrocket.rocketcomponent.TubeCoupler;
67 import net.sf.openrocket.simulation.FlightData;
68 import net.sf.openrocket.simulation.FlightDataBranch;
69 import net.sf.openrocket.simulation.FlightDataType;
70 import net.sf.openrocket.simulation.FlightEvent;
71 import net.sf.openrocket.simulation.FlightEvent.Type;
72 import net.sf.openrocket.simulation.SimulationOptions;
73 import net.sf.openrocket.startup.Application;
74 import net.sf.openrocket.unit.UnitGroup;
75 import net.sf.openrocket.util.BugException;
76 import net.sf.openrocket.util.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.findMethod(RocketComponent.class, "setName", String.class)));
210                 setters.put("RocketComponent:color", new ColorSetter(
211                                 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
212                 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
213                                 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
214                                 LineStyle.class));
215                 setters.put("RocketComponent:position", new PositionSetter());
216                 setters.put("RocketComponent:overridemass", new OverrideSetter(
217                                 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
218                                 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
219                 setters.put("RocketComponent:overridecg", new OverrideSetter(
220                                 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
221                                 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
222                 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
223                                 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
224                 setters.put("RocketComponent:comment", new StringSetter(
225                                 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
226                 
227                 // ExternalComponent
228                 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
229                                 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
230                                 Finish.class));
231                 setters.put("ExternalComponent:material", new MaterialSetter(
232                                 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
233                                 Material.Type.BULK));
234                 
235                 // BodyComponent
236                 setters.put("BodyComponent:length", new DoubleSetter(
237                                 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
238                 
239                 // SymmetricComponent
240                 setters.put("SymmetricComponent:thickness", new DoubleSetter(
241                                 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
242                                 "filled",
243                                 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
244                 
245                 // BodyTube
246                 setters.put("BodyTube:radius", new DoubleSetter(
247                                 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
248                                 "auto",
249                                 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
250                 
251                 // Transition
252                 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
253                                 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
254                                 Transition.Shape.class));
255                 setters.put("Transition:shapeclipped", new BooleanSetter(
256                                 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
257                 setters.put("Transition:shapeparameter", new DoubleSetter(
258                                 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
259                 
260                 setters.put("Transition:foreradius", new DoubleSetter(
261                                 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
262                                 "auto",
263                                 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
264                 setters.put("Transition:aftradius", new DoubleSetter(
265                                 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
266                                 "auto",
267                                 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
268                 
269                 setters.put("Transition:foreshoulderradius", new DoubleSetter(
270                                 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
271                 setters.put("Transition:foreshoulderlength", new DoubleSetter(
272                                 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
273                 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
274                                 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
275                 setters.put("Transition:foreshouldercapped", new BooleanSetter(
276                                 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
277                 
278                 setters.put("Transition:aftshoulderradius", new DoubleSetter(
279                                 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
280                 setters.put("Transition:aftshoulderlength", new DoubleSetter(
281                                 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
282                 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
283                                 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
284                 setters.put("Transition:aftshouldercapped", new BooleanSetter(
285                                 Reflection.findMethod(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.findMethod(FinSet.class, "setFinCount", int.class)));
297                 setters.put("FinSet:rotation", new DoubleSetter(
298                                 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
299                 setters.put("FinSet:thickness", new DoubleSetter(
300                                 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
301                 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
302                                 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
303                                 FinSet.CrossSection.class));
304                 setters.put("FinSet:cant", new DoubleSetter(
305                                 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
306                 setters.put("FinSet:tabheight", new DoubleSetter(
307                                 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
308                 setters.put("FinSet:tablength", new DoubleSetter(
309                                 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
310                 setters.put("FinSet:tabposition", new FinTabPositionSetter());
311                 
312                 // TrapezoidFinSet
313                 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
314                                 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
315                 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
316                                 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
317                 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
318                                 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
319                 setters.put("TrapezoidFinSet:height", new DoubleSetter(
320                                 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
321                 
322                 // EllipticalFinSet
323                 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
324                                 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
325                 setters.put("EllipticalFinSet:height", new DoubleSetter(
326                                 Reflection.findMethod(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.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
333                 setters.put("LaunchLug:length", new DoubleSetter(
334                                 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
335                 setters.put("LaunchLug:thickness", new DoubleSetter(
336                                 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
337                 setters.put("LaunchLug:radialdirection", new DoubleSetter(
338                                 Reflection.findMethod(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.findMethod(StructuralComponent.class, "setMaterial", Material.class),
346                                 Material.Type.BULK));
347                 
348                 // RingComponent
349                 setters.put("RingComponent:length", new DoubleSetter(
350                                 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
351                 setters.put("RingComponent:radialposition", new DoubleSetter(
352                                 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
353                 setters.put("RingComponent:radialdirection", new DoubleSetter(
354                                 Reflection.findMethod(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.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
360                 
361                 // EngineBlock
362                 setters.put("EngineBlock:outerradius", new DoubleSetter(
363                                 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
364                                 "auto",
365                                 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
366                 
367                 // TubeCoupler
368                 setters.put("TubeCoupler:outerradius", new DoubleSetter(
369                                 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
370                                 "auto",
371                                 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
372                 
373                 // InnerTube
374                 setters.put("InnerTube:outerradius", new DoubleSetter(
375                                 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
376                 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
377                 setters.put("InnerTube:clusterscale", new DoubleSetter(
378                                 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
379                 setters.put("InnerTube:clusterrotation", new DoubleSetter(
380                                 Reflection.findMethod(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.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
388                 setters.put("Bulkhead:outerradius", new DoubleSetter(
389                                 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
390                                 "auto",
391                                 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
392                 
393                 // CenteringRing
394                 setters.put("CenteringRing:innerradius", new DoubleSetter(
395                                 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
396                                 "auto",
397                                 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
398                 setters.put("CenteringRing:outerradius", new DoubleSetter(
399                                 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
400                                 "auto",
401                                 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
402                 
403
404                 // MassObject
405                 setters.put("MassObject:packedlength", new DoubleSetter(
406                                 Reflection.findMethod(MassObject.class, "setLength", double.class)));
407                 setters.put("MassObject:packedradius", new DoubleSetter(
408                                 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
409                 setters.put("MassObject:radialposition", new DoubleSetter(
410                                 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
411                 setters.put("MassObject:radialdirection", new DoubleSetter(
412                                 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
413                                 Math.PI / 180.0));
414                 
415                 // MassComponent
416                 setters.put("MassComponent:mass", new DoubleSetter(
417                                 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
418                 
419                 // ShockCord
420                 setters.put("ShockCord:cordlength", new DoubleSetter(
421                                 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
422                 setters.put("ShockCord:material", new MaterialSetter(
423                                 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
424                                 Material.Type.LINE));
425                 
426                 // RecoveryDevice
427                 setters.put("RecoveryDevice:cd", new DoubleSetter(
428                                 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
429                                 "auto",
430                                 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
431                 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
432                                 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
433                                 RecoveryDevice.DeployEvent.class));
434                 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
435                                 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
436                 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
437                                 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
438                 setters.put("RecoveryDevice:material", new MaterialSetter(
439                                 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
440                                 Material.Type.SURFACE));
441                 
442                 // Parachute
443                 setters.put("Parachute:diameter", new DoubleSetter(
444                                 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
445                 setters.put("Parachute:linecount", new IntSetter(
446                                 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
447                 setters.put("Parachute:linelength", new DoubleSetter(
448                                 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
449                 setters.put("Parachute:linematerial", new MaterialSetter(
450                                 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
451                                 Material.Type.LINE));
452                 
453                 // Streamer
454                 setters.put("Streamer:striplength", new DoubleSetter(
455                                 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
456                 setters.put("Streamer:stripwidth", new DoubleSetter(
457                                 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
458                 
459                 // Rocket
460                 // <motorconfiguration> handled by separate handler
461                 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
462                                 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
463                                 ReferenceType.class));
464                 setters.put("Rocket:customreference", new DoubleSetter(
465                                 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
466                 setters.put("Rocket:designer", new StringSetter(
467                                 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
468                 setters.put("Rocket:revision", new StringSetter(
469                                 Reflection.findMethod(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                                 s.set(component, content, attributes, warnings);
757                                 break;
758                         }
759                         if (DocumentConfig.setters.containsKey(setterKey)) {
760                                 // Key exists but is null -> invalid parameter
761                                 c = null;
762                                 break;
763                         }
764                 }
765                 if (c == null) {
766                         warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
767                                         + component.getComponentName() + ", ignoring."));
768                 }
769         }
770 }
771
772
773 /**
774  * A handler that reads the <point> specifications within the freeformfinset's
775  * <finpoints> elements.
776  */
777 class FinSetPointHandler extends ElementHandler {
778         private final FreeformFinSet finset;
779         private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
780         
781         public FinSetPointHandler(FreeformFinSet finset) {
782                 this.finset = finset;
783         }
784         
785         @Override
786         public ElementHandler openElement(String element, HashMap<String, String> attributes,
787                         WarningSet warnings) {
788                 return PlainTextHandler.INSTANCE;
789         }
790         
791         
792         @Override
793         public void closeElement(String element, HashMap<String, String> attributes,
794                         String content, WarningSet warnings) throws SAXException {
795                 
796                 String strx = attributes.remove("x");
797                 String stry = attributes.remove("y");
798                 if (strx == null || stry == null) {
799                         warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
800                         return;
801                 }
802                 try {
803                         double x = Double.parseDouble(strx);
804                         double y = Double.parseDouble(stry);
805                         coordinates.add(new Coordinate(x, y));
806                 } catch (NumberFormatException e) {
807                         warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
808                         return;
809                 }
810                 
811                 super.closeElement(element, attributes, content, warnings);
812         }
813         
814         @Override
815         public void endHandler(String element, HashMap<String, String> attributes,
816                         String content, WarningSet warnings) {
817                 try {
818                         finset.setPoints(coordinates.toArray(new Coordinate[0]));
819                 } catch (IllegalFinPointException e) {
820                         warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
821                 }
822         }
823 }
824
825
826 class MotorMountHandler extends ElementHandler {
827         private final MotorMount mount;
828         private MotorHandler motorHandler;
829         
830         public MotorMountHandler(MotorMount mount) {
831                 this.mount = mount;
832                 mount.setMotorMount(true);
833         }
834         
835         @Override
836         public ElementHandler openElement(String element, HashMap<String, String> attributes,
837                         WarningSet warnings) {
838                 
839                 if (element.equals("motor")) {
840                         motorHandler = new MotorHandler();
841                         return motorHandler;
842                 }
843                 
844                 if (element.equals("ignitionevent") ||
845                                 element.equals("ignitiondelay") ||
846                                 element.equals("overhang")) {
847                         return PlainTextHandler.INSTANCE;
848                 }
849                 
850                 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
851                 return null;
852         }
853         
854         
855
856         @Override
857         public void closeElement(String element, HashMap<String, String> attributes,
858                         String content, WarningSet warnings) throws SAXException {
859                 
860                 if (element.equals("motor")) {
861                         String id = attributes.get("configid");
862                         if (id == null || id.equals("")) {
863                                 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
864                                 return;
865                         }
866                         
867                         Motor motor = motorHandler.getMotor(warnings);
868                         mount.setMotor(id, motor);
869                         mount.setMotorDelay(id, motorHandler.getDelay(warnings));
870                         return;
871                 }
872                 
873                 if (element.equals("ignitionevent")) {
874                         MotorMount.IgnitionEvent event = null;
875                         for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
876                                 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
877                                         event = e;
878                                         break;
879                                 }
880                         }
881                         if (event == null) {
882                                 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
883                                 return;
884                         }
885                         mount.setIgnitionEvent(event);
886                         return;
887                 }
888                 
889                 if (element.equals("ignitiondelay")) {
890                         double d;
891                         try {
892                                 d = Double.parseDouble(content);
893                         } catch (NumberFormatException nfe) {
894                                 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
895                                 return;
896                         }
897                         mount.setIgnitionDelay(d);
898                         return;
899                 }
900                 
901                 if (element.equals("overhang")) {
902                         double d;
903                         try {
904                                 d = Double.parseDouble(content);
905                         } catch (NumberFormatException nfe) {
906                                 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
907                                 return;
908                         }
909                         mount.setMotorOverhang(d);
910                         return;
911                 }
912                 
913                 super.closeElement(element, attributes, content, warnings);
914         }
915 }
916
917
918
919
920 class MotorConfigurationHandler extends ElementHandler {
921         private final Rocket rocket;
922         private String name = null;
923         private boolean inNameElement = false;
924         
925         public MotorConfigurationHandler(Rocket rocket) {
926                 this.rocket = rocket;
927         }
928         
929         @Override
930         public ElementHandler openElement(String element, HashMap<String, String> attributes,
931                         WarningSet warnings) {
932                 
933                 if (inNameElement || !element.equals("name")) {
934                         warnings.add(Warning.FILE_INVALID_PARAMETER);
935                         return null;
936                 }
937                 inNameElement = true;
938                 
939                 return PlainTextHandler.INSTANCE;
940         }
941         
942         @Override
943         public void closeElement(String element, HashMap<String, String> attributes,
944                         String content, WarningSet warnings) {
945                 name = content;
946         }
947         
948         @Override
949         public void endHandler(String element, HashMap<String, String> attributes,
950                         String content, WarningSet warnings) throws SAXException {
951                 
952                 String configid = attributes.remove("configid");
953                 if (configid == null || configid.equals("")) {
954                         warnings.add(Warning.FILE_INVALID_PARAMETER);
955                         return;
956                 }
957                 
958                 if (!rocket.addMotorConfigurationID(configid)) {
959                         warnings.add("Duplicate motor configuration ID used.");
960                         return;
961                 }
962                 
963                 if (name != null && name.trim().length() > 0) {
964                         rocket.setMotorConfigurationName(configid, name);
965                 }
966                 
967                 if ("true".equals(attributes.remove("default"))) {
968                         rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
969                 }
970                 
971                 super.closeElement(element, attributes, content, warnings);
972         }
973 }
974
975
976 class MotorHandler extends ElementHandler {
977         private Motor.Type type = null;
978         private String manufacturer = null;
979         private String designation = null;
980         private String digest = null;
981         private double diameter = Double.NaN;
982         private double length = Double.NaN;
983         private double delay = Double.NaN;
984         
985         @Override
986         public ElementHandler openElement(String element, HashMap<String, String> attributes,
987                         WarningSet warnings) {
988                 return PlainTextHandler.INSTANCE;
989         }
990         
991         
992         /**
993          * Return the motor to use, or null.
994          */
995         public Motor getMotor(WarningSet warnings) {
996                 if (designation == null) {
997                         warnings.add(Warning.fromString("No motor specified, ignoring."));
998                         return null;
999                 }
1000                 
1001                 List<ThrustCurveMotor> motors = Application.getMotorSetDatabase().findMotors(type, manufacturer,
1002                                 designation, diameter, length);
1003                 
1004                 // No motors
1005                 if (motors.size() == 0) {
1006                         String str = "No motor with designation '" + designation + "'";
1007                         if (manufacturer != null)
1008                                 str += " for manufacturer '" + manufacturer + "'";
1009                         str += " found.";
1010                         warnings.add(str);
1011                         return null;
1012                 }
1013                 
1014                 // One motor
1015                 if (motors.size() == 1) {
1016                         ThrustCurveMotor m = motors.get(0);
1017                         if (digest != null && !MotorDigest.digestMotor(m).equals(digest)) {
1018                                 String str = "Motor with designation '" + designation + "'";
1019                                 if (manufacturer != null)
1020                                         str += " for manufacturer '" + manufacturer + "'";
1021                                 str += " has differing thrust curve than the original.";
1022                                 warnings.add(str);
1023                         }
1024                         return m;
1025                 }
1026                 
1027                 // Multiple motors, check digest for which one to use
1028                 if (digest != null) {
1029                         
1030                         // Check for motor with correct digest
1031                         for (ThrustCurveMotor m : motors) {
1032                                 if (MotorDigest.digestMotor(m).equals(digest)) {
1033                                         return m;
1034                                 }
1035                         }
1036                         String str = "Motor with designation '" + designation + "'";
1037                         if (manufacturer != null)
1038                                 str += " for manufacturer '" + manufacturer + "'";
1039                         str += " has differing thrust curve than the original.";
1040                         warnings.add(str);
1041                         
1042                 } else {
1043                         
1044                         // No digest, check for preferred digest (OpenRocket <= 1.1.0)
1045                         // TODO: MEDIUM: This should only be done for document versions 1.1 and below
1046                         for (ThrustCurveMotor m : motors) {
1047                                 if (PreferredMotorDigests.DIGESTS.contains(MotorDigest.digestMotor(m))) {
1048                                         return m;
1049                                 }
1050                         }
1051                         
1052                         String str = "Multiple motors with designation '" + designation + "'";
1053                         if (manufacturer != null)
1054                                 str += " for manufacturer '" + manufacturer + "'";
1055                         str += " found, one chosen arbitrarily.";
1056                         warnings.add(str);
1057                         
1058                 }
1059                 return motors.get(0);
1060         }
1061         
1062         /**
1063          * Return the delay to use for the motor.
1064          */
1065         public double getDelay(WarningSet warnings) {
1066                 if (Double.isNaN(delay)) {
1067                         warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1068                         return Motor.PLUGGED;
1069                 }
1070                 return delay;
1071         }
1072         
1073         
1074         @Override
1075         public void closeElement(String element, HashMap<String, String> attributes,
1076                         String content, WarningSet warnings) throws SAXException {
1077                 
1078                 content = content.trim();
1079                 
1080                 if (element.equals("type")) {
1081                         
1082                         // Motor type
1083                         type = null;
1084                         for (Motor.Type t : Motor.Type.values()) {
1085                                 if (t.name().toLowerCase().equals(content.trim())) {
1086                                         type = t;
1087                                         break;
1088                                 }
1089                         }
1090                         if (type == null) {
1091                                 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1092                         }
1093                         
1094                 } else if (element.equals("manufacturer")) {
1095                         
1096                         // Manufacturer
1097                         manufacturer = content.trim();
1098                         
1099                 } else if (element.equals("designation")) {
1100                         
1101                         // Designation
1102                         designation = content.trim();
1103                         
1104                 } else if (element.equals("digest")) {
1105                         
1106                         // Digest
1107                         digest = content.trim();
1108                         
1109                 } else if (element.equals("diameter")) {
1110                         
1111                         // Diameter
1112                         diameter = Double.NaN;
1113                         try {
1114                                 diameter = Double.parseDouble(content.trim());
1115                         } catch (NumberFormatException e) {
1116                                 // Ignore
1117                         }
1118                         if (Double.isNaN(diameter)) {
1119                                 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1120                         }
1121                         
1122                 } else if (element.equals("length")) {
1123                         
1124                         // Length
1125                         length = Double.NaN;
1126                         try {
1127                                 length = Double.parseDouble(content.trim());
1128                         } catch (NumberFormatException ignore) {
1129                         }
1130                         
1131                         if (Double.isNaN(length)) {
1132                                 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1133                         }
1134                         
1135                 } else if (element.equals("delay")) {
1136                         
1137                         // Delay
1138                         delay = Double.NaN;
1139                         if (content.equals("none")) {
1140                                 delay = Motor.PLUGGED;
1141                         } else {
1142                                 try {
1143                                         delay = Double.parseDouble(content.trim());
1144                                 } catch (NumberFormatException ignore) {
1145                                 }
1146                                 
1147                                 if (Double.isNaN(delay)) {
1148                                         warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1149                                 }
1150                                 
1151                         }
1152                         
1153                 } else {
1154                         super.closeElement(element, attributes, content, warnings);
1155                 }
1156         }
1157         
1158 }
1159
1160
1161
1162 class SimulationsHandler extends ElementHandler {
1163         private final OpenRocketDocument doc;
1164         private SingleSimulationHandler handler;
1165         
1166         public SimulationsHandler(OpenRocketDocument doc) {
1167                 this.doc = doc;
1168         }
1169         
1170         @Override
1171         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1172                         WarningSet warnings) {
1173                 
1174                 if (!element.equals("simulation")) {
1175                         warnings.add("Unknown element '" + element + "', ignoring.");
1176                         return null;
1177                 }
1178                 
1179                 handler = new SingleSimulationHandler(doc);
1180                 return handler;
1181         }
1182         
1183         @Override
1184         public void closeElement(String element, HashMap<String, String> attributes,
1185                         String content, WarningSet warnings) throws SAXException {
1186                 attributes.remove("status");
1187                 super.closeElement(element, attributes, content, warnings);
1188         }
1189         
1190
1191 }
1192
1193 class SingleSimulationHandler extends ElementHandler {
1194         
1195         private final OpenRocketDocument doc;
1196         
1197         private String name;
1198         
1199         private SimulationConditionsHandler conditionHandler;
1200         private FlightDataHandler dataHandler;
1201         
1202         private final List<String> listeners = new ArrayList<String>();
1203         
1204         public SingleSimulationHandler(OpenRocketDocument doc) {
1205                 this.doc = doc;
1206         }
1207         
1208         
1209
1210         @Override
1211         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1212                         WarningSet warnings) {
1213                 
1214                 if (element.equals("name") || element.equals("simulator") ||
1215                                 element.equals("calculator") || element.equals("listener")) {
1216                         return PlainTextHandler.INSTANCE;
1217                 } else if (element.equals("conditions")) {
1218                         conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1219                         return conditionHandler;
1220                 } else if (element.equals("flightdata")) {
1221                         dataHandler = new FlightDataHandler();
1222                         return dataHandler;
1223                 } else {
1224                         warnings.add("Unknown element '" + element + "', ignoring.");
1225                         return null;
1226                 }
1227         }
1228         
1229         @Override
1230         public void closeElement(String element, HashMap<String, String> attributes,
1231                         String content, WarningSet warnings) {
1232                 
1233                 if (element.equals("name")) {
1234                         name = content;
1235                 } else if (element.equals("simulator")) {
1236                         if (!content.trim().equals("RK4Simulator")) {
1237                                 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1238                         }
1239                 } else if (element.equals("calculator")) {
1240                         if (!content.trim().equals("BarrowmanCalculator")) {
1241                                 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1242                         }
1243                 } else if (element.equals("listener") && content.trim().length() > 0) {
1244                         listeners.add(content.trim());
1245                 }
1246                 
1247         }
1248         
1249         @Override
1250         public void endHandler(String element, HashMap<String, String> attributes,
1251                         String content, WarningSet warnings) {
1252                 
1253                 String s = attributes.get("status");
1254                 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1255                 if (status == null) {
1256                         warnings.add("Simulation status unknown, assuming outdated.");
1257                         status = Simulation.Status.OUTDATED;
1258                 }
1259                 
1260                 SimulationOptions conditions;
1261                 if (conditionHandler != null) {
1262                         conditions = conditionHandler.getConditions();
1263                 } else {
1264                         warnings.add("Simulation conditions not defined, using defaults.");
1265                         conditions = new SimulationOptions(doc.getRocket());
1266                 }
1267                 
1268                 if (name == null)
1269                         name = "Simulation";
1270                 
1271                 FlightData data;
1272                 if (dataHandler == null)
1273                         data = null;
1274                 else
1275                         data = dataHandler.getFlightData();
1276                 
1277                 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1278                                 conditions, listeners, data);
1279                 
1280                 doc.addSimulation(simulation);
1281         }
1282 }
1283
1284
1285
1286 class SimulationConditionsHandler extends ElementHandler {
1287         private SimulationOptions conditions;
1288         private AtmosphereHandler atmosphereHandler;
1289         
1290         public SimulationConditionsHandler(Rocket rocket) {
1291                 conditions = new SimulationOptions(rocket);
1292         }
1293         
1294         public SimulationOptions getConditions() {
1295                 return conditions;
1296         }
1297         
1298         @Override
1299         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1300                         WarningSet warnings) {
1301                 if (element.equals("atmosphere")) {
1302                         atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1303                         return atmosphereHandler;
1304                 }
1305                 return PlainTextHandler.INSTANCE;
1306         }
1307         
1308         @Override
1309         public void closeElement(String element, HashMap<String, String> attributes,
1310                         String content, WarningSet warnings) {
1311                 
1312                 double d = Double.NaN;
1313                 try {
1314                         d = Double.parseDouble(content);
1315                 } catch (NumberFormatException ignore) {
1316                 }
1317                 
1318
1319                 if (element.equals("configid")) {
1320                         if (content.equals("")) {
1321                                 conditions.setMotorConfigurationID(null);
1322                         } else {
1323                                 conditions.setMotorConfigurationID(content);
1324                         }
1325                 } else if (element.equals("launchrodlength")) {
1326                         if (Double.isNaN(d)) {
1327                                 warnings.add("Illegal launch rod length defined, ignoring.");
1328                         } else {
1329                                 conditions.setLaunchRodLength(d);
1330                         }
1331                 } else if (element.equals("launchrodangle")) {
1332                         if (Double.isNaN(d)) {
1333                                 warnings.add("Illegal launch rod angle defined, ignoring.");
1334                         } else {
1335                                 conditions.setLaunchRodAngle(d * Math.PI / 180);
1336                         }
1337                 } else if (element.equals("launchroddirection")) {
1338                         if (Double.isNaN(d)) {
1339                                 warnings.add("Illegal launch rod direction defined, ignoring.");
1340                         } else {
1341                                 conditions.setLaunchRodDirection(d * Math.PI / 180);
1342                         }
1343                 } else if (element.equals("windaverage")) {
1344                         if (Double.isNaN(d)) {
1345                                 warnings.add("Illegal average windspeed defined, ignoring.");
1346                         } else {
1347                                 conditions.setWindSpeedAverage(d);
1348                         }
1349                 } else if (element.equals("windturbulence")) {
1350                         if (Double.isNaN(d)) {
1351                                 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1352                         } else {
1353                                 conditions.setWindTurbulenceIntensity(d);
1354                         }
1355                 } else if (element.equals("launchaltitude")) {
1356                         if (Double.isNaN(d)) {
1357                                 warnings.add("Illegal launch altitude defined, ignoring.");
1358                         } else {
1359                                 conditions.setLaunchAltitude(d);
1360                         }
1361                 } else if (element.equals("launchlatitude")) {
1362                         if (Double.isNaN(d)) {
1363                                 warnings.add("Illegal launch latitude defined, ignoring.");
1364                         } else {
1365                                 conditions.setLaunchLatitude(d);
1366                         }
1367                 } else if (element.equals("atmosphere")) {
1368                         atmosphereHandler.storeSettings(conditions, warnings);
1369                 } else if (element.equals("timestep")) {
1370                         if (Double.isNaN(d)) {
1371                                 warnings.add("Illegal time step defined, ignoring.");
1372                         } else {
1373                                 conditions.setTimeStep(d);
1374                         }
1375                 }
1376         }
1377 }
1378
1379
1380 class AtmosphereHandler extends ElementHandler {
1381         private final String model;
1382         private double temperature = Double.NaN;
1383         private double pressure = Double.NaN;
1384         
1385         public AtmosphereHandler(String model) {
1386                 this.model = model;
1387         }
1388         
1389         @Override
1390         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1391                         WarningSet warnings) {
1392                 return PlainTextHandler.INSTANCE;
1393         }
1394         
1395         @Override
1396         public void closeElement(String element, HashMap<String, String> attributes,
1397                         String content, WarningSet warnings) throws SAXException {
1398                 
1399                 double d = Double.NaN;
1400                 try {
1401                         d = Double.parseDouble(content);
1402                 } catch (NumberFormatException ignore) {
1403                 }
1404                 
1405                 if (element.equals("basetemperature")) {
1406                         if (Double.isNaN(d)) {
1407                                 warnings.add("Illegal base temperature specified, ignoring.");
1408                         }
1409                         temperature = d;
1410                 } else if (element.equals("basepressure")) {
1411                         if (Double.isNaN(d)) {
1412                                 warnings.add("Illegal base pressure specified, ignoring.");
1413                         }
1414                         pressure = d;
1415                 } else {
1416                         super.closeElement(element, attributes, content, warnings);
1417                 }
1418         }
1419         
1420         
1421         public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1422                 if (!Double.isNaN(pressure)) {
1423                         cond.setLaunchPressure(pressure);
1424                 }
1425                 if (!Double.isNaN(temperature)) {
1426                         cond.setLaunchTemperature(temperature);
1427                 }
1428                 
1429                 if ("isa".equals(model)) {
1430                         cond.setISAAtmosphere(true);
1431                 } else if ("extendedisa".equals(model)) {
1432                         cond.setISAAtmosphere(false);
1433                 } else {
1434                         cond.setISAAtmosphere(true);
1435                         warnings.add("Unknown atmospheric model, using ISA.");
1436                 }
1437         }
1438         
1439 }
1440
1441
1442 class FlightDataHandler extends ElementHandler {
1443         
1444         private FlightDataBranchHandler dataHandler;
1445         private WarningSet warningSet = new WarningSet();
1446         private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1447         
1448         private FlightData data;
1449         
1450         public FlightData getFlightData() {
1451                 return data;
1452         }
1453         
1454         @Override
1455         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1456                         WarningSet warnings) {
1457                 
1458                 if (element.equals("warning")) {
1459                         return PlainTextHandler.INSTANCE;
1460                 }
1461                 if (element.equals("databranch")) {
1462                         if (attributes.get("name") == null || attributes.get("types") == null) {
1463                                 warnings.add("Illegal flight data definition, ignoring.");
1464                                 return null;
1465                         }
1466                         dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1467                                         attributes.get("types"));
1468                         return dataHandler;
1469                 }
1470                 
1471                 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1472                 return null;
1473         }
1474         
1475         
1476         @Override
1477         public void closeElement(String element, HashMap<String, String> attributes,
1478                         String content, WarningSet warnings) {
1479                 
1480                 if (element.equals("databranch")) {
1481                         FlightDataBranch branch = dataHandler.getBranch();
1482                         if (branch.getLength() > 0) {
1483                                 branches.add(branch);
1484                         }
1485                 } else if (element.equals("warning")) {
1486                         warningSet.add(Warning.fromString(content));
1487                 }
1488         }
1489         
1490         
1491         @Override
1492         public void endHandler(String element, HashMap<String, String> attributes,
1493                         String content, WarningSet warnings) {
1494                 
1495                 if (branches.size() > 0) {
1496                         data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1497                 } else {
1498                         double maxAltitude = Double.NaN;
1499                         double maxVelocity = Double.NaN;
1500                         double maxAcceleration = Double.NaN;
1501                         double maxMach = Double.NaN;
1502                         double timeToApogee = Double.NaN;
1503                         double flightTime = Double.NaN;
1504                         double groundHitVelocity = Double.NaN;
1505                         
1506                         try {
1507                                 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1508                         } catch (NumberFormatException ignore) {
1509                         }
1510                         try {
1511                                 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1512                         } catch (NumberFormatException ignore) {
1513                         }
1514                         try {
1515                                 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1516                         } catch (NumberFormatException ignore) {
1517                         }
1518                         try {
1519                                 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1520                         } catch (NumberFormatException ignore) {
1521                         }
1522                         try {
1523                                 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1524                         } catch (NumberFormatException ignore) {
1525                         }
1526                         try {
1527                                 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1528                         } catch (NumberFormatException ignore) {
1529                         }
1530                         try {
1531                                 groundHitVelocity =
1532                                                 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1533                         } catch (NumberFormatException ignore) {
1534                         }
1535                         
1536                         // TODO: HIGH: Store and load launchRodVelocity
1537                         data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1538                                         timeToApogee, flightTime, groundHitVelocity, Double.NaN);
1539                 }
1540                 
1541                 data.getWarningSet().addAll(warningSet);
1542                 data.immute();
1543         }
1544         
1545
1546 }
1547
1548
1549 class FlightDataBranchHandler extends ElementHandler {
1550         private final FlightDataType[] types;
1551         private final FlightDataBranch branch;
1552         
1553         public FlightDataBranchHandler(String name, String typeList) {
1554                 String[] split = typeList.split(",");
1555                 types = new FlightDataType[split.length];
1556                 for (int i = 0; i < split.length; i++) {
1557                         types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1558                 }
1559                 
1560                 // TODO: LOW: May throw an IllegalArgumentException
1561                 branch = new FlightDataBranch(name, types);
1562         }
1563         
1564         public FlightDataBranch getBranch() {
1565                 branch.immute();
1566                 return branch;
1567         }
1568         
1569         @Override
1570         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1571                         WarningSet warnings) {
1572                 
1573                 if (element.equals("datapoint"))
1574                         return PlainTextHandler.INSTANCE;
1575                 if (element.equals("event"))
1576                         return PlainTextHandler.INSTANCE;
1577                 
1578                 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1579                 return null;
1580         }
1581         
1582         
1583         @Override
1584         public void closeElement(String element, HashMap<String, String> attributes,
1585                         String content, WarningSet warnings) {
1586                 
1587                 if (element.equals("event")) {
1588                         double time;
1589                         FlightEvent.Type type;
1590                         
1591                         try {
1592                                 time = DocumentConfig.stringToDouble(attributes.get("time"));
1593                         } catch (NumberFormatException e) {
1594                                 warnings.add("Illegal event specification, ignoring.");
1595                                 return;
1596                         }
1597                         
1598                         type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1599                         if (type == null) {
1600                                 warnings.add("Illegal event specification, ignoring.");
1601                                 return;
1602                         }
1603                         
1604                         branch.addEvent(new FlightEvent(type, time));
1605                         return;
1606                 }
1607                 
1608                 if (!element.equals("datapoint")) {
1609                         warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1610                         return;
1611                 }
1612                 
1613                 // element == "datapoint"
1614                 
1615
1616                 // Check line format
1617                 String[] split = content.split(",");
1618                 if (split.length != types.length) {
1619                         warnings.add("Data point did not contain correct amount of values, ignoring point.");
1620                         return;
1621                 }
1622                 
1623                 // Parse the doubles
1624                 double[] values = new double[split.length];
1625                 for (int i = 0; i < values.length; i++) {
1626                         try {
1627                                 values[i] = DocumentConfig.stringToDouble(split[i]);
1628                         } catch (NumberFormatException e) {
1629                                 warnings.add("Data point format error, ignoring point.");
1630                                 return;
1631                         }
1632                 }
1633                 
1634                 // Add point to branch
1635                 branch.addPoint();
1636                 for (int i = 0; i < types.length; i++) {
1637                         branch.setValue(types[i], values[i]);
1638                 }
1639         }
1640 }
1641
1642
1643
1644
1645
1646 /////////////////    Setters implementation
1647
1648
1649 ////  Interface
1650 interface Setter {
1651         /**
1652          * Set the specified value to the given component.
1653          * 
1654          * @param component             the component to which to set.
1655          * @param value                 the value within the element.
1656          * @param attributes    attributes for the element.
1657          * @param warnings              the warning set to use.
1658          */
1659         public void set(RocketComponent component, String value,
1660                         HashMap<String, String> attributes, WarningSet warnings);
1661 }
1662
1663
1664 ////  StringSetter - sets the value to the contained String
1665 class StringSetter implements Setter {
1666         private final Reflection.Method setMethod;
1667         
1668         public StringSetter(Reflection.Method set) {
1669                 setMethod = set;
1670         }
1671         
1672         @Override
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         @Override
1688         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1689                         WarningSet warnings) {
1690                 try {
1691                         int n = Integer.parseInt(s);
1692                         setMethod.invoke(c, n);
1693                 } catch (NumberFormatException e) {
1694                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1695                 }
1696         }
1697 }
1698
1699
1700 //// BooleanSetter - set a boolean value
1701 class BooleanSetter implements Setter {
1702         private final Reflection.Method setMethod;
1703         
1704         public BooleanSetter(Reflection.Method set) {
1705                 setMethod = set;
1706         }
1707         
1708         @Override
1709         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1710                         WarningSet warnings) {
1711                 
1712                 s = s.trim();
1713                 if (s.equalsIgnoreCase("true")) {
1714                         setMethod.invoke(c, true);
1715                 } else if (s.equalsIgnoreCase("false")) {
1716                         setMethod.invoke(c, false);
1717                 } else {
1718                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1719                 }
1720         }
1721 }
1722
1723
1724
1725 ////  DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1726 ////  calls a setXXX(boolean) method.
1727 class DoubleSetter implements Setter {
1728         private final Reflection.Method setMethod;
1729         private final String specialString;
1730         private final Reflection.Method specialMethod;
1731         private final double multiplier;
1732         
1733         /**
1734          * Set only the double value.
1735          * @param set   set method for the double value. 
1736          */
1737         public DoubleSetter(Reflection.Method set) {
1738                 this.setMethod = set;
1739                 this.specialString = null;
1740                 this.specialMethod = null;
1741                 this.multiplier = 1.0;
1742         }
1743         
1744         /**
1745          * Multiply with the given multiplier and set the double value.
1746          * @param set   set method for the double value.
1747          * @param mul   multiplier.
1748          */
1749         public DoubleSetter(Reflection.Method set, double mul) {
1750                 this.setMethod = set;
1751                 this.specialString = null;
1752                 this.specialMethod = null;
1753                 this.multiplier = mul;
1754         }
1755         
1756         /**
1757          * Set the double value, or if the value equals the special string, use the
1758          * special setter and set it to true.
1759          * 
1760          * @param set                   double setter.
1761          * @param special               special string
1762          * @param specialMethod boolean setter.
1763          */
1764         public DoubleSetter(Reflection.Method set, String special,
1765                         Reflection.Method specialMethod) {
1766                 this.setMethod = set;
1767                 this.specialString = special;
1768                 this.specialMethod = specialMethod;
1769                 this.multiplier = 1.0;
1770         }
1771         
1772         
1773         @Override
1774         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1775                         WarningSet warnings) {
1776                 
1777                 s = s.trim();
1778                 
1779                 // Check for special case
1780                 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1781                         specialMethod.invoke(c, true);
1782                         return;
1783                 }
1784                 
1785                 // Normal case
1786                 try {
1787                         double d = Double.parseDouble(s);
1788                         setMethod.invoke(c, d * multiplier);
1789                 } catch (NumberFormatException e) {
1790                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1791                 }
1792         }
1793 }
1794
1795
1796 class OverrideSetter implements Setter {
1797         private final Reflection.Method setMethod;
1798         private final Reflection.Method enabledMethod;
1799         
1800         public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1801                 this.setMethod = set;
1802                 this.enabledMethod = enabledMethod;
1803         }
1804         
1805         @Override
1806         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1807                         WarningSet warnings) {
1808                 
1809                 try {
1810                         double d = Double.parseDouble(s);
1811                         setMethod.invoke(c, d);
1812                         enabledMethod.invoke(c, true);
1813                 } catch (NumberFormatException e) {
1814                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1815                 }
1816         }
1817 }
1818
1819 ////  EnumSetter  -  sets a generic enum type
1820 class EnumSetter<T extends Enum<T>> implements Setter {
1821         private final Reflection.Method setter;
1822         private final Class<T> enumClass;
1823         
1824         public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1825                 this.setter = set;
1826                 this.enumClass = enumClass;
1827         }
1828         
1829         @Override
1830         public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1831                         WarningSet warnings) {
1832                 
1833                 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1834                 if (setEnum == null) {
1835                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1836                         return;
1837                 }
1838                 
1839                 setter.invoke(c, setEnum);
1840         }
1841 }
1842
1843
1844 ////  ColorSetter  -  sets a Color value
1845 class ColorSetter implements Setter {
1846         private final Reflection.Method setMethod;
1847         
1848         public ColorSetter(Reflection.Method set) {
1849                 setMethod = set;
1850         }
1851         
1852         @Override
1853         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1854                         WarningSet warnings) {
1855                 
1856                 String red = attributes.get("red");
1857                 String green = attributes.get("green");
1858                 String blue = attributes.get("blue");
1859                 
1860                 if (red == null || green == null || blue == null) {
1861                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1862                         return;
1863                 }
1864                 
1865                 int r, g, b;
1866                 try {
1867                         r = Integer.parseInt(red);
1868                         g = Integer.parseInt(green);
1869                         b = Integer.parseInt(blue);
1870                 } catch (NumberFormatException e) {
1871                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1872                         return;
1873                 }
1874                 
1875                 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1876                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1877                         return;
1878                 }
1879                 
1880                 Color color = new Color(r, g, b);
1881                 setMethod.invoke(c, color);
1882                 
1883                 if (!s.trim().equals("")) {
1884                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1885                 }
1886         }
1887 }
1888
1889
1890
1891 class MaterialSetter implements Setter {
1892         private final Reflection.Method setMethod;
1893         private final Material.Type type;
1894         
1895         public MaterialSetter(Reflection.Method set, Material.Type type) {
1896                 this.setMethod = set;
1897                 this.type = type;
1898         }
1899         
1900         @Override
1901         public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1902                         WarningSet warnings) {
1903                 
1904                 Material mat;
1905                 
1906                 // Check name != ""
1907                 name = name.trim();
1908                 if (name.equals("")) {
1909                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1910                         return;
1911                 }
1912                 
1913                 // Parse density
1914                 double density;
1915                 String str;
1916                 str = attributes.remove("density");
1917                 if (str == null) {
1918                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1919                         return;
1920                 }
1921                 try {
1922                         density = Double.parseDouble(str);
1923                 } catch (NumberFormatException e) {
1924                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1925                         return;
1926                 }
1927                 
1928                 // Parse thickness
1929                 //              double thickness = 0;
1930                 //              str = attributes.remove("thickness");
1931                 //              try {
1932                 //                      if (str != null)
1933                 //                              thickness = Double.parseDouble(str);
1934                 //              } catch (NumberFormatException e){
1935                 //                      warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1936                 //                      return;
1937                 //              }
1938                 
1939                 // Check type if specified
1940                 str = attributes.remove("type");
1941                 if (str != null && !type.name().toLowerCase().equals(str)) {
1942                         warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1943                         return;
1944                 }
1945                 
1946                 mat = Databases.findMaterial(type, name, density, false);
1947                 
1948                 setMethod.invoke(c, mat);
1949         }
1950 }
1951
1952
1953
1954
1955 class PositionSetter implements Setter {
1956         
1957         @Override
1958         public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1959                         WarningSet warnings) {
1960                 
1961                 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1962                                 RocketComponent.Position.class);
1963                 if (type == null) {
1964                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1965                         return;
1966                 }
1967                 
1968                 double pos;
1969                 try {
1970                         pos = Double.parseDouble(value);
1971                 } catch (NumberFormatException e) {
1972                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1973                         return;
1974                 }
1975                 
1976                 if (c instanceof FinSet) {
1977                         ((FinSet) c).setRelativePosition(type);
1978                         c.setPositionValue(pos);
1979                 } else if (c instanceof LaunchLug) {
1980                         ((LaunchLug) c).setRelativePosition(type);
1981                         c.setPositionValue(pos);
1982                 } else if (c instanceof InternalComponent) {
1983                         ((InternalComponent) c).setRelativePosition(type);
1984                         c.setPositionValue(pos);
1985                 } else {
1986                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1987                 }
1988                 
1989         }
1990 }
1991
1992
1993 class FinTabPositionSetter extends DoubleSetter {
1994         
1995         public FinTabPositionSetter() {
1996                 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
1997         }
1998         
1999         @Override
2000         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2001                         WarningSet warnings) {
2002                 
2003                 if (!(c instanceof FinSet)) {
2004                         throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2005                 }
2006                 
2007                 String relative = attributes.get("relativeto");
2008                 FinSet.TabRelativePosition position =
2009                                 (TabRelativePosition) DocumentConfig.findEnum(relative,
2010                                                 FinSet.TabRelativePosition.class);
2011                 
2012                 if (position != null) {
2013                         
2014                         ((FinSet) c).setTabRelativePosition(position);
2015                         
2016                 } else {
2017                         if (relative == null) {
2018                                 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2019                         } else {
2020                                 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2021                         }
2022                 }
2023                 
2024                 super.set(c, s, attributes, warnings);
2025         }
2026         
2027
2028 }
2029
2030
2031 class ClusterConfigurationSetter implements Setter {
2032         
2033         @Override
2034         public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2035                         WarningSet warnings) {
2036                 
2037                 if (!(component instanceof Clusterable)) {
2038                         warnings.add("Illegal component defined as cluster.");
2039                         return;
2040                 }
2041                 
2042                 ClusterConfiguration config = null;
2043                 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2044                         if (c.getXMLName().equals(value)) {
2045                                 config = c;
2046                                 break;
2047                         }
2048                 }
2049                 
2050                 if (config == null) {
2051                         warnings.add("Illegal cluster configuration specified.");
2052                         return;
2053                 }
2054                 
2055                 ((Clusterable) component).setClusterConfiguration(config);
2056         }
2057 }