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