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