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