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