1 package net.sf.openrocket.file.openrocket.importt;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.InvocationTargetException;
7 import java.util.ArrayList;
8 import java.util.HashMap;
10 import java.util.Locale;
11 import java.util.regex.Matcher;
12 import java.util.regex.Pattern;
14 import net.sf.openrocket.aerodynamics.Warning;
15 import net.sf.openrocket.aerodynamics.WarningSet;
16 import net.sf.openrocket.database.Databases;
17 import net.sf.openrocket.document.OpenRocketDocument;
18 import net.sf.openrocket.document.Simulation;
19 import net.sf.openrocket.document.Simulation.Status;
20 import net.sf.openrocket.document.StorageOptions;
21 import net.sf.openrocket.file.AbstractRocketLoader;
22 import net.sf.openrocket.file.MotorFinder;
23 import net.sf.openrocket.file.RocketLoadException;
24 import net.sf.openrocket.file.simplesax.AbstractElementHandler;
25 import net.sf.openrocket.file.simplesax.ElementHandler;
26 import net.sf.openrocket.file.simplesax.PlainTextHandler;
27 import net.sf.openrocket.file.simplesax.SimpleSAX;
28 import net.sf.openrocket.logging.LogHelper;
29 import net.sf.openrocket.material.Material;
30 import net.sf.openrocket.motor.Motor;
31 import net.sf.openrocket.preset.ComponentPreset;
32 import net.sf.openrocket.rocketcomponent.BodyComponent;
33 import net.sf.openrocket.rocketcomponent.BodyTube;
34 import net.sf.openrocket.rocketcomponent.Bulkhead;
35 import net.sf.openrocket.rocketcomponent.CenteringRing;
36 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
37 import net.sf.openrocket.rocketcomponent.Clusterable;
38 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
39 import net.sf.openrocket.rocketcomponent.EngineBlock;
40 import net.sf.openrocket.rocketcomponent.ExternalComponent;
41 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
42 import net.sf.openrocket.rocketcomponent.FinSet;
43 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
44 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
45 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
46 import net.sf.openrocket.rocketcomponent.InnerTube;
47 import net.sf.openrocket.rocketcomponent.InternalComponent;
48 import net.sf.openrocket.rocketcomponent.LaunchLug;
49 import net.sf.openrocket.rocketcomponent.MassComponent;
50 import net.sf.openrocket.rocketcomponent.MassObject;
51 import net.sf.openrocket.rocketcomponent.MotorMount;
52 import net.sf.openrocket.rocketcomponent.NoseCone;
53 import net.sf.openrocket.rocketcomponent.Parachute;
54 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
55 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
56 import net.sf.openrocket.rocketcomponent.ReferenceType;
57 import net.sf.openrocket.rocketcomponent.RingComponent;
58 import net.sf.openrocket.rocketcomponent.Rocket;
59 import net.sf.openrocket.rocketcomponent.RocketComponent;
60 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
61 import net.sf.openrocket.rocketcomponent.ShockCord;
62 import net.sf.openrocket.rocketcomponent.Stage;
63 import net.sf.openrocket.rocketcomponent.Streamer;
64 import net.sf.openrocket.rocketcomponent.StructuralComponent;
65 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
66 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
67 import net.sf.openrocket.rocketcomponent.Transition;
68 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
69 import net.sf.openrocket.rocketcomponent.TubeCoupler;
70 import net.sf.openrocket.simulation.customexpression.CustomExpression;
71 import net.sf.openrocket.simulation.FlightData;
72 import net.sf.openrocket.simulation.FlightDataBranch;
73 import net.sf.openrocket.simulation.FlightDataType;
74 import net.sf.openrocket.simulation.FlightEvent;
75 import net.sf.openrocket.simulation.FlightEvent.Type;
76 import net.sf.openrocket.simulation.SimulationOptions;
77 import net.sf.openrocket.startup.Application;
78 import net.sf.openrocket.unit.UnitGroup;
79 import net.sf.openrocket.util.BugException;
80 import net.sf.openrocket.util.Color;
81 import net.sf.openrocket.util.Coordinate;
82 import net.sf.openrocket.util.GeodeticComputationStrategy;
83 import net.sf.openrocket.util.LineStyle;
84 import net.sf.openrocket.util.Reflection;
86 import org.xml.sax.InputSource;
87 import org.xml.sax.SAXException;
91 * Class that loads a rocket definition from an OpenRocket rocket file.
93 * This class uses SAX to read the XML file format. The
94 * #loadFromStream(InputStream) method simply sets the system up and
95 * starts the parsing, while the actual logic is in the private inner class
96 * <code>OpenRocketHandler</code>.
98 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
100 public class OpenRocketLoader extends AbstractRocketLoader {
101 private static final LogHelper log = Application.getLogger();
105 public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException,
107 log.info("Loading .ork file");
108 DocumentLoadingContext context = new DocumentLoadingContext();
109 context.setMotorFinder(motorFinder);
111 InputSource xmlSource = new InputSource(source);
112 OpenRocketHandler handler = new OpenRocketHandler(context);
116 SimpleSAX.readXML(xmlSource, handler, warnings);
117 } catch (SAXException e) {
118 log.warn("Malformed XML in input");
119 throw new RocketLoadException("Malformed XML in input.", e);
123 OpenRocketDocument doc = handler.getDocument();
124 doc.getDefaultConfiguration().setAllStages();
126 // Deduce suitable time skip
127 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
128 for (Simulation s : doc.getSimulations()) {
129 if (s.getStatus() == Simulation.Status.EXTERNAL ||
130 s.getStatus() == Simulation.Status.NOT_SIMULATED)
132 if (s.getSimulatedData() == null)
134 if (s.getSimulatedData().getBranchCount() == 0)
136 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
139 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
143 double previousTime = Double.NaN;
144 for (double time : list) {
145 if (time - previousTime < timeSkip)
146 timeSkip = time - previousTime;
151 timeSkip = Math.rint(timeSkip * 100) / 100;
153 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
154 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
155 doc.getDefaultStorageOptions().setExplicitlySet(false);
158 log.info("Loading done");
166 class DocumentConfig {
168 /* Remember to update OpenRocketSaver as well! */
169 public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4", "1.5" };
172 * Divisor used in converting an integer version to the point-represented version.
173 * The integer version divided by this value is the major version and the remainder is
174 * the minor version. For example 101 corresponds to file version "1.1".
176 public static final int FILE_VERSION_DIVISOR = 100;
179 //////// Component constructors
180 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
183 // External components
184 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
185 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
186 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
187 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
188 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
189 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
190 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
192 // Internal components
193 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
194 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
195 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
196 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
197 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
199 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
200 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
201 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
202 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
205 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
207 } catch (NoSuchMethodException e) {
208 throw new BugException(
209 "Error in constructing the 'constructors' HashMap.");
214 //////// Parameter setters
216 * The keys are of the form Class:param, where Class is the class name and param
217 * the element name. Setters are searched for in descending class order.
218 * A setter of null means setting the parameter is not allowed.
220 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
223 setters.put("RocketComponent:name", new StringSetter(
224 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
225 setters.put("RocketComponent:color", new ColorSetter(
226 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
227 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
228 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
230 setters.put("RocketComponent:position", new PositionSetter());
231 setters.put("RocketComponent:overridemass", new OverrideSetter(
232 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
233 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
234 setters.put("RocketComponent:overridecg", new OverrideSetter(
235 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
236 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
237 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
238 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
239 setters.put("RocketComponent:comment", new StringSetter(
240 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
241 setters.put("RocketComponent:preset", new ComponentPresetSetter(
242 Reflection.findMethod(RocketComponent.class, "loadPreset", ComponentPreset.class)));
245 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
246 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
248 setters.put("ExternalComponent:material", new MaterialSetter(
249 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
250 Material.Type.BULK));
253 setters.put("BodyComponent:length", new DoubleSetter(
254 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
256 // SymmetricComponent
257 setters.put("SymmetricComponent:thickness", new DoubleSetter(
258 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
260 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
263 setters.put("BodyTube:radius", new DoubleSetter(
264 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
266 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
269 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
270 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
271 Transition.Shape.class));
272 setters.put("Transition:shapeclipped", new BooleanSetter(
273 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
274 setters.put("Transition:shapeparameter", new DoubleSetter(
275 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
277 setters.put("Transition:foreradius", new DoubleSetter(
278 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
280 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
281 setters.put("Transition:aftradius", new DoubleSetter(
282 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
284 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
286 setters.put("Transition:foreshoulderradius", new DoubleSetter(
287 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
288 setters.put("Transition:foreshoulderlength", new DoubleSetter(
289 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
290 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
291 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
292 setters.put("Transition:foreshouldercapped", new BooleanSetter(
293 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
295 setters.put("Transition:aftshoulderradius", new DoubleSetter(
296 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
297 setters.put("Transition:aftshoulderlength", new DoubleSetter(
298 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
299 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
300 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
301 setters.put("Transition:aftshouldercapped", new BooleanSetter(
302 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
304 // NoseCone - disable disallowed elements
305 setters.put("NoseCone:foreradius", null);
306 setters.put("NoseCone:foreshoulderradius", null);
307 setters.put("NoseCone:foreshoulderlength", null);
308 setters.put("NoseCone:foreshoulderthickness", null);
309 setters.put("NoseCone:foreshouldercapped", null);
312 setters.put("FinSet:fincount", new IntSetter(
313 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
314 setters.put("FinSet:rotation", new DoubleSetter(
315 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
316 setters.put("FinSet:thickness", new DoubleSetter(
317 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
318 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
319 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
320 FinSet.CrossSection.class));
321 setters.put("FinSet:cant", new DoubleSetter(
322 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
323 setters.put("FinSet:tabheight", new DoubleSetter(
324 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
325 setters.put("FinSet:tablength", new DoubleSetter(
326 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
327 setters.put("FinSet:tabposition", new FinTabPositionSetter());
330 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
331 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
332 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
333 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
334 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
335 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
336 setters.put("TrapezoidFinSet:height", new DoubleSetter(
337 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
340 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
341 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
342 setters.put("EllipticalFinSet:height", new DoubleSetter(
343 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
345 // FreeformFinSet points handled as a special handler
348 setters.put("LaunchLug:radius", new DoubleSetter(
349 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
350 setters.put("LaunchLug:length", new DoubleSetter(
351 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
352 setters.put("LaunchLug:thickness", new DoubleSetter(
353 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
354 setters.put("LaunchLug:radialdirection", new DoubleSetter(
355 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
358 // InternalComponent - nothing
360 // StructuralComponent
361 setters.put("StructuralComponent:material", new MaterialSetter(
362 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
363 Material.Type.BULK));
366 setters.put("RingComponent:length", new DoubleSetter(
367 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
368 setters.put("RingComponent:radialposition", new DoubleSetter(
369 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
370 setters.put("RingComponent:radialdirection", new DoubleSetter(
371 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
374 // ThicknessRingComponent - radius on separate components due to differing automatics
375 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
376 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
379 setters.put("EngineBlock:outerradius", new DoubleSetter(
380 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
382 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
385 setters.put("TubeCoupler:outerradius", new DoubleSetter(
386 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
388 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
391 setters.put("InnerTube:outerradius", new DoubleSetter(
392 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
393 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
394 setters.put("InnerTube:clusterscale", new DoubleSetter(
395 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
396 setters.put("InnerTube:clusterrotation", new DoubleSetter(
397 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
400 // RadiusRingComponent
403 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
404 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
405 setters.put("Bulkhead:outerradius", new DoubleSetter(
406 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
408 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
411 setters.put("CenteringRing:innerradius", new DoubleSetter(
412 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
414 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
415 setters.put("CenteringRing:outerradius", new DoubleSetter(
416 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
418 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
422 setters.put("MassObject:packedlength", new DoubleSetter(
423 Reflection.findMethod(MassObject.class, "setLength", double.class)));
424 setters.put("MassObject:packedradius", new DoubleSetter(
425 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
426 setters.put("MassObject:radialposition", new DoubleSetter(
427 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
428 setters.put("MassObject:radialdirection", new DoubleSetter(
429 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
433 setters.put("MassComponent:mass", new DoubleSetter(
434 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
437 setters.put("ShockCord:cordlength", new DoubleSetter(
438 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
439 setters.put("ShockCord:material", new MaterialSetter(
440 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
441 Material.Type.LINE));
444 setters.put("RecoveryDevice:cd", new DoubleSetter(
445 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
447 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
448 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
449 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
450 RecoveryDevice.DeployEvent.class));
451 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
452 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
453 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
454 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
455 setters.put("RecoveryDevice:material", new MaterialSetter(
456 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
457 Material.Type.SURFACE));
460 setters.put("Parachute:diameter", new DoubleSetter(
461 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
462 setters.put("Parachute:linecount", new IntSetter(
463 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
464 setters.put("Parachute:linelength", new DoubleSetter(
465 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
466 setters.put("Parachute:linematerial", new MaterialSetter(
467 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
468 Material.Type.LINE));
471 setters.put("Streamer:striplength", new DoubleSetter(
472 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
473 setters.put("Streamer:stripwidth", new DoubleSetter(
474 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
477 // <motorconfiguration> handled by separate handler
478 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
479 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
480 ReferenceType.class));
481 setters.put("Rocket:customreference", new DoubleSetter(
482 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
483 setters.put("Rocket:designer", new StringSetter(
484 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
485 setters.put("Rocket:revision", new StringSetter(
486 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
489 setters.put("Stage:separationevent", new EnumSetter<Stage.SeparationEvent>(
490 Reflection.findMethod(Stage.class, "setSeparationEvent", Stage.SeparationEvent.class),
491 Stage.SeparationEvent.class));
492 setters.put("Stage:separationdelay", new DoubleSetter(
493 Reflection.findMethod(Stage.class, "setSeparationDelay", double.class)));
499 * Search for a enum value that has the corresponding name as an XML value. The current
500 * conversion from enum name to XML value is to lowercase the name and strip out all
501 * underscore characters. This method returns a match to these criteria, or <code>null</code>
502 * if no such enum exists.
504 * @param <T> then enum type.
505 * @param name the XML value, null ok.
506 * @param enumClass the class of the enum.
507 * @return the found enum value, or <code>null</code>.
509 public static <T extends Enum<T>> Enum<T> findEnum(String name,
510 Class<? extends Enum<T>> enumClass) {
515 for (Enum<T> e : enumClass.getEnumConstants()) {
516 if (e.name().toLowerCase(Locale.ENGLISH).replace("_", "").equals(name)) {
525 * Convert a string to a double including formatting specifications of the OpenRocket
526 * file format. This accepts all formatting that is valid for
527 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
529 * @param s the string to parse.
530 * @return the numerical value.
531 * @throws NumberFormatException the the string cannot be parsed.
533 public static double stringToDouble(String s) throws NumberFormatException {
535 throw new NumberFormatException("null string");
536 if (s.equalsIgnoreCase("NaN"))
538 if (s.equalsIgnoreCase("Inf"))
539 return Double.POSITIVE_INFINITY;
540 if (s.equalsIgnoreCase("-Inf"))
541 return Double.NEGATIVE_INFINITY;
542 return Double.parseDouble(s);
551 * The starting point of the handlers. Accepts a single <openrocket> element and hands
552 * the contents to be read by a OpenRocketContentsHandler.
554 class OpenRocketHandler extends AbstractElementHandler {
555 private final DocumentLoadingContext context;
556 private OpenRocketContentHandler handler = null;
558 public OpenRocketHandler(DocumentLoadingContext context) {
559 this.context = context;
563 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
564 * has not been read yet.
566 * @return the document read, or null.
568 public OpenRocketDocument getDocument() {
569 return handler.getDocument();
573 public ElementHandler openElement(String element, HashMap<String, String> attributes,
574 WarningSet warnings) {
576 // Check for unknown elements
577 if (!element.equals("openrocket")) {
578 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
582 // Check for first call
583 if (handler != null) {
584 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
589 // Check version number
590 String version = null;
591 String creator = attributes.remove("creator");
592 String docVersion = attributes.remove("version");
593 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
594 if (v.equals(docVersion)) {
599 if (version == null) {
600 String str = "Unsupported document version";
601 if (docVersion != null)
602 str += " " + docVersion;
603 if (creator != null && !creator.trim().equals(""))
604 str += " (written using '" + creator.trim() + "')";
605 str += ", attempting to read file anyway.";
609 context.setFileVersion(parseVersion(docVersion));
611 handler = new OpenRocketContentHandler(context);
616 private int parseVersion(String docVersion) {
617 if (docVersion == null)
620 Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion);
622 int major = Integer.parseInt(m.group(1));
623 int minor = Integer.parseInt(m.group(2));
624 return major * DocumentConfig.FILE_VERSION_DIVISOR + minor;
631 public void closeElement(String element, HashMap<String, String> attributes,
632 String content, WarningSet warnings) throws SAXException {
633 attributes.remove("version");
634 attributes.remove("creator");
635 super.closeElement(element, attributes, content, warnings);
643 * Handles the content of the <openrocket> tag.
645 class OpenRocketContentHandler extends AbstractElementHandler {
646 private final DocumentLoadingContext context;
647 private final OpenRocketDocument doc;
648 private final Rocket rocket;
650 private boolean rocketDefined = false;
651 private boolean simulationsDefined = false;
652 private boolean datatypesDefined = false;
654 public OpenRocketContentHandler(DocumentLoadingContext context) {
655 this.context = context;
656 this.rocket = new Rocket();
657 this.doc = new OpenRocketDocument(rocket);
660 public OpenRocketDocument getDocument() {
667 public ElementHandler openElement(String element, HashMap<String, String> attributes,
668 WarningSet warnings) {
670 if (element.equals("rocket")) {
673 .fromString("Multiple rocket designs within one document, "
674 + "ignoring later ones."));
677 rocketDefined = true;
678 return new ComponentParameterHandler(rocket, context);
681 if (element.equals("datatypes")){
682 if (datatypesDefined) {
683 warnings.add(Warning.fromString("Multiple datatype blocks. Ignoring later ones."));
686 datatypesDefined = true;
687 return new DatatypeHandler(this, context);
690 if (element.equals("simulations")) {
691 if (simulationsDefined) {
693 .fromString("Multiple simulation definitions within one document, "
694 + "ignoring later ones."));
697 simulationsDefined = true;
698 return new SimulationsHandler(doc, context);
701 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
709 class DatatypeHandler extends AbstractElementHandler {
710 private final DocumentLoadingContext context;
711 private final OpenRocketContentHandler contentHandler;
712 private CustomExpressionHandler customExpressionHandler = null;
714 public DatatypeHandler(OpenRocketContentHandler contentHandler, DocumentLoadingContext context) {
715 this.context = context;
716 this.contentHandler = contentHandler;
720 public ElementHandler openElement(String element,
721 HashMap<String, String> attributes, WarningSet warnings)
722 throws SAXException {
724 if (element.equals("type") && attributes.get("source").equals("customexpression") ){
725 customExpressionHandler = new CustomExpressionHandler(contentHandler, context);
726 return customExpressionHandler;
729 warnings.add(Warning.fromString("Unknown datatype " + element + " defined, ignoring"));
736 public void closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) throws SAXException {
737 attributes.remove("source");
738 super.closeElement(element, attributes, content, warnings);
740 if (customExpressionHandler != null){
741 contentHandler.getDocument().addCustomExpression(customExpressionHandler.currentExpression);
748 class CustomExpressionHandler extends AbstractElementHandler{
749 private final DocumentLoadingContext context;
750 private final OpenRocketContentHandler contentHandler;
751 public CustomExpression currentExpression;
753 public CustomExpressionHandler(OpenRocketContentHandler contentHandler, DocumentLoadingContext context) {
754 this.context = context;
755 this.contentHandler = contentHandler;
756 currentExpression = new CustomExpression(contentHandler.getDocument());
761 public ElementHandler openElement(String element,
762 HashMap<String, String> attributes, WarningSet warnings)
763 throws SAXException {
769 public void closeElement(String element, HashMap<String, String> attributes,
770 String content, WarningSet warnings) throws SAXException {
772 if (element.equals("type")) {
773 contentHandler.getDocument().addCustomExpression(currentExpression);
776 if (element.equals("name")) {
777 currentExpression.setName(content);
780 if (element.equals("symbol")) {
781 currentExpression.setSymbol(content);
784 if (element.equals("unit") && attributes.get("unittype").equals("auto")) {
785 currentExpression.setUnit(content);
788 if (element.equals("expression")){
789 currentExpression.setExpression(content);
795 * A handler that creates components from the corresponding elements. The control of the
796 * contents is passed on to ComponentParameterHandler.
798 class ComponentHandler extends AbstractElementHandler {
799 private final DocumentLoadingContext context;
800 private final RocketComponent parent;
802 public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) {
803 this.parent = parent;
804 this.context = context;
808 public ElementHandler openElement(String element, HashMap<String, String> attributes,
809 WarningSet warnings) {
811 // Attempt to construct new component
812 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
814 if (constructor == null) {
815 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
821 c = constructor.newInstance();
822 } catch (InstantiationException e) {
823 throw new BugException("Error constructing component.", e);
824 } catch (IllegalAccessException e) {
825 throw new BugException("Error constructing component.", e);
826 } catch (InvocationTargetException e) {
827 throw Reflection.handleWrappedException(e);
832 return new ComponentParameterHandler(c, context);
838 * A handler that populates the parameters of a previously constructed rocket component.
839 * This uses the setters, or delegates the handling to another handler for specific
842 class ComponentParameterHandler extends AbstractElementHandler {
843 private final DocumentLoadingContext context;
844 private final RocketComponent component;
846 public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) {
848 this.context = context;
852 public ElementHandler openElement(String element, HashMap<String, String> attributes,
853 WarningSet warnings) {
855 // Check for specific elements that contain other elements
856 if (element.equals("subcomponents")) {
857 return new ComponentHandler(component, context);
859 if (element.equals("motormount")) {
860 if (!(component instanceof MotorMount)) {
861 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
864 return new MotorMountHandler((MotorMount) component, context);
866 if (element.equals("finpoints")) {
867 if (!(component instanceof FreeformFinSet)) {
868 warnings.add(Warning.fromString("Illegal component defined for fin points."));
871 return new FinSetPointHandler((FreeformFinSet) component, context);
873 if (element.equals("motorconfiguration")) {
874 if (!(component instanceof Rocket)) {
875 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
878 return new MotorConfigurationHandler((Rocket) component, context);
882 return PlainTextHandler.INSTANCE;
886 public void closeElement(String element, HashMap<String, String> attributes,
887 String content, WarningSet warnings) {
889 if (element.equals("subcomponents") || element.equals("motormount") ||
890 element.equals("finpoints") || element.equals("motorconfiguration")) {
894 // Search for the correct setter class
897 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
898 String setterKey = c.getSimpleName() + ":" + element;
899 Setter s = DocumentConfig.setters.get(setterKey);
902 s.set(component, content, attributes, warnings);
905 if (DocumentConfig.setters.containsKey(setterKey)) {
906 // Key exists but is null -> invalid parameter
912 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
913 + component.getComponentName() + ", ignoring."));
920 * A handler that reads the <point> specifications within the freeformfinset's
921 * <finpoints> elements.
923 class FinSetPointHandler extends AbstractElementHandler {
924 @SuppressWarnings("unused")
925 private final DocumentLoadingContext context;
926 private final FreeformFinSet finset;
927 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
929 public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) {
930 this.finset = finset;
931 this.context = context;
935 public ElementHandler openElement(String element, HashMap<String, String> attributes,
936 WarningSet warnings) {
937 return PlainTextHandler.INSTANCE;
942 public void closeElement(String element, HashMap<String, String> attributes,
943 String content, WarningSet warnings) throws SAXException {
945 String strx = attributes.remove("x");
946 String stry = attributes.remove("y");
947 if (strx == null || stry == null) {
948 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
952 double x = Double.parseDouble(strx);
953 double y = Double.parseDouble(stry);
954 coordinates.add(new Coordinate(x, y));
955 } catch (NumberFormatException e) {
956 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
960 super.closeElement(element, attributes, content, warnings);
964 public void endHandler(String element, HashMap<String, String> attributes,
965 String content, WarningSet warnings) {
967 finset.setPoints(coordinates.toArray(new Coordinate[0]));
968 } catch (IllegalFinPointException e) {
969 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
975 class MotorMountHandler extends AbstractElementHandler {
976 private final DocumentLoadingContext context;
977 private final MotorMount mount;
978 private MotorHandler motorHandler;
980 public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) {
982 this.context = context;
983 mount.setMotorMount(true);
987 public ElementHandler openElement(String element, HashMap<String, String> attributes,
988 WarningSet warnings) {
990 if (element.equals("motor")) {
991 motorHandler = new MotorHandler(context);
995 if (element.equals("ignitionevent") ||
996 element.equals("ignitiondelay") ||
997 element.equals("overhang")) {
998 return PlainTextHandler.INSTANCE;
1001 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
1008 public void closeElement(String element, HashMap<String, String> attributes,
1009 String content, WarningSet warnings) throws SAXException {
1011 if (element.equals("motor")) {
1012 String id = attributes.get("configid");
1013 if (id == null || id.equals("")) {
1014 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
1018 Motor motor = motorHandler.getMotor(warnings);
1019 mount.setMotor(id, motor);
1020 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
1024 if (element.equals("ignitionevent")) {
1025 MotorMount.IgnitionEvent event = null;
1026 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
1027 if (e.name().toLowerCase(Locale.ENGLISH).replaceAll("_", "").equals(content)) {
1032 if (event == null) {
1033 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
1036 mount.setIgnitionEvent(event);
1040 if (element.equals("ignitiondelay")) {
1043 d = Double.parseDouble(content);
1044 } catch (NumberFormatException nfe) {
1045 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
1048 mount.setIgnitionDelay(d);
1052 if (element.equals("overhang")) {
1055 d = Double.parseDouble(content);
1056 } catch (NumberFormatException nfe) {
1057 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
1060 mount.setMotorOverhang(d);
1064 super.closeElement(element, attributes, content, warnings);
1071 class MotorConfigurationHandler extends AbstractElementHandler {
1072 @SuppressWarnings("unused")
1073 private final DocumentLoadingContext context;
1074 private final Rocket rocket;
1075 private String name = null;
1076 private boolean inNameElement = false;
1078 public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) {
1079 this.rocket = rocket;
1080 this.context = context;
1084 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1085 WarningSet warnings) {
1087 if (inNameElement || !element.equals("name")) {
1088 warnings.add(Warning.FILE_INVALID_PARAMETER);
1091 inNameElement = true;
1093 return PlainTextHandler.INSTANCE;
1097 public void closeElement(String element, HashMap<String, String> attributes,
1098 String content, WarningSet warnings) {
1103 public void endHandler(String element, HashMap<String, String> attributes,
1104 String content, WarningSet warnings) throws SAXException {
1106 String configid = attributes.remove("configid");
1107 if (configid == null || configid.equals("")) {
1108 warnings.add(Warning.FILE_INVALID_PARAMETER);
1112 if (!rocket.addMotorConfigurationID(configid)) {
1113 warnings.add("Duplicate motor configuration ID used.");
1117 if (name != null && name.trim().length() > 0) {
1118 rocket.setMotorConfigurationName(configid, name);
1121 if ("true".equals(attributes.remove("default"))) {
1122 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
1125 super.closeElement(element, attributes, content, warnings);
1130 class MotorHandler extends AbstractElementHandler {
1131 /** File version where latest digest format was introduced */
1132 private static final int MOTOR_DIGEST_VERSION = 104;
1134 private final DocumentLoadingContext context;
1135 private Motor.Type type = null;
1136 private String manufacturer = null;
1137 private String designation = null;
1138 private String digest = null;
1139 private double diameter = Double.NaN;
1140 private double length = Double.NaN;
1141 private double delay = Double.NaN;
1143 public MotorHandler(DocumentLoadingContext context) {
1144 this.context = context;
1149 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1150 WarningSet warnings) {
1151 return PlainTextHandler.INSTANCE;
1156 * Return the motor to use, or null.
1158 public Motor getMotor(WarningSet warnings) {
1159 return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings);
1163 * Return the delay to use for the motor.
1165 public double getDelay(WarningSet warnings) {
1166 if (Double.isNaN(delay)) {
1167 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1168 return Motor.PLUGGED;
1175 public void closeElement(String element, HashMap<String, String> attributes,
1176 String content, WarningSet warnings) throws SAXException {
1178 content = content.trim();
1180 if (element.equals("type")) {
1184 for (Motor.Type t : Motor.Type.values()) {
1185 if (t.name().toLowerCase(Locale.ENGLISH).equals(content.trim())) {
1191 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1194 } else if (element.equals("manufacturer")) {
1197 manufacturer = content.trim();
1199 } else if (element.equals("designation")) {
1202 designation = content.trim();
1204 } else if (element.equals("digest")) {
1206 // Digest is used only for file versions saved using the same digest algorithm
1207 if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) {
1208 digest = content.trim();
1211 } else if (element.equals("diameter")) {
1214 diameter = Double.NaN;
1216 diameter = Double.parseDouble(content.trim());
1217 } catch (NumberFormatException e) {
1220 if (Double.isNaN(diameter)) {
1221 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1224 } else if (element.equals("length")) {
1227 length = Double.NaN;
1229 length = Double.parseDouble(content.trim());
1230 } catch (NumberFormatException ignore) {
1233 if (Double.isNaN(length)) {
1234 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1237 } else if (element.equals("delay")) {
1241 if (content.equals("none")) {
1242 delay = Motor.PLUGGED;
1245 delay = Double.parseDouble(content.trim());
1246 } catch (NumberFormatException ignore) {
1249 if (Double.isNaN(delay)) {
1250 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1256 super.closeElement(element, attributes, content, warnings);
1264 class SimulationsHandler extends AbstractElementHandler {
1265 private final DocumentLoadingContext context;
1266 private final OpenRocketDocument doc;
1267 private SingleSimulationHandler handler;
1269 public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1271 this.context = context;
1275 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1276 WarningSet warnings) {
1278 if (!element.equals("simulation")) {
1279 warnings.add("Unknown element '" + element + "', ignoring.");
1283 handler = new SingleSimulationHandler(doc, context);
1288 public void closeElement(String element, HashMap<String, String> attributes,
1289 String content, WarningSet warnings) throws SAXException {
1290 attributes.remove("status");
1291 super.closeElement(element, attributes, content, warnings);
1297 class SingleSimulationHandler extends AbstractElementHandler {
1299 private final DocumentLoadingContext context;
1301 private final OpenRocketDocument doc;
1303 private String name;
1305 private SimulationConditionsHandler conditionHandler;
1306 private FlightDataHandler dataHandler;
1308 private final List<String> listeners = new ArrayList<String>();
1310 public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1312 this.context = context;
1315 public OpenRocketDocument getDocument(){
1320 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1321 WarningSet warnings) {
1323 if (element.equals("name") || element.equals("simulator") ||
1324 element.equals("calculator") || element.equals("listener")) {
1325 return PlainTextHandler.INSTANCE;
1326 } else if (element.equals("conditions")) {
1327 conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context);
1328 return conditionHandler;
1329 } else if (element.equals("flightdata")) {
1330 dataHandler = new FlightDataHandler(this, context);
1333 warnings.add("Unknown element '" + element + "', ignoring.");
1339 public void closeElement(String element, HashMap<String, String> attributes,
1340 String content, WarningSet warnings) {
1342 if (element.equals("name")) {
1344 } else if (element.equals("simulator")) {
1345 if (!content.trim().equals("RK4Simulator")) {
1346 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1348 } else if (element.equals("calculator")) {
1349 if (!content.trim().equals("BarrowmanCalculator")) {
1350 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1352 } else if (element.equals("listener") && content.trim().length() > 0) {
1353 listeners.add(content.trim());
1359 public void endHandler(String element, HashMap<String, String> attributes,
1360 String content, WarningSet warnings) {
1362 String s = attributes.get("status");
1363 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1364 if (status == null) {
1365 warnings.add("Simulation status unknown, assuming outdated.");
1366 status = Simulation.Status.OUTDATED;
1369 SimulationOptions conditions;
1370 if (conditionHandler != null) {
1371 conditions = conditionHandler.getConditions();
1373 warnings.add("Simulation conditions not defined, using defaults.");
1374 conditions = new SimulationOptions(doc.getRocket());
1378 name = "Simulation";
1381 if (dataHandler == null)
1384 data = dataHandler.getFlightData();
1386 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1387 conditions, listeners, data);
1389 doc.addSimulation(simulation);
1393 class SimulationConditionsHandler extends AbstractElementHandler {
1394 private final DocumentLoadingContext context;
1395 private SimulationOptions conditions;
1396 private AtmosphereHandler atmosphereHandler;
1398 public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) {
1399 this.context = context;
1400 conditions = new SimulationOptions(rocket);
1401 // Set up default loading settings (which may differ from the new defaults)
1402 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1405 public SimulationOptions getConditions() {
1410 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1411 WarningSet warnings) {
1412 if (element.equals("atmosphere")) {
1413 atmosphereHandler = new AtmosphereHandler(attributes.get("model"), context);
1414 return atmosphereHandler;
1416 return PlainTextHandler.INSTANCE;
1420 public void closeElement(String element, HashMap<String, String> attributes,
1421 String content, WarningSet warnings) {
1423 double d = Double.NaN;
1425 d = Double.parseDouble(content);
1426 } catch (NumberFormatException ignore) {
1430 if (element.equals("configid")) {
1431 if (content.equals("")) {
1432 conditions.setMotorConfigurationID(null);
1434 conditions.setMotorConfigurationID(content);
1436 } else if (element.equals("launchrodlength")) {
1437 if (Double.isNaN(d)) {
1438 warnings.add("Illegal launch rod length defined, ignoring.");
1440 conditions.setLaunchRodLength(d);
1442 } else if (element.equals("launchrodangle")) {
1443 if (Double.isNaN(d)) {
1444 warnings.add("Illegal launch rod angle defined, ignoring.");
1446 conditions.setLaunchRodAngle(d * Math.PI / 180);
1448 } else if (element.equals("launchroddirection")) {
1449 if (Double.isNaN(d)) {
1450 warnings.add("Illegal launch rod direction defined, ignoring.");
1452 conditions.setLaunchRodDirection(d * Math.PI / 180);
1454 } else if (element.equals("windaverage")) {
1455 if (Double.isNaN(d)) {
1456 warnings.add("Illegal average windspeed defined, ignoring.");
1458 conditions.setWindSpeedAverage(d);
1460 } else if (element.equals("windturbulence")) {
1461 if (Double.isNaN(d)) {
1462 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1464 conditions.setWindTurbulenceIntensity(d);
1466 } else if (element.equals("launchaltitude")) {
1467 if (Double.isNaN(d)) {
1468 warnings.add("Illegal launch altitude defined, ignoring.");
1470 conditions.setLaunchAltitude(d);
1472 } else if (element.equals("launchlatitude")) {
1473 if (Double.isNaN(d)) {
1474 warnings.add("Illegal launch latitude defined, ignoring.");
1476 conditions.setLaunchLatitude(d);
1478 } else if (element.equals("launchlongitude")) {
1479 if (Double.isNaN(d)) {
1480 warnings.add("Illegal launch longitude.");
1482 conditions.setLaunchLongitude(d);
1484 } else if (element.equals("geodeticmethod")) {
1485 GeodeticComputationStrategy gcs =
1486 (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1488 conditions.setGeodeticComputation(gcs);
1490 warnings.add("Unknown geodetic computation method '" + content + "'");
1492 } else if (element.equals("atmosphere")) {
1493 atmosphereHandler.storeSettings(conditions, warnings);
1494 } else if (element.equals("timestep")) {
1495 if (Double.isNaN(d)) {
1496 warnings.add("Illegal time step defined, ignoring.");
1498 conditions.setTimeStep(d);
1505 class AtmosphereHandler extends AbstractElementHandler {
1506 @SuppressWarnings("unused")
1507 private final DocumentLoadingContext context;
1508 private final String model;
1509 private double temperature = Double.NaN;
1510 private double pressure = Double.NaN;
1512 public AtmosphereHandler(String model, DocumentLoadingContext context) {
1514 this.context = context;
1518 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1519 WarningSet warnings) {
1520 return PlainTextHandler.INSTANCE;
1524 public void closeElement(String element, HashMap<String, String> attributes,
1525 String content, WarningSet warnings) throws SAXException {
1527 double d = Double.NaN;
1529 d = Double.parseDouble(content);
1530 } catch (NumberFormatException ignore) {
1533 if (element.equals("basetemperature")) {
1534 if (Double.isNaN(d)) {
1535 warnings.add("Illegal base temperature specified, ignoring.");
1538 } else if (element.equals("basepressure")) {
1539 if (Double.isNaN(d)) {
1540 warnings.add("Illegal base pressure specified, ignoring.");
1544 super.closeElement(element, attributes, content, warnings);
1549 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1550 if (!Double.isNaN(pressure)) {
1551 cond.setLaunchPressure(pressure);
1553 if (!Double.isNaN(temperature)) {
1554 cond.setLaunchTemperature(temperature);
1557 if ("isa".equals(model)) {
1558 cond.setISAAtmosphere(true);
1559 } else if ("extendedisa".equals(model)) {
1560 cond.setISAAtmosphere(false);
1562 cond.setISAAtmosphere(true);
1563 warnings.add("Unknown atmospheric model, using ISA.");
1570 class FlightDataHandler extends AbstractElementHandler {
1571 private final DocumentLoadingContext context;
1573 private FlightDataBranchHandler dataHandler;
1574 private WarningSet warningSet = new WarningSet();
1575 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1577 private SingleSimulationHandler simHandler;
1578 private FlightData data;
1581 public FlightDataHandler(SingleSimulationHandler simHandler, DocumentLoadingContext context) {
1582 this.context = context;
1583 this.simHandler = simHandler;
1586 public FlightData getFlightData() {
1591 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1592 WarningSet warnings) {
1594 if (element.equals("warning")) {
1595 return PlainTextHandler.INSTANCE;
1597 if (element.equals("databranch")) {
1598 if (attributes.get("name") == null || attributes.get("types") == null) {
1599 warnings.add("Illegal flight data definition, ignoring.");
1602 dataHandler = new FlightDataBranchHandler( attributes.get("name"),
1603 attributes.get("types"),
1604 simHandler, context);
1608 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1614 public void closeElement(String element, HashMap<String, String> attributes,
1615 String content, WarningSet warnings) {
1617 if (element.equals("databranch")) {
1618 FlightDataBranch branch = dataHandler.getBranch();
1619 if (branch.getLength() > 0) {
1620 branches.add(branch);
1622 } else if (element.equals("warning")) {
1623 warningSet.add(Warning.fromString(content));
1629 public void endHandler(String element, HashMap<String, String> attributes,
1630 String content, WarningSet warnings) {
1632 if (branches.size() > 0) {
1633 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1635 double maxAltitude = Double.NaN;
1636 double maxVelocity = Double.NaN;
1637 double maxAcceleration = Double.NaN;
1638 double maxMach = Double.NaN;
1639 double timeToApogee = Double.NaN;
1640 double flightTime = Double.NaN;
1641 double groundHitVelocity = Double.NaN;
1642 double launchRodVelocity = Double.NaN;
1643 double deploymentVelocity = Double.NaN;
1646 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1647 } catch (NumberFormatException ignore) {
1650 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1651 } catch (NumberFormatException ignore) {
1654 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1655 } catch (NumberFormatException ignore) {
1658 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1659 } catch (NumberFormatException ignore) {
1662 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1663 } catch (NumberFormatException ignore) {
1666 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1667 } catch (NumberFormatException ignore) {
1671 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1672 } catch (NumberFormatException ignore) {
1675 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1676 } catch (NumberFormatException ignore) {
1679 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1680 } catch (NumberFormatException ignore) {
1683 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1684 timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1687 data.getWarningSet().addAll(warningSet);
1695 class FlightDataBranchHandler extends AbstractElementHandler {
1696 @SuppressWarnings("unused")
1697 private final DocumentLoadingContext context;
1698 private final FlightDataType[] types;
1699 private final FlightDataBranch branch;
1701 private static final LogHelper log = Application.getLogger();
1702 private final SingleSimulationHandler simHandler;
1704 public FlightDataBranchHandler(String name, String typeList, SingleSimulationHandler simHandler, DocumentLoadingContext context) {
1705 this.simHandler = simHandler;
1706 this.context = context;
1707 String[] split = typeList.split(",");
1708 types = new FlightDataType[split.length];
1709 for (int i = 0; i < split.length; i++) {
1710 String typeName = split[i];
1711 FlightDataType matching = findFlightDataType(typeName);
1712 types[i] = matching;
1713 //types[i] = FlightDataType.getType(typeName, matching.getSymbol(), matching.getUnitGroup());
1716 // TODO: LOW: May throw an IllegalArgumentException
1717 branch = new FlightDataBranch(name, types);
1720 // Find the full flight data type given name only
1721 // Note: this way of doing it requires that custom expressions always come before flight data in the file,
1722 // not the nicest but this is always the case anyway.
1723 private FlightDataType findFlightDataType(String name){
1725 // Kevins version with lookup by key. Not using right now
1727 if ( key != null ) {
1728 for (FlightDataType t : FlightDataType.ALL_TYPES){
1729 if (t.getKey().equals(key) ){
1736 // Look in built in types
1737 for (FlightDataType t : FlightDataType.ALL_TYPES){
1738 if (t.getName().equals(name) ){
1743 // Look in custom expressions
1744 for (CustomExpression exp : simHandler.getDocument().getCustomExpressions()){
1745 if (exp.getName().equals(name) ){
1746 return exp.getType();
1750 log.warn("Could not find the flight data type '"+name+"' used in the XML file. Substituted type with unknown symbol and units.");
1751 return FlightDataType.getType(name, "Unknown", UnitGroup.UNITS_NONE);
1754 public FlightDataBranch getBranch() {
1760 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1761 WarningSet warnings) {
1763 if (element.equals("datapoint"))
1764 return PlainTextHandler.INSTANCE;
1765 if (element.equals("event"))
1766 return PlainTextHandler.INSTANCE;
1768 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1774 public void closeElement(String element, HashMap<String, String> attributes,
1775 String content, WarningSet warnings) {
1777 if (element.equals("event")) {
1779 FlightEvent.Type type;
1782 time = DocumentConfig.stringToDouble(attributes.get("time"));
1783 } catch (NumberFormatException e) {
1784 warnings.add("Illegal event specification, ignoring.");
1788 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1790 warnings.add("Illegal event specification, ignoring.");
1794 branch.addEvent(new FlightEvent(type, time));
1798 if (!element.equals("datapoint")) {
1799 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1803 // element == "datapoint"
1806 // Check line format
1807 String[] split = content.split(",");
1808 if (split.length != types.length) {
1809 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1813 // Parse the doubles
1814 double[] values = new double[split.length];
1815 for (int i = 0; i < values.length; i++) {
1817 values[i] = DocumentConfig.stringToDouble(split[i]);
1818 } catch (NumberFormatException e) {
1819 warnings.add("Data point format error, ignoring point.");
1824 // Add point to branch
1826 for (int i = 0; i < types.length; i++) {
1827 branch.setValue(types[i], values[i]);
1836 ///////////////// Setters implementation
1842 * Set the specified value to the given component.
1844 * @param component the component to which to set.
1845 * @param value the value within the element.
1846 * @param attributes attributes for the element.
1847 * @param warnings the warning set to use.
1849 public void set(RocketComponent component, String value,
1850 HashMap<String, String> attributes, WarningSet warnings);
1854 //// StringSetter - sets the value to the contained String
1855 class StringSetter implements Setter {
1856 private final Reflection.Method setMethod;
1858 public StringSetter(Reflection.Method set) {
1863 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1864 WarningSet warnings) {
1865 setMethod.invoke(c, s);
1869 //// IntSetter - set an integer value
1870 class IntSetter implements Setter {
1871 private final Reflection.Method setMethod;
1873 public IntSetter(Reflection.Method set) {
1878 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1879 WarningSet warnings) {
1881 int n = Integer.parseInt(s);
1882 setMethod.invoke(c, n);
1883 } catch (NumberFormatException e) {
1884 warnings.add(Warning.FILE_INVALID_PARAMETER);
1890 //// BooleanSetter - set a boolean value
1891 class BooleanSetter implements Setter {
1892 private final Reflection.Method setMethod;
1894 public BooleanSetter(Reflection.Method set) {
1899 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1900 WarningSet warnings) {
1903 if (s.equalsIgnoreCase("true")) {
1904 setMethod.invoke(c, true);
1905 } else if (s.equalsIgnoreCase("false")) {
1906 setMethod.invoke(c, false);
1908 warnings.add(Warning.FILE_INVALID_PARAMETER);
1915 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1916 //// calls a setXXX(boolean) method.
1917 class DoubleSetter implements Setter {
1918 private final Reflection.Method setMethod;
1919 private final String specialString;
1920 private final Reflection.Method specialMethod;
1921 private final double multiplier;
1924 * Set only the double value.
1925 * @param set set method for the double value.
1927 public DoubleSetter(Reflection.Method set) {
1928 this.setMethod = set;
1929 this.specialString = null;
1930 this.specialMethod = null;
1931 this.multiplier = 1.0;
1935 * Multiply with the given multiplier and set the double value.
1936 * @param set set method for the double value.
1937 * @param mul multiplier.
1939 public DoubleSetter(Reflection.Method set, double mul) {
1940 this.setMethod = set;
1941 this.specialString = null;
1942 this.specialMethod = null;
1943 this.multiplier = mul;
1947 * Set the double value, or if the value equals the special string, use the
1948 * special setter and set it to true.
1950 * @param set double setter.
1951 * @param special special string
1952 * @param specialMethod boolean setter.
1954 public DoubleSetter(Reflection.Method set, String special,
1955 Reflection.Method specialMethod) {
1956 this.setMethod = set;
1957 this.specialString = special;
1958 this.specialMethod = specialMethod;
1959 this.multiplier = 1.0;
1964 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1965 WarningSet warnings) {
1969 // Check for special case
1970 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1971 specialMethod.invoke(c, true);
1977 double d = Double.parseDouble(s);
1978 setMethod.invoke(c, d * multiplier);
1979 } catch (NumberFormatException e) {
1980 warnings.add(Warning.FILE_INVALID_PARAMETER);
1986 class OverrideSetter implements Setter {
1987 private final Reflection.Method setMethod;
1988 private final Reflection.Method enabledMethod;
1990 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1991 this.setMethod = set;
1992 this.enabledMethod = enabledMethod;
1996 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1997 WarningSet warnings) {
2000 double d = Double.parseDouble(s);
2001 setMethod.invoke(c, d);
2002 enabledMethod.invoke(c, true);
2003 } catch (NumberFormatException e) {
2004 warnings.add(Warning.FILE_INVALID_PARAMETER);
2009 //// EnumSetter - sets a generic enum type
2010 class EnumSetter<T extends Enum<T>> implements Setter {
2011 private final Reflection.Method setter;
2012 private final Class<T> enumClass;
2014 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
2016 this.enumClass = enumClass;
2020 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
2021 WarningSet warnings) {
2023 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
2024 if (setEnum == null) {
2025 warnings.add(Warning.FILE_INVALID_PARAMETER);
2029 setter.invoke(c, setEnum);
2034 //// ColorSetter - sets a Color value
2035 class ColorSetter implements Setter {
2036 private final Reflection.Method setMethod;
2038 public ColorSetter(Reflection.Method set) {
2043 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2044 WarningSet warnings) {
2046 String red = attributes.get("red");
2047 String green = attributes.get("green");
2048 String blue = attributes.get("blue");
2050 if (red == null || green == null || blue == null) {
2051 warnings.add(Warning.FILE_INVALID_PARAMETER);
2057 r = Integer.parseInt(red);
2058 g = Integer.parseInt(green);
2059 b = Integer.parseInt(blue);
2060 } catch (NumberFormatException e) {
2061 warnings.add(Warning.FILE_INVALID_PARAMETER);
2065 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
2066 warnings.add(Warning.FILE_INVALID_PARAMETER);
2070 Color color = new Color(r, g, b);
2071 setMethod.invoke(c, color);
2073 if (!s.trim().equals("")) {
2074 warnings.add(Warning.FILE_INVALID_PARAMETER);
2079 ////ComponentPresetSetter - sets a ComponentPreset value
2080 class ComponentPresetSetter implements Setter {
2081 private final Reflection.Method setMethod;
2083 public ComponentPresetSetter(Reflection.Method set) {
2084 this.setMethod = set;
2088 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
2089 WarningSet warnings) {
2090 // FIXME - probably need more data in the warning messages - like what component preset...
2091 String manufacturerName = attributes.get("manufacturer");
2092 if ( manufacturerName == null ) {
2093 warnings.add(Warning.fromString("Invalid ComponentPreset, no manufacturer specified. Ignored"));
2097 String productNo = attributes.get("partno");
2098 if ( productNo == null ) {
2099 warnings.add(Warning.fromString("Invalid ComponentPreset, no partno specified. Ignored"));
2103 String digest = attributes.get("digest");
2104 if ( digest == null ) {
2105 warnings.add(Warning.fromString("Invalid ComponentPreset, no digest specified."));
2108 String type = attributes.get("type");
2109 if ( type == null ) {
2110 warnings.add(Warning.fromString("Invalid ComponentPreset, no type specified."));
2113 List<ComponentPreset> presets = Application.getComponentPresetDao().find( manufacturerName, productNo );
2115 ComponentPreset matchingPreset = null;
2117 for( ComponentPreset preset: presets ) {
2118 if ( digest != null && preset.getDigest().equals(digest) ) {
2119 // Found one with matching digest. Take it.
2120 matchingPreset = preset;
2123 if ( type != null && preset.getType().name().equals(type) && matchingPreset != null) {
2124 // Found the first one with matching type.
2125 matchingPreset = preset;
2130 if ( matchingPreset == null ) {
2131 warnings.add(Warning.fromString("No matching ComponentPreset found " + manufacturerName + " " + productNo));
2135 if ( digest != null && !matchingPreset.getDigest().equals(digest) ) {
2136 warnings.add(Warning.fromString("ComponentPreset has wrong digest"));
2139 setMethod.invoke(c, matchingPreset);
2144 ////MaterialSetter - sets a Material value
2145 class MaterialSetter implements Setter {
2146 private final Reflection.Method setMethod;
2147 private final Material.Type type;
2149 public MaterialSetter(Reflection.Method set, Material.Type type) {
2150 this.setMethod = set;
2155 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
2156 WarningSet warnings) {
2162 if (name.equals("")) {
2163 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2170 str = attributes.remove("density");
2172 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2176 density = Double.parseDouble(str);
2177 } catch (NumberFormatException e) {
2178 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2183 // double thickness = 0;
2184 // str = attributes.remove("thickness");
2187 // thickness = Double.parseDouble(str);
2188 // } catch (NumberFormatException e){
2189 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2193 // Check type if specified
2194 str = attributes.remove("type");
2195 if (str != null && !type.name().toLowerCase(Locale.ENGLISH).equals(str)) {
2196 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
2200 String key = attributes.remove("key");
2202 mat = Databases.findMaterial(type, key, name, density);
2204 setMethod.invoke(c, mat);
2212 class PositionSetter implements Setter {
2215 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
2216 WarningSet warnings) {
2218 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
2219 RocketComponent.Position.class);
2221 warnings.add(Warning.FILE_INVALID_PARAMETER);
2227 pos = Double.parseDouble(value);
2228 } catch (NumberFormatException e) {
2229 warnings.add(Warning.FILE_INVALID_PARAMETER);
2233 if (c instanceof FinSet) {
2234 ((FinSet) c).setRelativePosition(type);
2235 c.setPositionValue(pos);
2236 } else if (c instanceof LaunchLug) {
2237 ((LaunchLug) c).setRelativePosition(type);
2238 c.setPositionValue(pos);
2239 } else if (c instanceof InternalComponent) {
2240 ((InternalComponent) c).setRelativePosition(type);
2241 c.setPositionValue(pos);
2243 warnings.add(Warning.FILE_INVALID_PARAMETER);
2250 class FinTabPositionSetter extends DoubleSetter {
2252 public FinTabPositionSetter() {
2253 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2257 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2258 WarningSet warnings) {
2260 if (!(c instanceof FinSet)) {
2261 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2264 String relative = attributes.get("relativeto");
2265 FinSet.TabRelativePosition position =
2266 (TabRelativePosition) DocumentConfig.findEnum(relative,
2267 FinSet.TabRelativePosition.class);
2269 if (position != null) {
2271 ((FinSet) c).setTabRelativePosition(position);
2274 if (relative == null) {
2275 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2277 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2281 super.set(c, s, attributes, warnings);
2288 class ClusterConfigurationSetter implements Setter {
2291 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2292 WarningSet warnings) {
2294 if (!(component instanceof Clusterable)) {
2295 warnings.add("Illegal component defined as cluster.");
2299 ClusterConfiguration config = null;
2300 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2301 if (c.getXMLName().equals(value)) {
2307 if (config == null) {
2308 warnings.add("Illegal cluster configuration specified.");
2312 ((Clusterable) component).setClusterConfiguration(config);