Removed TODO comment for launchRodVelocity.
[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                         String str = "No motor with designation '" + designation + "'";
1006                         if (manufacturer != null)
1007                                 str += " for manufacturer '" + manufacturer + "'";
1008                         str += " found.";
1009                         warnings.add(str);
1010                         return null;
1011                 }
1012                 
1013                 // One motor
1014                 if (motors.size() == 1) {
1015                         Motor m = motors.get(0);
1016                         if (digest != null && !digest.equals(m.getDigest())) {
1017                                 String str = "Motor with designation '" + designation + "'";
1018                                 if (manufacturer != null)
1019                                         str += " for manufacturer '" + manufacturer + "'";
1020                                 str += " has differing thrust curve than the original.";
1021                                 warnings.add(str);
1022                         }
1023                         return m;
1024                 }
1025                 
1026                 // Multiple motors, check digest for which one to use
1027                 if (digest != null) {
1028                         
1029                         // Check for motor with correct digest
1030                         for (Motor m : motors) {
1031                                 if (digest.equals(m.getDigest())) {
1032                                         return m;
1033                                 }
1034                         }
1035                         String str = "Motor with designation '" + designation + "'";
1036                         if (manufacturer != null)
1037                                 str += " for manufacturer '" + manufacturer + "'";
1038                         str += " has differing thrust curve than the original.";
1039                         warnings.add(str);
1040                         
1041                 } else {
1042                         
1043                         // No digest, check for preferred digest (OpenRocket <= 1.1.0)
1044                         // TODO: MEDIUM: This should only be done for document versions 1.1 and below
1045                         for (Motor m : motors) {
1046                                 if (PreferredMotorDigests.DIGESTS.contains(m.getDigest())) {
1047                                         return m;
1048                                 }
1049                         }
1050                         
1051                         String str = "Multiple motors with designation '" + designation + "'";
1052                         if (manufacturer != null)
1053                                 str += " for manufacturer '" + manufacturer + "'";
1054                         str += " found, one chosen arbitrarily.";
1055                         warnings.add(str);
1056                         
1057                 }
1058                 return motors.get(0);
1059         }
1060         
1061         /**
1062          * Return the delay to use for the motor.
1063          */
1064         public double getDelay(WarningSet warnings) {
1065                 if (Double.isNaN(delay)) {
1066                         warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1067                         return Motor.PLUGGED;
1068                 }
1069                 return delay;
1070         }
1071         
1072         
1073         @Override
1074         public void closeElement(String element, HashMap<String, String> attributes,
1075                         String content, WarningSet warnings) throws SAXException {
1076                 
1077                 content = content.trim();
1078                 
1079                 if (element.equals("type")) {
1080                         
1081                         // Motor type
1082                         type = null;
1083                         for (Motor.Type t : Motor.Type.values()) {
1084                                 if (t.name().toLowerCase().equals(content.trim())) {
1085                                         type = t;
1086                                         break;
1087                                 }
1088                         }
1089                         if (type == null) {
1090                                 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1091                         }
1092                         
1093                 } else if (element.equals("manufacturer")) {
1094                         
1095                         // Manufacturer
1096                         manufacturer = content.trim();
1097                         
1098                 } else if (element.equals("designation")) {
1099                         
1100                         // Designation
1101                         designation = content.trim();
1102                         
1103                 } else if (element.equals("digest")) {
1104                         
1105                         // Digest
1106                         digest = content.trim();
1107                         
1108                 } else if (element.equals("diameter")) {
1109                         
1110                         // Diameter
1111                         diameter = Double.NaN;
1112                         try {
1113                                 diameter = Double.parseDouble(content.trim());
1114                         } catch (NumberFormatException e) {
1115                                 // Ignore
1116                         }
1117                         if (Double.isNaN(diameter)) {
1118                                 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1119                         }
1120                         
1121                 } else if (element.equals("length")) {
1122                         
1123                         // Length
1124                         length = Double.NaN;
1125                         try {
1126                                 length = Double.parseDouble(content.trim());
1127                         } catch (NumberFormatException ignore) {
1128                         }
1129                         
1130                         if (Double.isNaN(length)) {
1131                                 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1132                         }
1133                         
1134                 } else if (element.equals("delay")) {
1135                         
1136                         // Delay
1137                         delay = Double.NaN;
1138                         if (content.equals("none")) {
1139                                 delay = Motor.PLUGGED;
1140                         } else {
1141                                 try {
1142                                         delay = Double.parseDouble(content.trim());
1143                                 } catch (NumberFormatException ignore) {
1144                                 }
1145                                 
1146                                 if (Double.isNaN(delay)) {
1147                                         warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1148                                 }
1149                                 
1150                         }
1151                         
1152                 } else {
1153                         super.closeElement(element, attributes, content, warnings);
1154                 }
1155         }
1156         
1157 }
1158
1159
1160
1161 class SimulationsHandler extends ElementHandler {
1162         private final OpenRocketDocument doc;
1163         private SingleSimulationHandler handler;
1164         
1165         public SimulationsHandler(OpenRocketDocument doc) {
1166                 this.doc = doc;
1167         }
1168         
1169         @Override
1170         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1171                         WarningSet warnings) {
1172                 
1173                 if (!element.equals("simulation")) {
1174                         warnings.add("Unknown element '" + element + "', ignoring.");
1175                         return null;
1176                 }
1177                 
1178                 handler = new SingleSimulationHandler(doc);
1179                 return handler;
1180         }
1181         
1182         @Override
1183         public void closeElement(String element, HashMap<String, String> attributes,
1184                         String content, WarningSet warnings) throws SAXException {
1185                 attributes.remove("status");
1186                 super.closeElement(element, attributes, content, warnings);
1187         }
1188         
1189
1190 }
1191
1192 class SingleSimulationHandler extends ElementHandler {
1193         
1194         private final OpenRocketDocument doc;
1195         
1196         private String name;
1197         
1198         private SimulationConditionsHandler conditionHandler;
1199         private FlightDataHandler dataHandler;
1200         
1201         private final List<String> listeners = new ArrayList<String>();
1202         
1203         public SingleSimulationHandler(OpenRocketDocument doc) {
1204                 this.doc = doc;
1205         }
1206         
1207         
1208
1209         @Override
1210         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1211                         WarningSet warnings) {
1212                 
1213                 if (element.equals("name") || element.equals("simulator") ||
1214                                 element.equals("calculator") || element.equals("listener")) {
1215                         return PlainTextHandler.INSTANCE;
1216                 } else if (element.equals("conditions")) {
1217                         conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1218                         return conditionHandler;
1219                 } else if (element.equals("flightdata")) {
1220                         dataHandler = new FlightDataHandler();
1221                         return dataHandler;
1222                 } else {
1223                         warnings.add("Unknown element '" + element + "', ignoring.");
1224                         return null;
1225                 }
1226         }
1227         
1228         @Override
1229         public void closeElement(String element, HashMap<String, String> attributes,
1230                         String content, WarningSet warnings) {
1231                 
1232                 if (element.equals("name")) {
1233                         name = content;
1234                 } else if (element.equals("simulator")) {
1235                         if (!content.trim().equals("RK4Simulator")) {
1236                                 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1237                         }
1238                 } else if (element.equals("calculator")) {
1239                         if (!content.trim().equals("BarrowmanCalculator")) {
1240                                 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1241                         }
1242                 } else if (element.equals("listener") && content.trim().length() > 0) {
1243                         listeners.add(content.trim());
1244                 }
1245                 
1246         }
1247         
1248         @Override
1249         public void endHandler(String element, HashMap<String, String> attributes,
1250                         String content, WarningSet warnings) {
1251                 
1252                 String s = attributes.get("status");
1253                 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1254                 if (status == null) {
1255                         warnings.add("Simulation status unknown, assuming outdated.");
1256                         status = Simulation.Status.OUTDATED;
1257                 }
1258                 
1259                 SimulationOptions conditions;
1260                 if (conditionHandler != null) {
1261                         conditions = conditionHandler.getConditions();
1262                 } else {
1263                         warnings.add("Simulation conditions not defined, using defaults.");
1264                         conditions = new SimulationOptions(doc.getRocket());
1265                 }
1266                 
1267                 if (name == null)
1268                         name = "Simulation";
1269                 
1270                 FlightData data;
1271                 if (dataHandler == null)
1272                         data = null;
1273                 else
1274                         data = dataHandler.getFlightData();
1275                 
1276                 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1277                                 conditions, listeners, data);
1278                 
1279                 doc.addSimulation(simulation);
1280         }
1281 }
1282
1283
1284
1285 class SimulationConditionsHandler extends ElementHandler {
1286         private SimulationOptions conditions;
1287         private AtmosphereHandler atmosphereHandler;
1288         
1289         public SimulationConditionsHandler(Rocket rocket) {
1290                 conditions = new SimulationOptions(rocket);
1291                 // Set up default loading settings (which may differ from the new defaults)
1292                 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1293         }
1294         
1295         public SimulationOptions getConditions() {
1296                 return conditions;
1297         }
1298         
1299         @Override
1300         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1301                         WarningSet warnings) {
1302                 if (element.equals("atmosphere")) {
1303                         atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1304                         return atmosphereHandler;
1305                 }
1306                 return PlainTextHandler.INSTANCE;
1307         }
1308         
1309         @Override
1310         public void closeElement(String element, HashMap<String, String> attributes,
1311                         String content, WarningSet warnings) {
1312                 
1313                 double d = Double.NaN;
1314                 try {
1315                         d = Double.parseDouble(content);
1316                 } catch (NumberFormatException ignore) {
1317                 }
1318                 
1319
1320                 if (element.equals("configid")) {
1321                         if (content.equals("")) {
1322                                 conditions.setMotorConfigurationID(null);
1323                         } else {
1324                                 conditions.setMotorConfigurationID(content);
1325                         }
1326                 } else if (element.equals("launchrodlength")) {
1327                         if (Double.isNaN(d)) {
1328                                 warnings.add("Illegal launch rod length defined, ignoring.");
1329                         } else {
1330                                 conditions.setLaunchRodLength(d);
1331                         }
1332                 } else if (element.equals("launchrodangle")) {
1333                         if (Double.isNaN(d)) {
1334                                 warnings.add("Illegal launch rod angle defined, ignoring.");
1335                         } else {
1336                                 conditions.setLaunchRodAngle(d * Math.PI / 180);
1337                         }
1338                 } else if (element.equals("launchroddirection")) {
1339                         if (Double.isNaN(d)) {
1340                                 warnings.add("Illegal launch rod direction defined, ignoring.");
1341                         } else {
1342                                 conditions.setLaunchRodDirection(d * Math.PI / 180);
1343                         }
1344                 } else if (element.equals("windaverage")) {
1345                         if (Double.isNaN(d)) {
1346                                 warnings.add("Illegal average windspeed defined, ignoring.");
1347                         } else {
1348                                 conditions.setWindSpeedAverage(d);
1349                         }
1350                 } else if (element.equals("windturbulence")) {
1351                         if (Double.isNaN(d)) {
1352                                 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1353                         } else {
1354                                 conditions.setWindTurbulenceIntensity(d);
1355                         }
1356                 } else if (element.equals("launchaltitude")) {
1357                         if (Double.isNaN(d)) {
1358                                 warnings.add("Illegal launch altitude defined, ignoring.");
1359                         } else {
1360                                 conditions.setLaunchAltitude(d);
1361                         }
1362                 } else if (element.equals("launchlatitude")) {
1363                         if (Double.isNaN(d)) {
1364                                 warnings.add("Illegal launch latitude defined, ignoring.");
1365                         } else {
1366                                 conditions.setLaunchLatitude(d);
1367                         }
1368                 } else if (element.equals("launchlongitude")) {
1369                         if (Double.isNaN(d)) {
1370                                 warnings.add("Illegal launch longitude.");
1371                         } else {
1372                                 conditions.setLaunchLongitude(d);
1373                         }
1374                 } else if (element.equals("geodeticmethod")) {
1375                         GeodeticComputationStrategy gcs =
1376                                         (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1377                         if (gcs != null) {
1378                                 conditions.setGeodeticComputation(gcs);
1379                         } else {
1380                                 warnings.add("Unknown geodetic computation method '" + content + "'");
1381                         }
1382                 } else if (element.equals("atmosphere")) {
1383                         atmosphereHandler.storeSettings(conditions, warnings);
1384                 } else if (element.equals("timestep")) {
1385                         if (Double.isNaN(d)) {
1386                                 warnings.add("Illegal time step defined, ignoring.");
1387                         } else {
1388                                 conditions.setTimeStep(d);
1389                         }
1390                 }
1391         }
1392 }
1393
1394
1395 class AtmosphereHandler extends ElementHandler {
1396         private final String model;
1397         private double temperature = Double.NaN;
1398         private double pressure = Double.NaN;
1399         
1400         public AtmosphereHandler(String model) {
1401                 this.model = model;
1402         }
1403         
1404         @Override
1405         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1406                         WarningSet warnings) {
1407                 return PlainTextHandler.INSTANCE;
1408         }
1409         
1410         @Override
1411         public void closeElement(String element, HashMap<String, String> attributes,
1412                         String content, WarningSet warnings) throws SAXException {
1413                 
1414                 double d = Double.NaN;
1415                 try {
1416                         d = Double.parseDouble(content);
1417                 } catch (NumberFormatException ignore) {
1418                 }
1419                 
1420                 if (element.equals("basetemperature")) {
1421                         if (Double.isNaN(d)) {
1422                                 warnings.add("Illegal base temperature specified, ignoring.");
1423                         }
1424                         temperature = d;
1425                 } else if (element.equals("basepressure")) {
1426                         if (Double.isNaN(d)) {
1427                                 warnings.add("Illegal base pressure specified, ignoring.");
1428                         }
1429                         pressure = d;
1430                 } else {
1431                         super.closeElement(element, attributes, content, warnings);
1432                 }
1433         }
1434         
1435         
1436         public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1437                 if (!Double.isNaN(pressure)) {
1438                         cond.setLaunchPressure(pressure);
1439                 }
1440                 if (!Double.isNaN(temperature)) {
1441                         cond.setLaunchTemperature(temperature);
1442                 }
1443                 
1444                 if ("isa".equals(model)) {
1445                         cond.setISAAtmosphere(true);
1446                 } else if ("extendedisa".equals(model)) {
1447                         cond.setISAAtmosphere(false);
1448                 } else {
1449                         cond.setISAAtmosphere(true);
1450                         warnings.add("Unknown atmospheric model, using ISA.");
1451                 }
1452         }
1453         
1454 }
1455
1456
1457 class FlightDataHandler extends ElementHandler {
1458         
1459         private FlightDataBranchHandler dataHandler;
1460         private WarningSet warningSet = new WarningSet();
1461         private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1462         
1463         private FlightData data;
1464         
1465         public FlightData getFlightData() {
1466                 return data;
1467         }
1468         
1469         @Override
1470         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1471                         WarningSet warnings) {
1472                 
1473                 if (element.equals("warning")) {
1474                         return PlainTextHandler.INSTANCE;
1475                 }
1476                 if (element.equals("databranch")) {
1477                         if (attributes.get("name") == null || attributes.get("types") == null) {
1478                                 warnings.add("Illegal flight data definition, ignoring.");
1479                                 return null;
1480                         }
1481                         dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1482                                         attributes.get("types"));
1483                         return dataHandler;
1484                 }
1485                 
1486                 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1487                 return null;
1488         }
1489         
1490         
1491         @Override
1492         public void closeElement(String element, HashMap<String, String> attributes,
1493                         String content, WarningSet warnings) {
1494                 
1495                 if (element.equals("databranch")) {
1496                         FlightDataBranch branch = dataHandler.getBranch();
1497                         if (branch.getLength() > 0) {
1498                                 branches.add(branch);
1499                         }
1500                 } else if (element.equals("warning")) {
1501                         warningSet.add(Warning.fromString(content));
1502                 }
1503         }
1504         
1505         
1506         @Override
1507         public void endHandler(String element, HashMap<String, String> attributes,
1508                         String content, WarningSet warnings) {
1509                 
1510                 if (branches.size() > 0) {
1511                         data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1512                 } else {
1513                         double maxAltitude = Double.NaN;
1514                         double maxVelocity = Double.NaN;
1515                         double maxAcceleration = Double.NaN;
1516                         double maxMach = Double.NaN;
1517                         double timeToApogee = Double.NaN;
1518                         double flightTime = Double.NaN;
1519                         double groundHitVelocity = Double.NaN;
1520                         double launchRodVelocity = Double.NaN;
1521                         double deploymentVelocity = Double.NaN;
1522                         
1523                         try {
1524                                 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1525                         } catch (NumberFormatException ignore) {
1526                         }
1527                         try {
1528                                 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1529                         } catch (NumberFormatException ignore) {
1530                         }
1531                         try {
1532                                 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1533                         } catch (NumberFormatException ignore) {
1534                         }
1535                         try {
1536                                 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1537                         } catch (NumberFormatException ignore) {
1538                         }
1539                         try {
1540                                 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1541                         } catch (NumberFormatException ignore) {
1542                         }
1543                         try {
1544                                 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1545                         } catch (NumberFormatException ignore) {
1546                         }
1547                         try {
1548                                 groundHitVelocity =
1549                                                 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1550                         } catch (NumberFormatException ignore) {
1551                         }
1552                         try {
1553                                 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1554                         } catch (NumberFormatException ignore) {
1555                         }
1556                         try {
1557                                 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1558                         } catch (NumberFormatException ignore) {
1559                         }
1560                         
1561                         data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1562                                         timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1563                 }
1564                 
1565                 data.getWarningSet().addAll(warningSet);
1566                 data.immute();
1567         }
1568         
1569
1570 }
1571
1572
1573 class FlightDataBranchHandler extends ElementHandler {
1574         private final FlightDataType[] types;
1575         private final FlightDataBranch branch;
1576         
1577         public FlightDataBranchHandler(String name, String typeList) {
1578                 String[] split = typeList.split(",");
1579                 types = new FlightDataType[split.length];
1580                 for (int i = 0; i < split.length; i++) {
1581                         types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1582                 }
1583                 
1584                 // TODO: LOW: May throw an IllegalArgumentException
1585                 branch = new FlightDataBranch(name, types);
1586         }
1587         
1588         public FlightDataBranch getBranch() {
1589                 branch.immute();
1590                 return branch;
1591         }
1592         
1593         @Override
1594         public ElementHandler openElement(String element, HashMap<String, String> attributes,
1595                         WarningSet warnings) {
1596                 
1597                 if (element.equals("datapoint"))
1598                         return PlainTextHandler.INSTANCE;
1599                 if (element.equals("event"))
1600                         return PlainTextHandler.INSTANCE;
1601                 
1602                 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1603                 return null;
1604         }
1605         
1606         
1607         @Override
1608         public void closeElement(String element, HashMap<String, String> attributes,
1609                         String content, WarningSet warnings) {
1610                 
1611                 if (element.equals("event")) {
1612                         double time;
1613                         FlightEvent.Type type;
1614                         
1615                         try {
1616                                 time = DocumentConfig.stringToDouble(attributes.get("time"));
1617                         } catch (NumberFormatException e) {
1618                                 warnings.add("Illegal event specification, ignoring.");
1619                                 return;
1620                         }
1621                         
1622                         type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1623                         if (type == null) {
1624                                 warnings.add("Illegal event specification, ignoring.");
1625                                 return;
1626                         }
1627                         
1628                         branch.addEvent(new FlightEvent(type, time));
1629                         return;
1630                 }
1631                 
1632                 if (!element.equals("datapoint")) {
1633                         warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1634                         return;
1635                 }
1636                 
1637                 // element == "datapoint"
1638                 
1639
1640                 // Check line format
1641                 String[] split = content.split(",");
1642                 if (split.length != types.length) {
1643                         warnings.add("Data point did not contain correct amount of values, ignoring point.");
1644                         return;
1645                 }
1646                 
1647                 // Parse the doubles
1648                 double[] values = new double[split.length];
1649                 for (int i = 0; i < values.length; i++) {
1650                         try {
1651                                 values[i] = DocumentConfig.stringToDouble(split[i]);
1652                         } catch (NumberFormatException e) {
1653                                 warnings.add("Data point format error, ignoring point.");
1654                                 return;
1655                         }
1656                 }
1657                 
1658                 // Add point to branch
1659                 branch.addPoint();
1660                 for (int i = 0; i < types.length; i++) {
1661                         branch.setValue(types[i], values[i]);
1662                 }
1663         }
1664 }
1665
1666
1667
1668
1669
1670 /////////////////    Setters implementation
1671
1672
1673 ////  Interface
1674 interface Setter {
1675         /**
1676          * Set the specified value to the given component.
1677          * 
1678          * @param component             the component to which to set.
1679          * @param value                 the value within the element.
1680          * @param attributes    attributes for the element.
1681          * @param warnings              the warning set to use.
1682          */
1683         public void set(RocketComponent component, String value,
1684                         HashMap<String, String> attributes, WarningSet warnings);
1685 }
1686
1687
1688 ////  StringSetter - sets the value to the contained String
1689 class StringSetter implements Setter {
1690         private final Reflection.Method setMethod;
1691         
1692         public StringSetter(Reflection.Method set) {
1693                 setMethod = set;
1694         }
1695         
1696         @Override
1697         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1698                         WarningSet warnings) {
1699                 setMethod.invoke(c, s);
1700         }
1701 }
1702
1703 ////  IntSetter - set an integer value
1704 class IntSetter implements Setter {
1705         private final Reflection.Method setMethod;
1706         
1707         public IntSetter(Reflection.Method set) {
1708                 setMethod = set;
1709         }
1710         
1711         @Override
1712         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1713                         WarningSet warnings) {
1714                 try {
1715                         int n = Integer.parseInt(s);
1716                         setMethod.invoke(c, n);
1717                 } catch (NumberFormatException e) {
1718                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1719                 }
1720         }
1721 }
1722
1723
1724 //// BooleanSetter - set a boolean value
1725 class BooleanSetter implements Setter {
1726         private final Reflection.Method setMethod;
1727         
1728         public BooleanSetter(Reflection.Method set) {
1729                 setMethod = set;
1730         }
1731         
1732         @Override
1733         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1734                         WarningSet warnings) {
1735                 
1736                 s = s.trim();
1737                 if (s.equalsIgnoreCase("true")) {
1738                         setMethod.invoke(c, true);
1739                 } else if (s.equalsIgnoreCase("false")) {
1740                         setMethod.invoke(c, false);
1741                 } else {
1742                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1743                 }
1744         }
1745 }
1746
1747
1748
1749 ////  DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1750 ////  calls a setXXX(boolean) method.
1751 class DoubleSetter implements Setter {
1752         private final Reflection.Method setMethod;
1753         private final String specialString;
1754         private final Reflection.Method specialMethod;
1755         private final double multiplier;
1756         
1757         /**
1758          * Set only the double value.
1759          * @param set   set method for the double value. 
1760          */
1761         public DoubleSetter(Reflection.Method set) {
1762                 this.setMethod = set;
1763                 this.specialString = null;
1764                 this.specialMethod = null;
1765                 this.multiplier = 1.0;
1766         }
1767         
1768         /**
1769          * Multiply with the given multiplier and set the double value.
1770          * @param set   set method for the double value.
1771          * @param mul   multiplier.
1772          */
1773         public DoubleSetter(Reflection.Method set, double mul) {
1774                 this.setMethod = set;
1775                 this.specialString = null;
1776                 this.specialMethod = null;
1777                 this.multiplier = mul;
1778         }
1779         
1780         /**
1781          * Set the double value, or if the value equals the special string, use the
1782          * special setter and set it to true.
1783          * 
1784          * @param set                   double setter.
1785          * @param special               special string
1786          * @param specialMethod boolean setter.
1787          */
1788         public DoubleSetter(Reflection.Method set, String special,
1789                         Reflection.Method specialMethod) {
1790                 this.setMethod = set;
1791                 this.specialString = special;
1792                 this.specialMethod = specialMethod;
1793                 this.multiplier = 1.0;
1794         }
1795         
1796         
1797         @Override
1798         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1799                         WarningSet warnings) {
1800                 
1801                 s = s.trim();
1802                 
1803                 // Check for special case
1804                 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1805                         specialMethod.invoke(c, true);
1806                         return;
1807                 }
1808                 
1809                 // Normal case
1810                 try {
1811                         double d = Double.parseDouble(s);
1812                         setMethod.invoke(c, d * multiplier);
1813                 } catch (NumberFormatException e) {
1814                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1815                 }
1816         }
1817 }
1818
1819
1820 class OverrideSetter implements Setter {
1821         private final Reflection.Method setMethod;
1822         private final Reflection.Method enabledMethod;
1823         
1824         public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1825                 this.setMethod = set;
1826                 this.enabledMethod = enabledMethod;
1827         }
1828         
1829         @Override
1830         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1831                         WarningSet warnings) {
1832                 
1833                 try {
1834                         double d = Double.parseDouble(s);
1835                         setMethod.invoke(c, d);
1836                         enabledMethod.invoke(c, true);
1837                 } catch (NumberFormatException e) {
1838                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1839                 }
1840         }
1841 }
1842
1843 ////  EnumSetter  -  sets a generic enum type
1844 class EnumSetter<T extends Enum<T>> implements Setter {
1845         private final Reflection.Method setter;
1846         private final Class<T> enumClass;
1847         
1848         public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1849                 this.setter = set;
1850                 this.enumClass = enumClass;
1851         }
1852         
1853         @Override
1854         public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1855                         WarningSet warnings) {
1856                 
1857                 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1858                 if (setEnum == null) {
1859                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1860                         return;
1861                 }
1862                 
1863                 setter.invoke(c, setEnum);
1864         }
1865 }
1866
1867
1868 ////  ColorSetter  -  sets a Color value
1869 class ColorSetter implements Setter {
1870         private final Reflection.Method setMethod;
1871         
1872         public ColorSetter(Reflection.Method set) {
1873                 setMethod = set;
1874         }
1875         
1876         @Override
1877         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1878                         WarningSet warnings) {
1879                 
1880                 String red = attributes.get("red");
1881                 String green = attributes.get("green");
1882                 String blue = attributes.get("blue");
1883                 
1884                 if (red == null || green == null || blue == null) {
1885                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1886                         return;
1887                 }
1888                 
1889                 int r, g, b;
1890                 try {
1891                         r = Integer.parseInt(red);
1892                         g = Integer.parseInt(green);
1893                         b = Integer.parseInt(blue);
1894                 } catch (NumberFormatException e) {
1895                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1896                         return;
1897                 }
1898                 
1899                 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1900                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1901                         return;
1902                 }
1903                 
1904                 Color color = new Color(r, g, b);
1905                 setMethod.invoke(c, color);
1906                 
1907                 if (!s.trim().equals("")) {
1908                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1909                 }
1910         }
1911 }
1912
1913
1914
1915 class MaterialSetter implements Setter {
1916         private final Reflection.Method setMethod;
1917         private final Material.Type type;
1918         
1919         public MaterialSetter(Reflection.Method set, Material.Type type) {
1920                 this.setMethod = set;
1921                 this.type = type;
1922         }
1923         
1924         @Override
1925         public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1926                         WarningSet warnings) {
1927                 
1928                 Material mat;
1929                 
1930                 // Check name != ""
1931                 name = name.trim();
1932                 if (name.equals("")) {
1933                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1934                         return;
1935                 }
1936                 
1937                 // Parse density
1938                 double density;
1939                 String str;
1940                 str = attributes.remove("density");
1941                 if (str == null) {
1942                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1943                         return;
1944                 }
1945                 try {
1946                         density = Double.parseDouble(str);
1947                 } catch (NumberFormatException e) {
1948                         warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1949                         return;
1950                 }
1951                 
1952                 // Parse thickness
1953                 //              double thickness = 0;
1954                 //              str = attributes.remove("thickness");
1955                 //              try {
1956                 //                      if (str != null)
1957                 //                              thickness = Double.parseDouble(str);
1958                 //              } catch (NumberFormatException e){
1959                 //                      warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1960                 //                      return;
1961                 //              }
1962                 
1963                 // Check type if specified
1964                 str = attributes.remove("type");
1965                 if (str != null && !type.name().toLowerCase().equals(str)) {
1966                         warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1967                         return;
1968                 }
1969                 
1970                 mat = Databases.findMaterial(type, name, density, false);
1971                 
1972                 setMethod.invoke(c, mat);
1973         }
1974 }
1975
1976
1977
1978
1979 class PositionSetter implements Setter {
1980         
1981         @Override
1982         public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1983                         WarningSet warnings) {
1984                 
1985                 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1986                                 RocketComponent.Position.class);
1987                 if (type == null) {
1988                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1989                         return;
1990                 }
1991                 
1992                 double pos;
1993                 try {
1994                         pos = Double.parseDouble(value);
1995                 } catch (NumberFormatException e) {
1996                         warnings.add(Warning.FILE_INVALID_PARAMETER);
1997                         return;
1998                 }
1999                 
2000                 if (c instanceof FinSet) {
2001                         ((FinSet) c).setRelativePosition(type);
2002                         c.setPositionValue(pos);
2003                 } else if (c instanceof LaunchLug) {
2004                         ((LaunchLug) c).setRelativePosition(type);
2005                         c.setPositionValue(pos);
2006                 } else if (c instanceof InternalComponent) {
2007                         ((InternalComponent) c).setRelativePosition(type);
2008                         c.setPositionValue(pos);
2009                 } else {
2010                         warnings.add(Warning.FILE_INVALID_PARAMETER);
2011                 }
2012                 
2013         }
2014 }
2015
2016
2017 class FinTabPositionSetter extends DoubleSetter {
2018         
2019         public FinTabPositionSetter() {
2020                 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2021         }
2022         
2023         @Override
2024         public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2025                         WarningSet warnings) {
2026                 
2027                 if (!(c instanceof FinSet)) {
2028                         throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2029                 }
2030                 
2031                 String relative = attributes.get("relativeto");
2032                 FinSet.TabRelativePosition position =
2033                                 (TabRelativePosition) DocumentConfig.findEnum(relative,
2034                                                 FinSet.TabRelativePosition.class);
2035                 
2036                 if (position != null) {
2037                         
2038                         ((FinSet) c).setTabRelativePosition(position);
2039                         
2040                 } else {
2041                         if (relative == null) {
2042                                 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2043                         } else {
2044                                 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2045                         }
2046                 }
2047                 
2048                 super.set(c, s, attributes, warnings);
2049         }
2050         
2051
2052 }
2053
2054
2055 class ClusterConfigurationSetter implements Setter {
2056         
2057         @Override
2058         public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2059                         WarningSet warnings) {
2060                 
2061                 if (!(component instanceof Clusterable)) {
2062                         warnings.add("Illegal component defined as cluster.");
2063                         return;
2064                 }
2065                 
2066                 ClusterConfiguration config = null;
2067                 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2068                         if (c.getXMLName().equals(value)) {
2069                                 config = c;
2070                                 break;
2071                         }
2072                 }
2073                 
2074                 if (config == null) {
2075                         warnings.add("Illegal cluster configuration specified.");
2076                         return;
2077                 }
2078                 
2079                 ((Clusterable) component).setClusterConfiguration(config);
2080         }
2081 }