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