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.regex.Matcher;
11 import java.util.regex.Pattern;
13 import net.sf.openrocket.aerodynamics.Warning;
14 import net.sf.openrocket.aerodynamics.WarningSet;
15 import net.sf.openrocket.database.Databases;
16 import net.sf.openrocket.document.OpenRocketDocument;
17 import net.sf.openrocket.document.Simulation;
18 import net.sf.openrocket.document.Simulation.Status;
19 import net.sf.openrocket.document.StorageOptions;
20 import net.sf.openrocket.file.AbstractRocketLoader;
21 import net.sf.openrocket.file.MotorFinder;
22 import net.sf.openrocket.file.RocketLoadException;
23 import net.sf.openrocket.file.simplesax.AbstractElementHandler;
24 import net.sf.openrocket.file.simplesax.ElementHandler;
25 import net.sf.openrocket.file.simplesax.PlainTextHandler;
26 import net.sf.openrocket.file.simplesax.SimpleSAX;
27 import net.sf.openrocket.logging.LogHelper;
28 import net.sf.openrocket.material.Material;
29 import net.sf.openrocket.motor.Motor;
30 import net.sf.openrocket.rocketcomponent.BodyComponent;
31 import net.sf.openrocket.rocketcomponent.BodyTube;
32 import net.sf.openrocket.rocketcomponent.Bulkhead;
33 import net.sf.openrocket.rocketcomponent.CenteringRing;
34 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
35 import net.sf.openrocket.rocketcomponent.Clusterable;
36 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
37 import net.sf.openrocket.rocketcomponent.EngineBlock;
38 import net.sf.openrocket.rocketcomponent.ExternalComponent;
39 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
40 import net.sf.openrocket.rocketcomponent.FinSet;
41 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
42 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
43 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
44 import net.sf.openrocket.rocketcomponent.InnerTube;
45 import net.sf.openrocket.rocketcomponent.InternalComponent;
46 import net.sf.openrocket.rocketcomponent.LaunchLug;
47 import net.sf.openrocket.rocketcomponent.MassComponent;
48 import net.sf.openrocket.rocketcomponent.MassObject;
49 import net.sf.openrocket.rocketcomponent.MotorMount;
50 import net.sf.openrocket.rocketcomponent.NoseCone;
51 import net.sf.openrocket.rocketcomponent.Parachute;
52 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
53 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
54 import net.sf.openrocket.rocketcomponent.ReferenceType;
55 import net.sf.openrocket.rocketcomponent.RingComponent;
56 import net.sf.openrocket.rocketcomponent.Rocket;
57 import net.sf.openrocket.rocketcomponent.RocketComponent;
58 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
59 import net.sf.openrocket.rocketcomponent.ShockCord;
60 import net.sf.openrocket.rocketcomponent.Stage;
61 import net.sf.openrocket.rocketcomponent.Streamer;
62 import net.sf.openrocket.rocketcomponent.StructuralComponent;
63 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
64 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
65 import net.sf.openrocket.rocketcomponent.Transition;
66 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
67 import net.sf.openrocket.rocketcomponent.TubeCoupler;
68 import net.sf.openrocket.simulation.FlightData;
69 import net.sf.openrocket.simulation.FlightDataBranch;
70 import net.sf.openrocket.simulation.FlightDataType;
71 import net.sf.openrocket.simulation.FlightEvent;
72 import net.sf.openrocket.simulation.FlightEvent.Type;
73 import net.sf.openrocket.simulation.SimulationOptions;
74 import net.sf.openrocket.startup.Application;
75 import net.sf.openrocket.unit.UnitGroup;
76 import net.sf.openrocket.util.BugException;
77 import net.sf.openrocket.util.Color;
78 import net.sf.openrocket.util.Coordinate;
79 import net.sf.openrocket.util.GeodeticComputationStrategy;
80 import net.sf.openrocket.util.LineStyle;
81 import net.sf.openrocket.util.Reflection;
83 import org.xml.sax.InputSource;
84 import org.xml.sax.SAXException;
88 * Class that loads a rocket definition from an OpenRocket rocket file.
90 * This class uses SAX to read the XML file format. The
91 * #loadFromStream(InputStream) method simply sets the system up and
92 * starts the parsing, while the actual logic is in the private inner class
93 * <code>OpenRocketHandler</code>.
95 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
97 public class OpenRocketLoader extends AbstractRocketLoader {
98 private static final LogHelper log = Application.getLogger();
102 public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException,
104 log.info("Loading .ork file");
105 DocumentLoadingContext context = new DocumentLoadingContext();
106 context.setMotorFinder(motorFinder);
108 InputSource xmlSource = new InputSource(source);
109 OpenRocketHandler handler = new OpenRocketHandler(context);
113 SimpleSAX.readXML(xmlSource, handler, warnings);
114 } catch (SAXException e) {
115 log.warn("Malformed XML in input");
116 throw new RocketLoadException("Malformed XML in input.", e);
120 OpenRocketDocument doc = handler.getDocument();
121 doc.getDefaultConfiguration().setAllStages();
123 // Deduce suitable time skip
124 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
125 for (Simulation s : doc.getSimulations()) {
126 if (s.getStatus() == Simulation.Status.EXTERNAL ||
127 s.getStatus() == Simulation.Status.NOT_SIMULATED)
129 if (s.getSimulatedData() == null)
131 if (s.getSimulatedData().getBranchCount() == 0)
133 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
136 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
140 double previousTime = Double.NaN;
141 for (double time : list) {
142 if (time - previousTime < timeSkip)
143 timeSkip = time - previousTime;
148 timeSkip = Math.rint(timeSkip * 100) / 100;
150 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
151 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
152 doc.getDefaultStorageOptions().setExplicitlySet(false);
155 log.info("Loading done");
163 class DocumentConfig {
165 /* Remember to update OpenRocketSaver as well! */
166 public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4" };
169 * Divisor used in converting an integer version to the point-represented version.
170 * The integer version divided by this value is the major version and the remainder is
171 * the minor version. For example 101 corresponds to file version "1.1".
173 public static final int FILE_VERSION_DIVISOR = 100;
176 //////// Component constructors
177 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
180 // External components
181 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
182 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
183 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
184 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
185 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
186 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
187 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
189 // Internal components
190 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
191 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
192 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
193 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
194 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
196 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
197 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
198 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
199 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
202 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
204 } catch (NoSuchMethodException e) {
205 throw new BugException(
206 "Error in constructing the 'constructors' HashMap.");
211 //////// Parameter setters
213 * The keys are of the form Class:param, where Class is the class name and param
214 * the element name. Setters are searched for in descending class order.
215 * A setter of null means setting the parameter is not allowed.
217 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
220 setters.put("RocketComponent:name", new StringSetter(
221 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
222 setters.put("RocketComponent:color", new ColorSetter(
223 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
224 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
225 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
227 setters.put("RocketComponent:position", new PositionSetter());
228 setters.put("RocketComponent:overridemass", new OverrideSetter(
229 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
230 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
231 setters.put("RocketComponent:overridecg", new OverrideSetter(
232 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
233 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
234 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
235 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
236 setters.put("RocketComponent:comment", new StringSetter(
237 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
240 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
241 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
243 setters.put("ExternalComponent:material", new MaterialSetter(
244 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
245 Material.Type.BULK));
248 setters.put("BodyComponent:length", new DoubleSetter(
249 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
251 // SymmetricComponent
252 setters.put("SymmetricComponent:thickness", new DoubleSetter(
253 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
255 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
258 setters.put("BodyTube:radius", new DoubleSetter(
259 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
261 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
264 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
265 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
266 Transition.Shape.class));
267 setters.put("Transition:shapeclipped", new BooleanSetter(
268 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
269 setters.put("Transition:shapeparameter", new DoubleSetter(
270 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
272 setters.put("Transition:foreradius", new DoubleSetter(
273 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
275 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
276 setters.put("Transition:aftradius", new DoubleSetter(
277 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
279 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
281 setters.put("Transition:foreshoulderradius", new DoubleSetter(
282 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
283 setters.put("Transition:foreshoulderlength", new DoubleSetter(
284 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
285 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
286 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
287 setters.put("Transition:foreshouldercapped", new BooleanSetter(
288 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
290 setters.put("Transition:aftshoulderradius", new DoubleSetter(
291 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
292 setters.put("Transition:aftshoulderlength", new DoubleSetter(
293 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
294 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
295 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
296 setters.put("Transition:aftshouldercapped", new BooleanSetter(
297 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
299 // NoseCone - disable disallowed elements
300 setters.put("NoseCone:foreradius", null);
301 setters.put("NoseCone:foreshoulderradius", null);
302 setters.put("NoseCone:foreshoulderlength", null);
303 setters.put("NoseCone:foreshoulderthickness", null);
304 setters.put("NoseCone:foreshouldercapped", null);
307 setters.put("FinSet:fincount", new IntSetter(
308 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
309 setters.put("FinSet:rotation", new DoubleSetter(
310 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
311 setters.put("FinSet:thickness", new DoubleSetter(
312 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
313 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
314 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
315 FinSet.CrossSection.class));
316 setters.put("FinSet:cant", new DoubleSetter(
317 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
318 setters.put("FinSet:tabheight", new DoubleSetter(
319 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
320 setters.put("FinSet:tablength", new DoubleSetter(
321 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
322 setters.put("FinSet:tabposition", new FinTabPositionSetter());
325 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
326 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
327 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
328 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
329 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
330 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
331 setters.put("TrapezoidFinSet:height", new DoubleSetter(
332 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
335 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
336 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
337 setters.put("EllipticalFinSet:height", new DoubleSetter(
338 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
340 // FreeformFinSet points handled as a special handler
343 setters.put("LaunchLug:radius", new DoubleSetter(
344 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
345 setters.put("LaunchLug:length", new DoubleSetter(
346 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
347 setters.put("LaunchLug:thickness", new DoubleSetter(
348 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
349 setters.put("LaunchLug:radialdirection", new DoubleSetter(
350 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
353 // InternalComponent - nothing
355 // StructuralComponent
356 setters.put("StructuralComponent:material", new MaterialSetter(
357 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
358 Material.Type.BULK));
361 setters.put("RingComponent:length", new DoubleSetter(
362 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
363 setters.put("RingComponent:radialposition", new DoubleSetter(
364 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
365 setters.put("RingComponent:radialdirection", new DoubleSetter(
366 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
369 // ThicknessRingComponent - radius on separate components due to differing automatics
370 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
371 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
374 setters.put("EngineBlock:outerradius", new DoubleSetter(
375 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
377 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
380 setters.put("TubeCoupler:outerradius", new DoubleSetter(
381 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
383 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
386 setters.put("InnerTube:outerradius", new DoubleSetter(
387 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
388 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
389 setters.put("InnerTube:clusterscale", new DoubleSetter(
390 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
391 setters.put("InnerTube:clusterrotation", new DoubleSetter(
392 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
395 // RadiusRingComponent
398 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
399 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
400 setters.put("Bulkhead:outerradius", new DoubleSetter(
401 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
403 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
406 setters.put("CenteringRing:innerradius", new DoubleSetter(
407 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
409 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
410 setters.put("CenteringRing:outerradius", new DoubleSetter(
411 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
413 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
417 setters.put("MassObject:packedlength", new DoubleSetter(
418 Reflection.findMethod(MassObject.class, "setLength", double.class)));
419 setters.put("MassObject:packedradius", new DoubleSetter(
420 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
421 setters.put("MassObject:radialposition", new DoubleSetter(
422 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
423 setters.put("MassObject:radialdirection", new DoubleSetter(
424 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
428 setters.put("MassComponent:mass", new DoubleSetter(
429 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
432 setters.put("ShockCord:cordlength", new DoubleSetter(
433 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
434 setters.put("ShockCord:material", new MaterialSetter(
435 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
436 Material.Type.LINE));
439 setters.put("RecoveryDevice:cd", new DoubleSetter(
440 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
442 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
443 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
444 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
445 RecoveryDevice.DeployEvent.class));
446 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
447 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
448 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
449 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
450 setters.put("RecoveryDevice:material", new MaterialSetter(
451 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
452 Material.Type.SURFACE));
455 setters.put("Parachute:diameter", new DoubleSetter(
456 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
457 setters.put("Parachute:linecount", new IntSetter(
458 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
459 setters.put("Parachute:linelength", new DoubleSetter(
460 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
461 setters.put("Parachute:linematerial", new MaterialSetter(
462 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
463 Material.Type.LINE));
466 setters.put("Streamer:striplength", new DoubleSetter(
467 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
468 setters.put("Streamer:stripwidth", new DoubleSetter(
469 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
472 // <motorconfiguration> handled by separate handler
473 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
474 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
475 ReferenceType.class));
476 setters.put("Rocket:customreference", new DoubleSetter(
477 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
478 setters.put("Rocket:designer", new StringSetter(
479 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
480 setters.put("Rocket:revision", new StringSetter(
481 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
484 setters.put("Stage:separationevent", new EnumSetter<Stage.SeparationEvent>(
485 Reflection.findMethod(Stage.class, "setSeparationEvent", Stage.SeparationEvent.class),
486 Stage.SeparationEvent.class));
487 setters.put("Stage:separationdelay", new DoubleSetter(
488 Reflection.findMethod(Stage.class, "setSeparationDelay", double.class)));
494 * Search for a enum value that has the corresponding name as an XML value. The current
495 * conversion from enum name to XML value is to lowercase the name and strip out all
496 * underscore characters. This method returns a match to these criteria, or <code>null</code>
497 * if no such enum exists.
499 * @param <T> then enum type.
500 * @param name the XML value, null ok.
501 * @param enumClass the class of the enum.
502 * @return the found enum value, or <code>null</code>.
504 public static <T extends Enum<T>> Enum<T> findEnum(String name,
505 Class<? extends Enum<T>> enumClass) {
510 for (Enum<T> e : enumClass.getEnumConstants()) {
511 if (e.name().toLowerCase().replace("_", "").equals(name)) {
520 * Convert a string to a double including formatting specifications of the OpenRocket
521 * file format. This accepts all formatting that is valid for
522 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
524 * @param s the string to parse.
525 * @return the numerical value.
526 * @throws NumberFormatException the the string cannot be parsed.
528 public static double stringToDouble(String s) throws NumberFormatException {
530 throw new NumberFormatException("null string");
531 if (s.equalsIgnoreCase("NaN"))
533 if (s.equalsIgnoreCase("Inf"))
534 return Double.POSITIVE_INFINITY;
535 if (s.equalsIgnoreCase("-Inf"))
536 return Double.NEGATIVE_INFINITY;
537 return Double.parseDouble(s);
546 * The starting point of the handlers. Accepts a single <openrocket> element and hands
547 * the contents to be read by a OpenRocketContentsHandler.
549 class OpenRocketHandler extends AbstractElementHandler {
550 private final DocumentLoadingContext context;
551 private OpenRocketContentHandler handler = null;
553 public OpenRocketHandler(DocumentLoadingContext context) {
554 this.context = context;
558 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
559 * has not been read yet.
561 * @return the document read, or null.
563 public OpenRocketDocument getDocument() {
564 return handler.getDocument();
568 public ElementHandler openElement(String element, HashMap<String, String> attributes,
569 WarningSet warnings) {
571 // Check for unknown elements
572 if (!element.equals("openrocket")) {
573 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
577 // Check for first call
578 if (handler != null) {
579 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
584 // Check version number
585 String version = null;
586 String creator = attributes.remove("creator");
587 String docVersion = attributes.remove("version");
588 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
589 if (v.equals(docVersion)) {
594 if (version == null) {
595 String str = "Unsupported document version";
596 if (docVersion != null)
597 str += " " + docVersion;
598 if (creator != null && !creator.trim().equals(""))
599 str += " (written using '" + creator.trim() + "')";
600 str += ", attempting to read file anyway.";
604 context.setFileVersion(parseVersion(docVersion));
606 handler = new OpenRocketContentHandler(context);
611 private int parseVersion(String docVersion) {
612 if (docVersion == null)
615 Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion);
617 int major = Integer.parseInt(m.group(1));
618 int minor = Integer.parseInt(m.group(2));
619 return major * DocumentConfig.FILE_VERSION_DIVISOR + minor;
626 public void closeElement(String element, HashMap<String, String> attributes,
627 String content, WarningSet warnings) throws SAXException {
628 attributes.remove("version");
629 attributes.remove("creator");
630 super.closeElement(element, attributes, content, warnings);
638 * Handles the content of the <openrocket> tag.
640 class OpenRocketContentHandler extends AbstractElementHandler {
641 private final DocumentLoadingContext context;
642 private final OpenRocketDocument doc;
643 private final Rocket rocket;
645 private boolean rocketDefined = false;
646 private boolean simulationsDefined = false;
648 public OpenRocketContentHandler(DocumentLoadingContext context) {
649 this.context = context;
650 this.rocket = new Rocket();
651 this.doc = new OpenRocketDocument(rocket);
655 public OpenRocketDocument getDocument() {
662 public ElementHandler openElement(String element, HashMap<String, String> attributes,
663 WarningSet warnings) {
665 if (element.equals("rocket")) {
668 .fromString("Multiple rocket designs within one document, "
669 + "ignoring later ones."));
672 rocketDefined = true;
673 return new ComponentParameterHandler(rocket, context);
676 if (element.equals("simulations")) {
677 if (simulationsDefined) {
679 .fromString("Multiple simulation definitions within one document, "
680 + "ignoring later ones."));
683 simulationsDefined = true;
684 return new SimulationsHandler(doc, context);
687 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
697 * A handler that creates components from the corresponding elements. The control of the
698 * contents is passed on to ComponentParameterHandler.
700 class ComponentHandler extends AbstractElementHandler {
701 private final DocumentLoadingContext context;
702 private final RocketComponent parent;
704 public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) {
705 this.parent = parent;
706 this.context = context;
710 public ElementHandler openElement(String element, HashMap<String, String> attributes,
711 WarningSet warnings) {
713 // Attempt to construct new component
714 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
716 if (constructor == null) {
717 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
723 c = constructor.newInstance();
724 } catch (InstantiationException e) {
725 throw new BugException("Error constructing component.", e);
726 } catch (IllegalAccessException e) {
727 throw new BugException("Error constructing component.", e);
728 } catch (InvocationTargetException e) {
729 throw Reflection.handleWrappedException(e);
734 return new ComponentParameterHandler(c, context);
740 * A handler that populates the parameters of a previously constructed rocket component.
741 * This uses the setters, or delegates the handling to another handler for specific
744 class ComponentParameterHandler extends AbstractElementHandler {
745 private final DocumentLoadingContext context;
746 private final RocketComponent component;
748 public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) {
750 this.context = context;
754 public ElementHandler openElement(String element, HashMap<String, String> attributes,
755 WarningSet warnings) {
757 // Check for specific elements that contain other elements
758 if (element.equals("subcomponents")) {
759 return new ComponentHandler(component, context);
761 if (element.equals("motormount")) {
762 if (!(component instanceof MotorMount)) {
763 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
766 return new MotorMountHandler((MotorMount) component, context);
768 if (element.equals("finpoints")) {
769 if (!(component instanceof FreeformFinSet)) {
770 warnings.add(Warning.fromString("Illegal component defined for fin points."));
773 return new FinSetPointHandler((FreeformFinSet) component, context);
775 if (element.equals("motorconfiguration")) {
776 if (!(component instanceof Rocket)) {
777 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
780 return new MotorConfigurationHandler((Rocket) component, context);
784 return PlainTextHandler.INSTANCE;
788 public void closeElement(String element, HashMap<String, String> attributes,
789 String content, WarningSet warnings) {
791 if (element.equals("subcomponents") || element.equals("motormount") ||
792 element.equals("finpoints") || element.equals("motorconfiguration")) {
796 // Search for the correct setter class
799 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
800 String setterKey = c.getSimpleName() + ":" + element;
801 Setter s = DocumentConfig.setters.get(setterKey);
804 s.set(component, content, attributes, warnings);
807 if (DocumentConfig.setters.containsKey(setterKey)) {
808 // Key exists but is null -> invalid parameter
814 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
815 + component.getComponentName() + ", ignoring."));
822 * A handler that reads the <point> specifications within the freeformfinset's
823 * <finpoints> elements.
825 class FinSetPointHandler extends AbstractElementHandler {
826 @SuppressWarnings("unused")
827 private final DocumentLoadingContext context;
828 private final FreeformFinSet finset;
829 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
831 public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) {
832 this.finset = finset;
833 this.context = context;
837 public ElementHandler openElement(String element, HashMap<String, String> attributes,
838 WarningSet warnings) {
839 return PlainTextHandler.INSTANCE;
844 public void closeElement(String element, HashMap<String, String> attributes,
845 String content, WarningSet warnings) throws SAXException {
847 String strx = attributes.remove("x");
848 String stry = attributes.remove("y");
849 if (strx == null || stry == null) {
850 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
854 double x = Double.parseDouble(strx);
855 double y = Double.parseDouble(stry);
856 coordinates.add(new Coordinate(x, y));
857 } catch (NumberFormatException e) {
858 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
862 super.closeElement(element, attributes, content, warnings);
866 public void endHandler(String element, HashMap<String, String> attributes,
867 String content, WarningSet warnings) {
869 finset.setPoints(coordinates.toArray(new Coordinate[0]));
870 } catch (IllegalFinPointException e) {
871 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
877 class MotorMountHandler extends AbstractElementHandler {
878 private final DocumentLoadingContext context;
879 private final MotorMount mount;
880 private MotorHandler motorHandler;
882 public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) {
884 this.context = context;
885 mount.setMotorMount(true);
889 public ElementHandler openElement(String element, HashMap<String, String> attributes,
890 WarningSet warnings) {
892 if (element.equals("motor")) {
893 motorHandler = new MotorHandler(context);
897 if (element.equals("ignitionevent") ||
898 element.equals("ignitiondelay") ||
899 element.equals("overhang")) {
900 return PlainTextHandler.INSTANCE;
903 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
910 public void closeElement(String element, HashMap<String, String> attributes,
911 String content, WarningSet warnings) throws SAXException {
913 if (element.equals("motor")) {
914 String id = attributes.get("configid");
915 if (id == null || id.equals("")) {
916 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
920 Motor motor = motorHandler.getMotor(warnings);
921 mount.setMotor(id, motor);
922 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
926 if (element.equals("ignitionevent")) {
927 MotorMount.IgnitionEvent event = null;
928 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
929 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
935 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
938 mount.setIgnitionEvent(event);
942 if (element.equals("ignitiondelay")) {
945 d = Double.parseDouble(content);
946 } catch (NumberFormatException nfe) {
947 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
950 mount.setIgnitionDelay(d);
954 if (element.equals("overhang")) {
957 d = Double.parseDouble(content);
958 } catch (NumberFormatException nfe) {
959 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
962 mount.setMotorOverhang(d);
966 super.closeElement(element, attributes, content, warnings);
973 class MotorConfigurationHandler extends AbstractElementHandler {
974 @SuppressWarnings("unused")
975 private final DocumentLoadingContext context;
976 private final Rocket rocket;
977 private String name = null;
978 private boolean inNameElement = false;
980 public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) {
981 this.rocket = rocket;
982 this.context = context;
986 public ElementHandler openElement(String element, HashMap<String, String> attributes,
987 WarningSet warnings) {
989 if (inNameElement || !element.equals("name")) {
990 warnings.add(Warning.FILE_INVALID_PARAMETER);
993 inNameElement = true;
995 return PlainTextHandler.INSTANCE;
999 public void closeElement(String element, HashMap<String, String> attributes,
1000 String content, WarningSet warnings) {
1005 public void endHandler(String element, HashMap<String, String> attributes,
1006 String content, WarningSet warnings) throws SAXException {
1008 String configid = attributes.remove("configid");
1009 if (configid == null || configid.equals("")) {
1010 warnings.add(Warning.FILE_INVALID_PARAMETER);
1014 if (!rocket.addMotorConfigurationID(configid)) {
1015 warnings.add("Duplicate motor configuration ID used.");
1019 if (name != null && name.trim().length() > 0) {
1020 rocket.setMotorConfigurationName(configid, name);
1023 if ("true".equals(attributes.remove("default"))) {
1024 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
1027 super.closeElement(element, attributes, content, warnings);
1032 class MotorHandler extends AbstractElementHandler {
1033 /** File version where latest digest format was introduced */
1034 private static final int MOTOR_DIGEST_VERSION = 104;
1036 private final DocumentLoadingContext context;
1037 private Motor.Type type = null;
1038 private String manufacturer = null;
1039 private String designation = null;
1040 private String digest = null;
1041 private double diameter = Double.NaN;
1042 private double length = Double.NaN;
1043 private double delay = Double.NaN;
1045 public MotorHandler(DocumentLoadingContext context) {
1046 this.context = context;
1051 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1052 WarningSet warnings) {
1053 return PlainTextHandler.INSTANCE;
1058 * Return the motor to use, or null.
1060 public Motor getMotor(WarningSet warnings) {
1061 return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings);
1065 * Return the delay to use for the motor.
1067 public double getDelay(WarningSet warnings) {
1068 if (Double.isNaN(delay)) {
1069 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1070 return Motor.PLUGGED;
1077 public void closeElement(String element, HashMap<String, String> attributes,
1078 String content, WarningSet warnings) throws SAXException {
1080 content = content.trim();
1082 if (element.equals("type")) {
1086 for (Motor.Type t : Motor.Type.values()) {
1087 if (t.name().toLowerCase().equals(content.trim())) {
1093 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1096 } else if (element.equals("manufacturer")) {
1099 manufacturer = content.trim();
1101 } else if (element.equals("designation")) {
1104 designation = content.trim();
1106 } else if (element.equals("digest")) {
1108 // Digest is used only for file versions saved using the same digest algorithm
1109 if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) {
1110 digest = content.trim();
1113 } else if (element.equals("diameter")) {
1116 diameter = Double.NaN;
1118 diameter = Double.parseDouble(content.trim());
1119 } catch (NumberFormatException e) {
1122 if (Double.isNaN(diameter)) {
1123 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1126 } else if (element.equals("length")) {
1129 length = Double.NaN;
1131 length = Double.parseDouble(content.trim());
1132 } catch (NumberFormatException ignore) {
1135 if (Double.isNaN(length)) {
1136 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1139 } else if (element.equals("delay")) {
1143 if (content.equals("none")) {
1144 delay = Motor.PLUGGED;
1147 delay = Double.parseDouble(content.trim());
1148 } catch (NumberFormatException ignore) {
1151 if (Double.isNaN(delay)) {
1152 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1158 super.closeElement(element, attributes, content, warnings);
1166 class SimulationsHandler extends AbstractElementHandler {
1167 private final DocumentLoadingContext context;
1168 private final OpenRocketDocument doc;
1169 private SingleSimulationHandler handler;
1171 public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1173 this.context = context;
1177 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1178 WarningSet warnings) {
1180 if (!element.equals("simulation")) {
1181 warnings.add("Unknown element '" + element + "', ignoring.");
1185 handler = new SingleSimulationHandler(doc, context);
1190 public void closeElement(String element, HashMap<String, String> attributes,
1191 String content, WarningSet warnings) throws SAXException {
1192 attributes.remove("status");
1193 super.closeElement(element, attributes, content, warnings);
1199 class SingleSimulationHandler extends AbstractElementHandler {
1200 private final DocumentLoadingContext context;
1202 private final OpenRocketDocument doc;
1204 private String name;
1206 private SimulationConditionsHandler conditionHandler;
1207 private FlightDataHandler dataHandler;
1209 private final List<String> listeners = new ArrayList<String>();
1211 public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1213 this.context = context;
1219 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1220 WarningSet warnings) {
1222 if (element.equals("name") || element.equals("simulator") ||
1223 element.equals("calculator") || element.equals("listener")) {
1224 return PlainTextHandler.INSTANCE;
1225 } else if (element.equals("conditions")) {
1226 conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context);
1227 return conditionHandler;
1228 } else if (element.equals("flightdata")) {
1229 dataHandler = new FlightDataHandler(context);
1232 warnings.add("Unknown element '" + element + "', ignoring.");
1238 public void closeElement(String element, HashMap<String, String> attributes,
1239 String content, WarningSet warnings) {
1241 if (element.equals("name")) {
1243 } else if (element.equals("simulator")) {
1244 if (!content.trim().equals("RK4Simulator")) {
1245 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1247 } else if (element.equals("calculator")) {
1248 if (!content.trim().equals("BarrowmanCalculator")) {
1249 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1251 } else if (element.equals("listener") && content.trim().length() > 0) {
1252 listeners.add(content.trim());
1258 public void endHandler(String element, HashMap<String, String> attributes,
1259 String content, WarningSet warnings) {
1261 String s = attributes.get("status");
1262 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1263 if (status == null) {
1264 warnings.add("Simulation status unknown, assuming outdated.");
1265 status = Simulation.Status.OUTDATED;
1268 SimulationOptions conditions;
1269 if (conditionHandler != null) {
1270 conditions = conditionHandler.getConditions();
1272 warnings.add("Simulation conditions not defined, using defaults.");
1273 conditions = new SimulationOptions(doc.getRocket());
1277 name = "Simulation";
1280 if (dataHandler == null)
1283 data = dataHandler.getFlightData();
1285 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1286 conditions, listeners, data);
1288 doc.addSimulation(simulation);
1294 class SimulationConditionsHandler extends AbstractElementHandler {
1295 private final DocumentLoadingContext context;
1296 private SimulationOptions conditions;
1297 private AtmosphereHandler atmosphereHandler;
1299 public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) {
1300 this.context = context;
1301 conditions = new SimulationOptions(rocket);
1302 // Set up default loading settings (which may differ from the new defaults)
1303 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1306 public SimulationOptions getConditions() {
1311 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1312 WarningSet warnings) {
1313 if (element.equals("atmosphere")) {
1314 atmosphereHandler = new AtmosphereHandler(attributes.get("model"), context);
1315 return atmosphereHandler;
1317 return PlainTextHandler.INSTANCE;
1321 public void closeElement(String element, HashMap<String, String> attributes,
1322 String content, WarningSet warnings) {
1324 double d = Double.NaN;
1326 d = Double.parseDouble(content);
1327 } catch (NumberFormatException ignore) {
1331 if (element.equals("configid")) {
1332 if (content.equals("")) {
1333 conditions.setMotorConfigurationID(null);
1335 conditions.setMotorConfigurationID(content);
1337 } else if (element.equals("launchrodlength")) {
1338 if (Double.isNaN(d)) {
1339 warnings.add("Illegal launch rod length defined, ignoring.");
1341 conditions.setLaunchRodLength(d);
1343 } else if (element.equals("launchrodangle")) {
1344 if (Double.isNaN(d)) {
1345 warnings.add("Illegal launch rod angle defined, ignoring.");
1347 conditions.setLaunchRodAngle(d * Math.PI / 180);
1349 } else if (element.equals("launchroddirection")) {
1350 if (Double.isNaN(d)) {
1351 warnings.add("Illegal launch rod direction defined, ignoring.");
1353 conditions.setLaunchRodDirection(d * Math.PI / 180);
1355 } else if (element.equals("windaverage")) {
1356 if (Double.isNaN(d)) {
1357 warnings.add("Illegal average windspeed defined, ignoring.");
1359 conditions.setWindSpeedAverage(d);
1361 } else if (element.equals("windturbulence")) {
1362 if (Double.isNaN(d)) {
1363 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1365 conditions.setWindTurbulenceIntensity(d);
1367 } else if (element.equals("launchaltitude")) {
1368 if (Double.isNaN(d)) {
1369 warnings.add("Illegal launch altitude defined, ignoring.");
1371 conditions.setLaunchAltitude(d);
1373 } else if (element.equals("launchlatitude")) {
1374 if (Double.isNaN(d)) {
1375 warnings.add("Illegal launch latitude defined, ignoring.");
1377 conditions.setLaunchLatitude(d);
1379 } else if (element.equals("launchlongitude")) {
1380 if (Double.isNaN(d)) {
1381 warnings.add("Illegal launch longitude.");
1383 conditions.setLaunchLongitude(d);
1385 } else if (element.equals("geodeticmethod")) {
1386 GeodeticComputationStrategy gcs =
1387 (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1389 conditions.setGeodeticComputation(gcs);
1391 warnings.add("Unknown geodetic computation method '" + content + "'");
1393 } else if (element.equals("atmosphere")) {
1394 atmosphereHandler.storeSettings(conditions, warnings);
1395 } else if (element.equals("timestep")) {
1396 if (Double.isNaN(d)) {
1397 warnings.add("Illegal time step defined, ignoring.");
1399 conditions.setTimeStep(d);
1406 class AtmosphereHandler extends AbstractElementHandler {
1407 @SuppressWarnings("unused")
1408 private final DocumentLoadingContext context;
1409 private final String model;
1410 private double temperature = Double.NaN;
1411 private double pressure = Double.NaN;
1413 public AtmosphereHandler(String model, DocumentLoadingContext context) {
1415 this.context = context;
1419 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1420 WarningSet warnings) {
1421 return PlainTextHandler.INSTANCE;
1425 public void closeElement(String element, HashMap<String, String> attributes,
1426 String content, WarningSet warnings) throws SAXException {
1428 double d = Double.NaN;
1430 d = Double.parseDouble(content);
1431 } catch (NumberFormatException ignore) {
1434 if (element.equals("basetemperature")) {
1435 if (Double.isNaN(d)) {
1436 warnings.add("Illegal base temperature specified, ignoring.");
1439 } else if (element.equals("basepressure")) {
1440 if (Double.isNaN(d)) {
1441 warnings.add("Illegal base pressure specified, ignoring.");
1445 super.closeElement(element, attributes, content, warnings);
1450 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1451 if (!Double.isNaN(pressure)) {
1452 cond.setLaunchPressure(pressure);
1454 if (!Double.isNaN(temperature)) {
1455 cond.setLaunchTemperature(temperature);
1458 if ("isa".equals(model)) {
1459 cond.setISAAtmosphere(true);
1460 } else if ("extendedisa".equals(model)) {
1461 cond.setISAAtmosphere(false);
1463 cond.setISAAtmosphere(true);
1464 warnings.add("Unknown atmospheric model, using ISA.");
1471 class FlightDataHandler extends AbstractElementHandler {
1472 private final DocumentLoadingContext context;
1474 private FlightDataBranchHandler dataHandler;
1475 private WarningSet warningSet = new WarningSet();
1476 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1478 private FlightData data;
1481 public FlightDataHandler(DocumentLoadingContext context) {
1482 this.context = context;
1485 public FlightData getFlightData() {
1490 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1491 WarningSet warnings) {
1493 if (element.equals("warning")) {
1494 return PlainTextHandler.INSTANCE;
1496 if (element.equals("databranch")) {
1497 if (attributes.get("name") == null || attributes.get("types") == null) {
1498 warnings.add("Illegal flight data definition, ignoring.");
1501 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1502 attributes.get("types"), context);
1506 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1512 public void closeElement(String element, HashMap<String, String> attributes,
1513 String content, WarningSet warnings) {
1515 if (element.equals("databranch")) {
1516 FlightDataBranch branch = dataHandler.getBranch();
1517 if (branch.getLength() > 0) {
1518 branches.add(branch);
1520 } else if (element.equals("warning")) {
1521 warningSet.add(Warning.fromString(content));
1527 public void endHandler(String element, HashMap<String, String> attributes,
1528 String content, WarningSet warnings) {
1530 if (branches.size() > 0) {
1531 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1533 double maxAltitude = Double.NaN;
1534 double maxVelocity = Double.NaN;
1535 double maxAcceleration = Double.NaN;
1536 double maxMach = Double.NaN;
1537 double timeToApogee = Double.NaN;
1538 double flightTime = Double.NaN;
1539 double groundHitVelocity = Double.NaN;
1540 double launchRodVelocity = Double.NaN;
1541 double deploymentVelocity = Double.NaN;
1544 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1545 } catch (NumberFormatException ignore) {
1548 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1549 } catch (NumberFormatException ignore) {
1552 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1553 } catch (NumberFormatException ignore) {
1556 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1557 } catch (NumberFormatException ignore) {
1560 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1561 } catch (NumberFormatException ignore) {
1564 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1565 } catch (NumberFormatException ignore) {
1569 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1570 } catch (NumberFormatException ignore) {
1573 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1574 } catch (NumberFormatException ignore) {
1577 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1578 } catch (NumberFormatException ignore) {
1581 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1582 timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1585 data.getWarningSet().addAll(warningSet);
1593 class FlightDataBranchHandler extends AbstractElementHandler {
1594 @SuppressWarnings("unused")
1595 private final DocumentLoadingContext context;
1596 private final FlightDataType[] types;
1597 private final FlightDataBranch branch;
1599 public FlightDataBranchHandler(String name, String typeList, DocumentLoadingContext context) {
1600 this.context = context;
1601 String[] split = typeList.split(",");
1602 types = new FlightDataType[split.length];
1603 for (int i = 0; i < split.length; i++) {
1604 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1607 // TODO: LOW: May throw an IllegalArgumentException
1608 branch = new FlightDataBranch(name, types);
1611 public FlightDataBranch getBranch() {
1617 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1618 WarningSet warnings) {
1620 if (element.equals("datapoint"))
1621 return PlainTextHandler.INSTANCE;
1622 if (element.equals("event"))
1623 return PlainTextHandler.INSTANCE;
1625 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1631 public void closeElement(String element, HashMap<String, String> attributes,
1632 String content, WarningSet warnings) {
1634 if (element.equals("event")) {
1636 FlightEvent.Type type;
1639 time = DocumentConfig.stringToDouble(attributes.get("time"));
1640 } catch (NumberFormatException e) {
1641 warnings.add("Illegal event specification, ignoring.");
1645 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1647 warnings.add("Illegal event specification, ignoring.");
1651 branch.addEvent(new FlightEvent(type, time));
1655 if (!element.equals("datapoint")) {
1656 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1660 // element == "datapoint"
1663 // Check line format
1664 String[] split = content.split(",");
1665 if (split.length != types.length) {
1666 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1670 // Parse the doubles
1671 double[] values = new double[split.length];
1672 for (int i = 0; i < values.length; i++) {
1674 values[i] = DocumentConfig.stringToDouble(split[i]);
1675 } catch (NumberFormatException e) {
1676 warnings.add("Data point format error, ignoring point.");
1681 // Add point to branch
1683 for (int i = 0; i < types.length; i++) {
1684 branch.setValue(types[i], values[i]);
1693 ///////////////// Setters implementation
1699 * Set the specified value to the given component.
1701 * @param component the component to which to set.
1702 * @param value the value within the element.
1703 * @param attributes attributes for the element.
1704 * @param warnings the warning set to use.
1706 public void set(RocketComponent component, String value,
1707 HashMap<String, String> attributes, WarningSet warnings);
1711 //// StringSetter - sets the value to the contained String
1712 class StringSetter implements Setter {
1713 private final Reflection.Method setMethod;
1715 public StringSetter(Reflection.Method set) {
1720 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1721 WarningSet warnings) {
1722 setMethod.invoke(c, s);
1726 //// IntSetter - set an integer value
1727 class IntSetter implements Setter {
1728 private final Reflection.Method setMethod;
1730 public IntSetter(Reflection.Method set) {
1735 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1736 WarningSet warnings) {
1738 int n = Integer.parseInt(s);
1739 setMethod.invoke(c, n);
1740 } catch (NumberFormatException e) {
1741 warnings.add(Warning.FILE_INVALID_PARAMETER);
1747 //// BooleanSetter - set a boolean value
1748 class BooleanSetter implements Setter {
1749 private final Reflection.Method setMethod;
1751 public BooleanSetter(Reflection.Method set) {
1756 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1757 WarningSet warnings) {
1760 if (s.equalsIgnoreCase("true")) {
1761 setMethod.invoke(c, true);
1762 } else if (s.equalsIgnoreCase("false")) {
1763 setMethod.invoke(c, false);
1765 warnings.add(Warning.FILE_INVALID_PARAMETER);
1772 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1773 //// calls a setXXX(boolean) method.
1774 class DoubleSetter implements Setter {
1775 private final Reflection.Method setMethod;
1776 private final String specialString;
1777 private final Reflection.Method specialMethod;
1778 private final double multiplier;
1781 * Set only the double value.
1782 * @param set set method for the double value.
1784 public DoubleSetter(Reflection.Method set) {
1785 this.setMethod = set;
1786 this.specialString = null;
1787 this.specialMethod = null;
1788 this.multiplier = 1.0;
1792 * Multiply with the given multiplier and set the double value.
1793 * @param set set method for the double value.
1794 * @param mul multiplier.
1796 public DoubleSetter(Reflection.Method set, double mul) {
1797 this.setMethod = set;
1798 this.specialString = null;
1799 this.specialMethod = null;
1800 this.multiplier = mul;
1804 * Set the double value, or if the value equals the special string, use the
1805 * special setter and set it to true.
1807 * @param set double setter.
1808 * @param special special string
1809 * @param specialMethod boolean setter.
1811 public DoubleSetter(Reflection.Method set, String special,
1812 Reflection.Method specialMethod) {
1813 this.setMethod = set;
1814 this.specialString = special;
1815 this.specialMethod = specialMethod;
1816 this.multiplier = 1.0;
1821 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1822 WarningSet warnings) {
1826 // Check for special case
1827 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1828 specialMethod.invoke(c, true);
1834 double d = Double.parseDouble(s);
1835 setMethod.invoke(c, d * multiplier);
1836 } catch (NumberFormatException e) {
1837 warnings.add(Warning.FILE_INVALID_PARAMETER);
1843 class OverrideSetter implements Setter {
1844 private final Reflection.Method setMethod;
1845 private final Reflection.Method enabledMethod;
1847 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1848 this.setMethod = set;
1849 this.enabledMethod = enabledMethod;
1853 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1854 WarningSet warnings) {
1857 double d = Double.parseDouble(s);
1858 setMethod.invoke(c, d);
1859 enabledMethod.invoke(c, true);
1860 } catch (NumberFormatException e) {
1861 warnings.add(Warning.FILE_INVALID_PARAMETER);
1866 //// EnumSetter - sets a generic enum type
1867 class EnumSetter<T extends Enum<T>> implements Setter {
1868 private final Reflection.Method setter;
1869 private final Class<T> enumClass;
1871 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1873 this.enumClass = enumClass;
1877 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1878 WarningSet warnings) {
1880 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1881 if (setEnum == null) {
1882 warnings.add(Warning.FILE_INVALID_PARAMETER);
1886 setter.invoke(c, setEnum);
1891 //// ColorSetter - sets a Color value
1892 class ColorSetter implements Setter {
1893 private final Reflection.Method setMethod;
1895 public ColorSetter(Reflection.Method set) {
1900 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1901 WarningSet warnings) {
1903 String red = attributes.get("red");
1904 String green = attributes.get("green");
1905 String blue = attributes.get("blue");
1907 if (red == null || green == null || blue == null) {
1908 warnings.add(Warning.FILE_INVALID_PARAMETER);
1914 r = Integer.parseInt(red);
1915 g = Integer.parseInt(green);
1916 b = Integer.parseInt(blue);
1917 } catch (NumberFormatException e) {
1918 warnings.add(Warning.FILE_INVALID_PARAMETER);
1922 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1923 warnings.add(Warning.FILE_INVALID_PARAMETER);
1927 Color color = new Color(r, g, b);
1928 setMethod.invoke(c, color);
1930 if (!s.trim().equals("")) {
1931 warnings.add(Warning.FILE_INVALID_PARAMETER);
1938 class MaterialSetter implements Setter {
1939 private final Reflection.Method setMethod;
1940 private final Material.Type type;
1942 public MaterialSetter(Reflection.Method set, Material.Type type) {
1943 this.setMethod = set;
1948 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1949 WarningSet warnings) {
1955 if (name.equals("")) {
1956 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1963 str = attributes.remove("density");
1965 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1969 density = Double.parseDouble(str);
1970 } catch (NumberFormatException e) {
1971 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1976 // double thickness = 0;
1977 // str = attributes.remove("thickness");
1980 // thickness = Double.parseDouble(str);
1981 // } catch (NumberFormatException e){
1982 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1986 // Check type if specified
1987 str = attributes.remove("type");
1988 if (str != null && !type.name().toLowerCase().equals(str)) {
1989 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1993 mat = Databases.findMaterial(type, name, density, false);
1995 setMethod.invoke(c, mat);
2002 class PositionSetter implements Setter {
2005 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
2006 WarningSet warnings) {
2008 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
2009 RocketComponent.Position.class);
2011 warnings.add(Warning.FILE_INVALID_PARAMETER);
2017 pos = Double.parseDouble(value);
2018 } catch (NumberFormatException e) {
2019 warnings.add(Warning.FILE_INVALID_PARAMETER);
2023 if (c instanceof FinSet) {
2024 ((FinSet) c).setRelativePosition(type);
2025 c.setPositionValue(pos);
2026 } else if (c instanceof LaunchLug) {
2027 ((LaunchLug) c).setRelativePosition(type);
2028 c.setPositionValue(pos);
2029 } else if (c instanceof InternalComponent) {
2030 ((InternalComponent) c).setRelativePosition(type);
2031 c.setPositionValue(pos);
2033 warnings.add(Warning.FILE_INVALID_PARAMETER);
2040 class FinTabPositionSetter extends DoubleSetter {
2042 public FinTabPositionSetter() {
2043 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2047 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2048 WarningSet warnings) {
2050 if (!(c instanceof FinSet)) {
2051 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2054 String relative = attributes.get("relativeto");
2055 FinSet.TabRelativePosition position =
2056 (TabRelativePosition) DocumentConfig.findEnum(relative,
2057 FinSet.TabRelativePosition.class);
2059 if (position != null) {
2061 ((FinSet) c).setTabRelativePosition(position);
2064 if (relative == null) {
2065 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2067 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2071 super.set(c, s, attributes, warnings);
2078 class ClusterConfigurationSetter implements Setter {
2081 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2082 WarningSet warnings) {
2084 if (!(component instanceof Clusterable)) {
2085 warnings.add("Illegal component defined as cluster.");
2089 ClusterConfiguration config = null;
2090 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2091 if (c.getXMLName().equals(value)) {
2097 if (config == null) {
2098 warnings.add("Illegal cluster configuration specified.");
2102 ((Clusterable) component).setClusterConfiguration(config);