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