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.FlightData;
71 import net.sf.openrocket.simulation.FlightDataBranch;
72 import net.sf.openrocket.simulation.FlightDataType;
73 import net.sf.openrocket.simulation.FlightEvent;
74 import net.sf.openrocket.simulation.FlightEvent.Type;
75 import net.sf.openrocket.simulation.SimulationOptions;
76 import net.sf.openrocket.startup.Application;
77 import net.sf.openrocket.unit.UnitGroup;
78 import net.sf.openrocket.util.BugException;
79 import net.sf.openrocket.util.Color;
80 import net.sf.openrocket.util.Coordinate;
81 import net.sf.openrocket.util.GeodeticComputationStrategy;
82 import net.sf.openrocket.util.LineStyle;
83 import net.sf.openrocket.util.Reflection;
85 import org.xml.sax.InputSource;
86 import org.xml.sax.SAXException;
90 * Class that loads a rocket definition from an OpenRocket rocket file.
92 * This class uses SAX to read the XML file format. The
93 * #loadFromStream(InputStream) method simply sets the system up and
94 * starts the parsing, while the actual logic is in the private inner class
95 * <code>OpenRocketHandler</code>.
97 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
99 public class OpenRocketLoader extends AbstractRocketLoader {
100 private static final LogHelper log = Application.getLogger();
104 public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException,
106 log.info("Loading .ork file");
107 DocumentLoadingContext context = new DocumentLoadingContext();
108 context.setMotorFinder(motorFinder);
110 InputSource xmlSource = new InputSource(source);
111 OpenRocketHandler handler = new OpenRocketHandler(context);
115 SimpleSAX.readXML(xmlSource, handler, warnings);
116 } catch (SAXException e) {
117 log.warn("Malformed XML in input");
118 throw new RocketLoadException("Malformed XML in input.", e);
122 OpenRocketDocument doc = handler.getDocument();
123 doc.getDefaultConfiguration().setAllStages();
125 // Deduce suitable time skip
126 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
127 for (Simulation s : doc.getSimulations()) {
128 if (s.getStatus() == Simulation.Status.EXTERNAL ||
129 s.getStatus() == Simulation.Status.NOT_SIMULATED)
131 if (s.getSimulatedData() == null)
133 if (s.getSimulatedData().getBranchCount() == 0)
135 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
138 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
142 double previousTime = Double.NaN;
143 for (double time : list) {
144 if (time - previousTime < timeSkip)
145 timeSkip = time - previousTime;
150 timeSkip = Math.rint(timeSkip * 100) / 100;
152 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
153 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
154 doc.getDefaultStorageOptions().setExplicitlySet(false);
157 log.info("Loading done");
165 class DocumentConfig {
167 /* Remember to update OpenRocketSaver as well! */
168 public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4", "1.5" };
171 * Divisor used in converting an integer version to the point-represented version.
172 * The integer version divided by this value is the major version and the remainder is
173 * the minor version. For example 101 corresponds to file version "1.1".
175 public static final int FILE_VERSION_DIVISOR = 100;
178 //////// Component constructors
179 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
182 // External components
183 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
184 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
185 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
186 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
187 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
188 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
189 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
191 // Internal components
192 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
193 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
194 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
195 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
196 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
198 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
199 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
200 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
201 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
204 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
206 } catch (NoSuchMethodException e) {
207 throw new BugException(
208 "Error in constructing the 'constructors' HashMap.");
213 //////// Parameter setters
215 * The keys are of the form Class:param, where Class is the class name and param
216 * the element name. Setters are searched for in descending class order.
217 * A setter of null means setting the parameter is not allowed.
219 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
222 setters.put("RocketComponent:name", new StringSetter(
223 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
224 setters.put("RocketComponent:color", new ColorSetter(
225 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
226 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
227 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
229 setters.put("RocketComponent:position", new PositionSetter());
230 setters.put("RocketComponent:overridemass", new OverrideSetter(
231 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
232 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
233 setters.put("RocketComponent:overridecg", new OverrideSetter(
234 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
235 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
236 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
237 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
238 setters.put("RocketComponent:comment", new StringSetter(
239 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
240 setters.put("RocketComponent:preset", new ComponentPresetSetter(
241 Reflection.findMethod(RocketComponent.class, "loadPreset", ComponentPreset.class)));
244 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
245 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
247 setters.put("ExternalComponent:material", new MaterialSetter(
248 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
249 Material.Type.BULK));
252 setters.put("BodyComponent:length", new DoubleSetter(
253 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
255 // SymmetricComponent
256 setters.put("SymmetricComponent:thickness", new DoubleSetter(
257 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
259 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
262 setters.put("BodyTube:radius", new DoubleSetter(
263 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
265 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
268 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
269 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
270 Transition.Shape.class));
271 setters.put("Transition:shapeclipped", new BooleanSetter(
272 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
273 setters.put("Transition:shapeparameter", new DoubleSetter(
274 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
276 setters.put("Transition:foreradius", new DoubleSetter(
277 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
279 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
280 setters.put("Transition:aftradius", new DoubleSetter(
281 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
283 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
285 setters.put("Transition:foreshoulderradius", new DoubleSetter(
286 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
287 setters.put("Transition:foreshoulderlength", new DoubleSetter(
288 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
289 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
290 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
291 setters.put("Transition:foreshouldercapped", new BooleanSetter(
292 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
294 setters.put("Transition:aftshoulderradius", new DoubleSetter(
295 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
296 setters.put("Transition:aftshoulderlength", new DoubleSetter(
297 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
298 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
299 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
300 setters.put("Transition:aftshouldercapped", new BooleanSetter(
301 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
303 // NoseCone - disable disallowed elements
304 setters.put("NoseCone:foreradius", null);
305 setters.put("NoseCone:foreshoulderradius", null);
306 setters.put("NoseCone:foreshoulderlength", null);
307 setters.put("NoseCone:foreshoulderthickness", null);
308 setters.put("NoseCone:foreshouldercapped", null);
311 setters.put("FinSet:fincount", new IntSetter(
312 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
313 setters.put("FinSet:rotation", new DoubleSetter(
314 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
315 setters.put("FinSet:thickness", new DoubleSetter(
316 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
317 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
318 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
319 FinSet.CrossSection.class));
320 setters.put("FinSet:cant", new DoubleSetter(
321 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
322 setters.put("FinSet:tabheight", new DoubleSetter(
323 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
324 setters.put("FinSet:tablength", new DoubleSetter(
325 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
326 setters.put("FinSet:tabposition", new FinTabPositionSetter());
329 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
330 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
331 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
332 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
333 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
334 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
335 setters.put("TrapezoidFinSet:height", new DoubleSetter(
336 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
339 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
340 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
341 setters.put("EllipticalFinSet:height", new DoubleSetter(
342 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
344 // FreeformFinSet points handled as a special handler
347 setters.put("LaunchLug:radius", new DoubleSetter(
348 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
349 setters.put("LaunchLug:length", new DoubleSetter(
350 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
351 setters.put("LaunchLug:thickness", new DoubleSetter(
352 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
353 setters.put("LaunchLug:radialdirection", new DoubleSetter(
354 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
357 // InternalComponent - nothing
359 // StructuralComponent
360 setters.put("StructuralComponent:material", new MaterialSetter(
361 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
362 Material.Type.BULK));
365 setters.put("RingComponent:length", new DoubleSetter(
366 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
367 setters.put("RingComponent:radialposition", new DoubleSetter(
368 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
369 setters.put("RingComponent:radialdirection", new DoubleSetter(
370 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
373 // ThicknessRingComponent - radius on separate components due to differing automatics
374 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
375 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
378 setters.put("EngineBlock:outerradius", new DoubleSetter(
379 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
381 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
384 setters.put("TubeCoupler:outerradius", new DoubleSetter(
385 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
387 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
390 setters.put("InnerTube:outerradius", new DoubleSetter(
391 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
392 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
393 setters.put("InnerTube:clusterscale", new DoubleSetter(
394 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
395 setters.put("InnerTube:clusterrotation", new DoubleSetter(
396 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
399 // RadiusRingComponent
402 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
403 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
404 setters.put("Bulkhead:outerradius", new DoubleSetter(
405 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
407 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
410 setters.put("CenteringRing:innerradius", new DoubleSetter(
411 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
413 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
414 setters.put("CenteringRing:outerradius", new DoubleSetter(
415 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
417 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
421 setters.put("MassObject:packedlength", new DoubleSetter(
422 Reflection.findMethod(MassObject.class, "setLength", double.class)));
423 setters.put("MassObject:packedradius", new DoubleSetter(
424 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
425 setters.put("MassObject:radialposition", new DoubleSetter(
426 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
427 setters.put("MassObject:radialdirection", new DoubleSetter(
428 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
432 setters.put("MassComponent:mass", new DoubleSetter(
433 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
436 setters.put("ShockCord:cordlength", new DoubleSetter(
437 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
438 setters.put("ShockCord:material", new MaterialSetter(
439 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
440 Material.Type.LINE));
443 setters.put("RecoveryDevice:cd", new DoubleSetter(
444 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
446 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
447 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
448 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
449 RecoveryDevice.DeployEvent.class));
450 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
451 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
452 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
453 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
454 setters.put("RecoveryDevice:material", new MaterialSetter(
455 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
456 Material.Type.SURFACE));
459 setters.put("Parachute:diameter", new DoubleSetter(
460 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
461 setters.put("Parachute:linecount", new IntSetter(
462 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
463 setters.put("Parachute:linelength", new DoubleSetter(
464 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
465 setters.put("Parachute:linematerial", new MaterialSetter(
466 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
467 Material.Type.LINE));
470 setters.put("Streamer:striplength", new DoubleSetter(
471 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
472 setters.put("Streamer:stripwidth", new DoubleSetter(
473 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
476 // <motorconfiguration> handled by separate handler
477 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
478 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
479 ReferenceType.class));
480 setters.put("Rocket:customreference", new DoubleSetter(
481 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
482 setters.put("Rocket:designer", new StringSetter(
483 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
484 setters.put("Rocket:revision", new StringSetter(
485 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
488 setters.put("Stage:separationevent", new EnumSetter<Stage.SeparationEvent>(
489 Reflection.findMethod(Stage.class, "setSeparationEvent", Stage.SeparationEvent.class),
490 Stage.SeparationEvent.class));
491 setters.put("Stage:separationdelay", new DoubleSetter(
492 Reflection.findMethod(Stage.class, "setSeparationDelay", double.class)));
498 * Search for a enum value that has the corresponding name as an XML value. The current
499 * conversion from enum name to XML value is to lowercase the name and strip out all
500 * underscore characters. This method returns a match to these criteria, or <code>null</code>
501 * if no such enum exists.
503 * @param <T> then enum type.
504 * @param name the XML value, null ok.
505 * @param enumClass the class of the enum.
506 * @return the found enum value, or <code>null</code>.
508 public static <T extends Enum<T>> Enum<T> findEnum(String name,
509 Class<? extends Enum<T>> enumClass) {
514 for (Enum<T> e : enumClass.getEnumConstants()) {
515 if (e.name().toLowerCase(Locale.ENGLISH).replace("_", "").equals(name)) {
524 * Convert a string to a double including formatting specifications of the OpenRocket
525 * file format. This accepts all formatting that is valid for
526 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
528 * @param s the string to parse.
529 * @return the numerical value.
530 * @throws NumberFormatException the the string cannot be parsed.
532 public static double stringToDouble(String s) throws NumberFormatException {
534 throw new NumberFormatException("null string");
535 if (s.equalsIgnoreCase("NaN"))
537 if (s.equalsIgnoreCase("Inf"))
538 return Double.POSITIVE_INFINITY;
539 if (s.equalsIgnoreCase("-Inf"))
540 return Double.NEGATIVE_INFINITY;
541 return Double.parseDouble(s);
550 * The starting point of the handlers. Accepts a single <openrocket> element and hands
551 * the contents to be read by a OpenRocketContentsHandler.
553 class OpenRocketHandler extends AbstractElementHandler {
554 private final DocumentLoadingContext context;
555 private OpenRocketContentHandler handler = null;
557 public OpenRocketHandler(DocumentLoadingContext context) {
558 this.context = context;
562 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
563 * has not been read yet.
565 * @return the document read, or null.
567 public OpenRocketDocument getDocument() {
568 return handler.getDocument();
572 public ElementHandler openElement(String element, HashMap<String, String> attributes,
573 WarningSet warnings) {
575 // Check for unknown elements
576 if (!element.equals("openrocket")) {
577 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
581 // Check for first call
582 if (handler != null) {
583 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
588 // Check version number
589 String version = null;
590 String creator = attributes.remove("creator");
591 String docVersion = attributes.remove("version");
592 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
593 if (v.equals(docVersion)) {
598 if (version == null) {
599 String str = "Unsupported document version";
600 if (docVersion != null)
601 str += " " + docVersion;
602 if (creator != null && !creator.trim().equals(""))
603 str += " (written using '" + creator.trim() + "')";
604 str += ", attempting to read file anyway.";
608 context.setFileVersion(parseVersion(docVersion));
610 handler = new OpenRocketContentHandler(context);
615 private int parseVersion(String docVersion) {
616 if (docVersion == null)
619 Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion);
621 int major = Integer.parseInt(m.group(1));
622 int minor = Integer.parseInt(m.group(2));
623 return major * DocumentConfig.FILE_VERSION_DIVISOR + minor;
630 public void closeElement(String element, HashMap<String, String> attributes,
631 String content, WarningSet warnings) throws SAXException {
632 attributes.remove("version");
633 attributes.remove("creator");
634 super.closeElement(element, attributes, content, warnings);
642 * Handles the content of the <openrocket> tag.
644 class OpenRocketContentHandler extends AbstractElementHandler {
645 private final DocumentLoadingContext context;
646 private final OpenRocketDocument doc;
647 private final Rocket rocket;
649 private boolean rocketDefined = false;
650 private boolean simulationsDefined = false;
652 public OpenRocketContentHandler(DocumentLoadingContext context) {
653 this.context = context;
654 this.rocket = new Rocket();
655 this.doc = new OpenRocketDocument(rocket);
659 public OpenRocketDocument getDocument() {
666 public ElementHandler openElement(String element, HashMap<String, String> attributes,
667 WarningSet warnings) {
669 if (element.equals("rocket")) {
672 .fromString("Multiple rocket designs within one document, "
673 + "ignoring later ones."));
676 rocketDefined = true;
677 return new ComponentParameterHandler(rocket, context);
680 if (element.equals("simulations")) {
681 if (simulationsDefined) {
683 .fromString("Multiple simulation definitions within one document, "
684 + "ignoring later ones."));
687 simulationsDefined = true;
688 return new SimulationsHandler(doc, context);
691 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
701 * A handler that creates components from the corresponding elements. The control of the
702 * contents is passed on to ComponentParameterHandler.
704 class ComponentHandler extends AbstractElementHandler {
705 private final DocumentLoadingContext context;
706 private final RocketComponent parent;
708 public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) {
709 this.parent = parent;
710 this.context = context;
714 public ElementHandler openElement(String element, HashMap<String, String> attributes,
715 WarningSet warnings) {
717 // Attempt to construct new component
718 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
720 if (constructor == null) {
721 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
727 c = constructor.newInstance();
728 } catch (InstantiationException e) {
729 throw new BugException("Error constructing component.", e);
730 } catch (IllegalAccessException e) {
731 throw new BugException("Error constructing component.", e);
732 } catch (InvocationTargetException e) {
733 throw Reflection.handleWrappedException(e);
738 return new ComponentParameterHandler(c, context);
744 * A handler that populates the parameters of a previously constructed rocket component.
745 * This uses the setters, or delegates the handling to another handler for specific
748 class ComponentParameterHandler extends AbstractElementHandler {
749 private final DocumentLoadingContext context;
750 private final RocketComponent component;
752 public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) {
754 this.context = context;
758 public ElementHandler openElement(String element, HashMap<String, String> attributes,
759 WarningSet warnings) {
761 // Check for specific elements that contain other elements
762 if (element.equals("subcomponents")) {
763 return new ComponentHandler(component, context);
765 if (element.equals("motormount")) {
766 if (!(component instanceof MotorMount)) {
767 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
770 return new MotorMountHandler((MotorMount) component, context);
772 if (element.equals("finpoints")) {
773 if (!(component instanceof FreeformFinSet)) {
774 warnings.add(Warning.fromString("Illegal component defined for fin points."));
777 return new FinSetPointHandler((FreeformFinSet) component, context);
779 if (element.equals("motorconfiguration")) {
780 if (!(component instanceof Rocket)) {
781 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
784 return new MotorConfigurationHandler((Rocket) component, context);
788 return PlainTextHandler.INSTANCE;
792 public void closeElement(String element, HashMap<String, String> attributes,
793 String content, WarningSet warnings) {
795 if (element.equals("subcomponents") || element.equals("motormount") ||
796 element.equals("finpoints") || element.equals("motorconfiguration")) {
800 // Search for the correct setter class
803 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
804 String setterKey = c.getSimpleName() + ":" + element;
805 Setter s = DocumentConfig.setters.get(setterKey);
808 s.set(component, content, attributes, warnings);
811 if (DocumentConfig.setters.containsKey(setterKey)) {
812 // Key exists but is null -> invalid parameter
818 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
819 + component.getComponentName() + ", ignoring."));
826 * A handler that reads the <point> specifications within the freeformfinset's
827 * <finpoints> elements.
829 class FinSetPointHandler extends AbstractElementHandler {
830 @SuppressWarnings("unused")
831 private final DocumentLoadingContext context;
832 private final FreeformFinSet finset;
833 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
835 public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) {
836 this.finset = finset;
837 this.context = context;
841 public ElementHandler openElement(String element, HashMap<String, String> attributes,
842 WarningSet warnings) {
843 return PlainTextHandler.INSTANCE;
848 public void closeElement(String element, HashMap<String, String> attributes,
849 String content, WarningSet warnings) throws SAXException {
851 String strx = attributes.remove("x");
852 String stry = attributes.remove("y");
853 if (strx == null || stry == null) {
854 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
858 double x = Double.parseDouble(strx);
859 double y = Double.parseDouble(stry);
860 coordinates.add(new Coordinate(x, y));
861 } catch (NumberFormatException e) {
862 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
866 super.closeElement(element, attributes, content, warnings);
870 public void endHandler(String element, HashMap<String, String> attributes,
871 String content, WarningSet warnings) {
873 finset.setPoints(coordinates.toArray(new Coordinate[0]));
874 } catch (IllegalFinPointException e) {
875 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
881 class MotorMountHandler extends AbstractElementHandler {
882 private final DocumentLoadingContext context;
883 private final MotorMount mount;
884 private MotorHandler motorHandler;
886 public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) {
888 this.context = context;
889 mount.setMotorMount(true);
893 public ElementHandler openElement(String element, HashMap<String, String> attributes,
894 WarningSet warnings) {
896 if (element.equals("motor")) {
897 motorHandler = new MotorHandler(context);
901 if (element.equals("ignitionevent") ||
902 element.equals("ignitiondelay") ||
903 element.equals("overhang")) {
904 return PlainTextHandler.INSTANCE;
907 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
914 public void closeElement(String element, HashMap<String, String> attributes,
915 String content, WarningSet warnings) throws SAXException {
917 if (element.equals("motor")) {
918 String id = attributes.get("configid");
919 if (id == null || id.equals("")) {
920 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
924 Motor motor = motorHandler.getMotor(warnings);
925 mount.setMotor(id, motor);
926 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
930 if (element.equals("ignitionevent")) {
931 MotorMount.IgnitionEvent event = null;
932 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
933 if (e.name().toLowerCase(Locale.ENGLISH).replaceAll("_", "").equals(content)) {
939 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
942 mount.setIgnitionEvent(event);
946 if (element.equals("ignitiondelay")) {
949 d = Double.parseDouble(content);
950 } catch (NumberFormatException nfe) {
951 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
954 mount.setIgnitionDelay(d);
958 if (element.equals("overhang")) {
961 d = Double.parseDouble(content);
962 } catch (NumberFormatException nfe) {
963 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
966 mount.setMotorOverhang(d);
970 super.closeElement(element, attributes, content, warnings);
977 class MotorConfigurationHandler extends AbstractElementHandler {
978 @SuppressWarnings("unused")
979 private final DocumentLoadingContext context;
980 private final Rocket rocket;
981 private String name = null;
982 private boolean inNameElement = false;
984 public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) {
985 this.rocket = rocket;
986 this.context = context;
990 public ElementHandler openElement(String element, HashMap<String, String> attributes,
991 WarningSet warnings) {
993 if (inNameElement || !element.equals("name")) {
994 warnings.add(Warning.FILE_INVALID_PARAMETER);
997 inNameElement = true;
999 return PlainTextHandler.INSTANCE;
1003 public void closeElement(String element, HashMap<String, String> attributes,
1004 String content, WarningSet warnings) {
1009 public void endHandler(String element, HashMap<String, String> attributes,
1010 String content, WarningSet warnings) throws SAXException {
1012 String configid = attributes.remove("configid");
1013 if (configid == null || configid.equals("")) {
1014 warnings.add(Warning.FILE_INVALID_PARAMETER);
1018 if (!rocket.addMotorConfigurationID(configid)) {
1019 warnings.add("Duplicate motor configuration ID used.");
1023 if (name != null && name.trim().length() > 0) {
1024 rocket.setMotorConfigurationName(configid, name);
1027 if ("true".equals(attributes.remove("default"))) {
1028 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
1031 super.closeElement(element, attributes, content, warnings);
1036 class MotorHandler extends AbstractElementHandler {
1037 /** File version where latest digest format was introduced */
1038 private static final int MOTOR_DIGEST_VERSION = 104;
1040 private final DocumentLoadingContext context;
1041 private Motor.Type type = null;
1042 private String manufacturer = null;
1043 private String designation = null;
1044 private String digest = null;
1045 private double diameter = Double.NaN;
1046 private double length = Double.NaN;
1047 private double delay = Double.NaN;
1049 public MotorHandler(DocumentLoadingContext context) {
1050 this.context = context;
1055 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1056 WarningSet warnings) {
1057 return PlainTextHandler.INSTANCE;
1062 * Return the motor to use, or null.
1064 public Motor getMotor(WarningSet warnings) {
1065 return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings);
1069 * Return the delay to use for the motor.
1071 public double getDelay(WarningSet warnings) {
1072 if (Double.isNaN(delay)) {
1073 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1074 return Motor.PLUGGED;
1081 public void closeElement(String element, HashMap<String, String> attributes,
1082 String content, WarningSet warnings) throws SAXException {
1084 content = content.trim();
1086 if (element.equals("type")) {
1090 for (Motor.Type t : Motor.Type.values()) {
1091 if (t.name().toLowerCase(Locale.ENGLISH).equals(content.trim())) {
1097 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1100 } else if (element.equals("manufacturer")) {
1103 manufacturer = content.trim();
1105 } else if (element.equals("designation")) {
1108 designation = content.trim();
1110 } else if (element.equals("digest")) {
1112 // Digest is used only for file versions saved using the same digest algorithm
1113 if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) {
1114 digest = content.trim();
1117 } else if (element.equals("diameter")) {
1120 diameter = Double.NaN;
1122 diameter = Double.parseDouble(content.trim());
1123 } catch (NumberFormatException e) {
1126 if (Double.isNaN(diameter)) {
1127 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1130 } else if (element.equals("length")) {
1133 length = Double.NaN;
1135 length = Double.parseDouble(content.trim());
1136 } catch (NumberFormatException ignore) {
1139 if (Double.isNaN(length)) {
1140 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1143 } else if (element.equals("delay")) {
1147 if (content.equals("none")) {
1148 delay = Motor.PLUGGED;
1151 delay = Double.parseDouble(content.trim());
1152 } catch (NumberFormatException ignore) {
1155 if (Double.isNaN(delay)) {
1156 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1162 super.closeElement(element, attributes, content, warnings);
1170 class SimulationsHandler extends AbstractElementHandler {
1171 private final DocumentLoadingContext context;
1172 private final OpenRocketDocument doc;
1173 private SingleSimulationHandler handler;
1175 public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1177 this.context = context;
1181 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1182 WarningSet warnings) {
1184 if (!element.equals("simulation")) {
1185 warnings.add("Unknown element '" + element + "', ignoring.");
1189 handler = new SingleSimulationHandler(doc, context);
1194 public void closeElement(String element, HashMap<String, String> attributes,
1195 String content, WarningSet warnings) throws SAXException {
1196 attributes.remove("status");
1197 super.closeElement(element, attributes, content, warnings);
1203 class SingleSimulationHandler extends AbstractElementHandler {
1204 private final DocumentLoadingContext context;
1206 private final OpenRocketDocument doc;
1208 private String name;
1210 private SimulationConditionsHandler conditionHandler;
1211 private FlightDataHandler dataHandler;
1213 private final List<String> listeners = new ArrayList<String>();
1215 public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1217 this.context = context;
1223 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1224 WarningSet warnings) {
1226 if (element.equals("name") || element.equals("simulator") ||
1227 element.equals("calculator") || element.equals("listener")) {
1228 return PlainTextHandler.INSTANCE;
1229 } else if (element.equals("conditions")) {
1230 conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context);
1231 return conditionHandler;
1232 } else if (element.equals("flightdata")) {
1233 dataHandler = new FlightDataHandler(context);
1236 warnings.add("Unknown element '" + element + "', ignoring.");
1242 public void closeElement(String element, HashMap<String, String> attributes,
1243 String content, WarningSet warnings) {
1245 if (element.equals("name")) {
1247 } else if (element.equals("simulator")) {
1248 if (!content.trim().equals("RK4Simulator")) {
1249 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1251 } else if (element.equals("calculator")) {
1252 if (!content.trim().equals("BarrowmanCalculator")) {
1253 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1255 } else if (element.equals("listener") && content.trim().length() > 0) {
1256 listeners.add(content.trim());
1262 public void endHandler(String element, HashMap<String, String> attributes,
1263 String content, WarningSet warnings) {
1265 String s = attributes.get("status");
1266 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1267 if (status == null) {
1268 warnings.add("Simulation status unknown, assuming outdated.");
1269 status = Simulation.Status.OUTDATED;
1272 SimulationOptions conditions;
1273 if (conditionHandler != null) {
1274 conditions = conditionHandler.getConditions();
1276 warnings.add("Simulation conditions not defined, using defaults.");
1277 conditions = new SimulationOptions(doc.getRocket());
1281 name = "Simulation";
1284 if (dataHandler == null)
1287 data = dataHandler.getFlightData();
1289 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1290 conditions, listeners, data);
1292 doc.addSimulation(simulation);
1298 class SimulationConditionsHandler extends AbstractElementHandler {
1299 private final DocumentLoadingContext context;
1300 private SimulationOptions conditions;
1301 private AtmosphereHandler atmosphereHandler;
1303 public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) {
1304 this.context = context;
1305 conditions = new SimulationOptions(rocket);
1306 // Set up default loading settings (which may differ from the new defaults)
1307 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1310 public SimulationOptions getConditions() {
1315 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1316 WarningSet warnings) {
1317 if (element.equals("atmosphere")) {
1318 atmosphereHandler = new AtmosphereHandler(attributes.get("model"), context);
1319 return atmosphereHandler;
1321 return PlainTextHandler.INSTANCE;
1325 public void closeElement(String element, HashMap<String, String> attributes,
1326 String content, WarningSet warnings) {
1328 double d = Double.NaN;
1330 d = Double.parseDouble(content);
1331 } catch (NumberFormatException ignore) {
1335 if (element.equals("configid")) {
1336 if (content.equals("")) {
1337 conditions.setMotorConfigurationID(null);
1339 conditions.setMotorConfigurationID(content);
1341 } else if (element.equals("launchrodlength")) {
1342 if (Double.isNaN(d)) {
1343 warnings.add("Illegal launch rod length defined, ignoring.");
1345 conditions.setLaunchRodLength(d);
1347 } else if (element.equals("launchrodangle")) {
1348 if (Double.isNaN(d)) {
1349 warnings.add("Illegal launch rod angle defined, ignoring.");
1351 conditions.setLaunchRodAngle(d * Math.PI / 180);
1353 } else if (element.equals("launchroddirection")) {
1354 if (Double.isNaN(d)) {
1355 warnings.add("Illegal launch rod direction defined, ignoring.");
1357 conditions.setLaunchRodDirection(d * Math.PI / 180);
1359 } else if (element.equals("windaverage")) {
1360 if (Double.isNaN(d)) {
1361 warnings.add("Illegal average windspeed defined, ignoring.");
1363 conditions.setWindSpeedAverage(d);
1365 } else if (element.equals("windturbulence")) {
1366 if (Double.isNaN(d)) {
1367 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1369 conditions.setWindTurbulenceIntensity(d);
1371 } else if (element.equals("launchaltitude")) {
1372 if (Double.isNaN(d)) {
1373 warnings.add("Illegal launch altitude defined, ignoring.");
1375 conditions.setLaunchAltitude(d);
1377 } else if (element.equals("launchlatitude")) {
1378 if (Double.isNaN(d)) {
1379 warnings.add("Illegal launch latitude defined, ignoring.");
1381 conditions.setLaunchLatitude(d);
1383 } else if (element.equals("launchlongitude")) {
1384 if (Double.isNaN(d)) {
1385 warnings.add("Illegal launch longitude.");
1387 conditions.setLaunchLongitude(d);
1389 } else if (element.equals("geodeticmethod")) {
1390 GeodeticComputationStrategy gcs =
1391 (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1393 conditions.setGeodeticComputation(gcs);
1395 warnings.add("Unknown geodetic computation method '" + content + "'");
1397 } else if (element.equals("atmosphere")) {
1398 atmosphereHandler.storeSettings(conditions, warnings);
1399 } else if (element.equals("timestep")) {
1400 if (Double.isNaN(d)) {
1401 warnings.add("Illegal time step defined, ignoring.");
1403 conditions.setTimeStep(d);
1410 class AtmosphereHandler extends AbstractElementHandler {
1411 @SuppressWarnings("unused")
1412 private final DocumentLoadingContext context;
1413 private final String model;
1414 private double temperature = Double.NaN;
1415 private double pressure = Double.NaN;
1417 public AtmosphereHandler(String model, DocumentLoadingContext context) {
1419 this.context = context;
1423 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1424 WarningSet warnings) {
1425 return PlainTextHandler.INSTANCE;
1429 public void closeElement(String element, HashMap<String, String> attributes,
1430 String content, WarningSet warnings) throws SAXException {
1432 double d = Double.NaN;
1434 d = Double.parseDouble(content);
1435 } catch (NumberFormatException ignore) {
1438 if (element.equals("basetemperature")) {
1439 if (Double.isNaN(d)) {
1440 warnings.add("Illegal base temperature specified, ignoring.");
1443 } else if (element.equals("basepressure")) {
1444 if (Double.isNaN(d)) {
1445 warnings.add("Illegal base pressure specified, ignoring.");
1449 super.closeElement(element, attributes, content, warnings);
1454 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1455 if (!Double.isNaN(pressure)) {
1456 cond.setLaunchPressure(pressure);
1458 if (!Double.isNaN(temperature)) {
1459 cond.setLaunchTemperature(temperature);
1462 if ("isa".equals(model)) {
1463 cond.setISAAtmosphere(true);
1464 } else if ("extendedisa".equals(model)) {
1465 cond.setISAAtmosphere(false);
1467 cond.setISAAtmosphere(true);
1468 warnings.add("Unknown atmospheric model, using ISA.");
1475 class FlightDataHandler extends AbstractElementHandler {
1476 private final DocumentLoadingContext context;
1478 private FlightDataBranchHandler dataHandler;
1479 private WarningSet warningSet = new WarningSet();
1480 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1482 private FlightData data;
1485 public FlightDataHandler(DocumentLoadingContext context) {
1486 this.context = context;
1489 public FlightData getFlightData() {
1494 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1495 WarningSet warnings) {
1497 if (element.equals("warning")) {
1498 return PlainTextHandler.INSTANCE;
1500 if (element.equals("databranch")) {
1501 if (attributes.get("name") == null || attributes.get("types") == null) {
1502 warnings.add("Illegal flight data definition, ignoring.");
1505 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1506 attributes.get("types"), context);
1510 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1516 public void closeElement(String element, HashMap<String, String> attributes,
1517 String content, WarningSet warnings) {
1519 if (element.equals("databranch")) {
1520 FlightDataBranch branch = dataHandler.getBranch();
1521 if (branch.getLength() > 0) {
1522 branches.add(branch);
1524 } else if (element.equals("warning")) {
1525 warningSet.add(Warning.fromString(content));
1531 public void endHandler(String element, HashMap<String, String> attributes,
1532 String content, WarningSet warnings) {
1534 if (branches.size() > 0) {
1535 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1537 double maxAltitude = Double.NaN;
1538 double maxVelocity = Double.NaN;
1539 double maxAcceleration = Double.NaN;
1540 double maxMach = Double.NaN;
1541 double timeToApogee = Double.NaN;
1542 double flightTime = Double.NaN;
1543 double groundHitVelocity = Double.NaN;
1544 double launchRodVelocity = Double.NaN;
1545 double deploymentVelocity = Double.NaN;
1548 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1549 } catch (NumberFormatException ignore) {
1552 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1553 } catch (NumberFormatException ignore) {
1556 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1557 } catch (NumberFormatException ignore) {
1560 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1561 } catch (NumberFormatException ignore) {
1564 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1565 } catch (NumberFormatException ignore) {
1568 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1569 } catch (NumberFormatException ignore) {
1573 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1574 } catch (NumberFormatException ignore) {
1577 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1578 } catch (NumberFormatException ignore) {
1581 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1582 } catch (NumberFormatException ignore) {
1585 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1586 timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1589 data.getWarningSet().addAll(warningSet);
1597 class FlightDataBranchHandler extends AbstractElementHandler {
1598 @SuppressWarnings("unused")
1599 private final DocumentLoadingContext context;
1600 private final FlightDataType[] types;
1601 private final FlightDataBranch branch;
1603 public FlightDataBranchHandler(String name, String typeList, DocumentLoadingContext context) {
1604 this.context = context;
1605 String[] split = typeList.split(",");
1606 types = new FlightDataType[split.length];
1607 for (int i = 0; i < split.length; i++) {
1608 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1611 // TODO: LOW: May throw an IllegalArgumentException
1612 branch = new FlightDataBranch(name, types);
1615 public FlightDataBranch getBranch() {
1621 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1622 WarningSet warnings) {
1624 if (element.equals("datapoint"))
1625 return PlainTextHandler.INSTANCE;
1626 if (element.equals("event"))
1627 return PlainTextHandler.INSTANCE;
1629 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1635 public void closeElement(String element, HashMap<String, String> attributes,
1636 String content, WarningSet warnings) {
1638 if (element.equals("event")) {
1640 FlightEvent.Type type;
1643 time = DocumentConfig.stringToDouble(attributes.get("time"));
1644 } catch (NumberFormatException e) {
1645 warnings.add("Illegal event specification, ignoring.");
1649 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1651 warnings.add("Illegal event specification, ignoring.");
1655 branch.addEvent(new FlightEvent(type, time));
1659 if (!element.equals("datapoint")) {
1660 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1664 // element == "datapoint"
1667 // Check line format
1668 String[] split = content.split(",");
1669 if (split.length != types.length) {
1670 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1674 // Parse the doubles
1675 double[] values = new double[split.length];
1676 for (int i = 0; i < values.length; i++) {
1678 values[i] = DocumentConfig.stringToDouble(split[i]);
1679 } catch (NumberFormatException e) {
1680 warnings.add("Data point format error, ignoring point.");
1685 // Add point to branch
1687 for (int i = 0; i < types.length; i++) {
1688 branch.setValue(types[i], values[i]);
1697 ///////////////// Setters implementation
1703 * Set the specified value to the given component.
1705 * @param component the component to which to set.
1706 * @param value the value within the element.
1707 * @param attributes attributes for the element.
1708 * @param warnings the warning set to use.
1710 public void set(RocketComponent component, String value,
1711 HashMap<String, String> attributes, WarningSet warnings);
1715 //// StringSetter - sets the value to the contained String
1716 class StringSetter implements Setter {
1717 private final Reflection.Method setMethod;
1719 public StringSetter(Reflection.Method set) {
1724 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1725 WarningSet warnings) {
1726 setMethod.invoke(c, s);
1730 //// IntSetter - set an integer value
1731 class IntSetter implements Setter {
1732 private final Reflection.Method setMethod;
1734 public IntSetter(Reflection.Method set) {
1739 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1740 WarningSet warnings) {
1742 int n = Integer.parseInt(s);
1743 setMethod.invoke(c, n);
1744 } catch (NumberFormatException e) {
1745 warnings.add(Warning.FILE_INVALID_PARAMETER);
1751 //// BooleanSetter - set a boolean value
1752 class BooleanSetter implements Setter {
1753 private final Reflection.Method setMethod;
1755 public BooleanSetter(Reflection.Method set) {
1760 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1761 WarningSet warnings) {
1764 if (s.equalsIgnoreCase("true")) {
1765 setMethod.invoke(c, true);
1766 } else if (s.equalsIgnoreCase("false")) {
1767 setMethod.invoke(c, false);
1769 warnings.add(Warning.FILE_INVALID_PARAMETER);
1776 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1777 //// calls a setXXX(boolean) method.
1778 class DoubleSetter implements Setter {
1779 private final Reflection.Method setMethod;
1780 private final String specialString;
1781 private final Reflection.Method specialMethod;
1782 private final double multiplier;
1785 * Set only the double value.
1786 * @param set set method for the double value.
1788 public DoubleSetter(Reflection.Method set) {
1789 this.setMethod = set;
1790 this.specialString = null;
1791 this.specialMethod = null;
1792 this.multiplier = 1.0;
1796 * Multiply with the given multiplier and set the double value.
1797 * @param set set method for the double value.
1798 * @param mul multiplier.
1800 public DoubleSetter(Reflection.Method set, double mul) {
1801 this.setMethod = set;
1802 this.specialString = null;
1803 this.specialMethod = null;
1804 this.multiplier = mul;
1808 * Set the double value, or if the value equals the special string, use the
1809 * special setter and set it to true.
1811 * @param set double setter.
1812 * @param special special string
1813 * @param specialMethod boolean setter.
1815 public DoubleSetter(Reflection.Method set, String special,
1816 Reflection.Method specialMethod) {
1817 this.setMethod = set;
1818 this.specialString = special;
1819 this.specialMethod = specialMethod;
1820 this.multiplier = 1.0;
1825 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1826 WarningSet warnings) {
1830 // Check for special case
1831 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1832 specialMethod.invoke(c, true);
1838 double d = Double.parseDouble(s);
1839 setMethod.invoke(c, d * multiplier);
1840 } catch (NumberFormatException e) {
1841 warnings.add(Warning.FILE_INVALID_PARAMETER);
1847 class OverrideSetter implements Setter {
1848 private final Reflection.Method setMethod;
1849 private final Reflection.Method enabledMethod;
1851 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1852 this.setMethod = set;
1853 this.enabledMethod = enabledMethod;
1857 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1858 WarningSet warnings) {
1861 double d = Double.parseDouble(s);
1862 setMethod.invoke(c, d);
1863 enabledMethod.invoke(c, true);
1864 } catch (NumberFormatException e) {
1865 warnings.add(Warning.FILE_INVALID_PARAMETER);
1870 //// EnumSetter - sets a generic enum type
1871 class EnumSetter<T extends Enum<T>> implements Setter {
1872 private final Reflection.Method setter;
1873 private final Class<T> enumClass;
1875 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1877 this.enumClass = enumClass;
1881 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1882 WarningSet warnings) {
1884 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1885 if (setEnum == null) {
1886 warnings.add(Warning.FILE_INVALID_PARAMETER);
1890 setter.invoke(c, setEnum);
1895 //// ColorSetter - sets a Color value
1896 class ColorSetter implements Setter {
1897 private final Reflection.Method setMethod;
1899 public ColorSetter(Reflection.Method set) {
1904 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1905 WarningSet warnings) {
1907 String red = attributes.get("red");
1908 String green = attributes.get("green");
1909 String blue = attributes.get("blue");
1911 if (red == null || green == null || blue == null) {
1912 warnings.add(Warning.FILE_INVALID_PARAMETER);
1918 r = Integer.parseInt(red);
1919 g = Integer.parseInt(green);
1920 b = Integer.parseInt(blue);
1921 } catch (NumberFormatException e) {
1922 warnings.add(Warning.FILE_INVALID_PARAMETER);
1926 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1927 warnings.add(Warning.FILE_INVALID_PARAMETER);
1931 Color color = new Color(r, g, b);
1932 setMethod.invoke(c, color);
1934 if (!s.trim().equals("")) {
1935 warnings.add(Warning.FILE_INVALID_PARAMETER);
1940 ////ComponentPresetSetter - sets a ComponentPreset value
1941 class ComponentPresetSetter implements Setter {
1942 private final Reflection.Method setMethod;
1944 public ComponentPresetSetter(Reflection.Method set) {
1945 this.setMethod = set;
1949 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1950 WarningSet warnings) {
1951 // FIXME - probably need more data in the warning messages - like what component preset...
1952 String manufacturerName = attributes.get("manufacturer");
1953 if ( manufacturerName == null ) {
1954 warnings.add(Warning.fromString("Invalid ComponentPreset, no manufacturer specified. Ignored"));
1958 String productNo = attributes.get("partno");
1959 if ( productNo == null ) {
1960 warnings.add(Warning.fromString("Invalid ComponentPreset, no partno specified. Ignored"));
1964 String digest = attributes.get("digest");
1965 if ( digest == null ) {
1966 warnings.add(Warning.fromString("Invalid ComponentPreset, no digest specified."));
1969 String type = attributes.get("type");
1970 if ( type == null ) {
1971 warnings.add(Warning.fromString("Invalid ComponentPreset, no type specified."));
1974 List<ComponentPreset> presets = Application.getComponentPresetDao().find( manufacturerName, productNo );
1976 ComponentPreset matchingPreset = null;
1978 for( ComponentPreset preset: presets ) {
1979 if ( digest != null && preset.getDigest().equals(digest) ) {
1980 // Found one with matching digest. Take it.
1981 matchingPreset = preset;
1984 if ( type != null && preset.getType().name().equals(type) && matchingPreset != null) {
1985 // Found the first one with matching type.
1986 matchingPreset = preset;
1991 if ( matchingPreset == null ) {
1992 warnings.add(Warning.fromString("No matching ComponentPreset found"));
1996 if ( digest != null && !matchingPreset.getDigest().equals(digest) ) {
1997 warnings.add(Warning.fromString("ComponentPreset has wrong digest"));
2000 setMethod.invoke(c, matchingPreset);
2005 ////MaterialSetter - sets a Material value
2006 class MaterialSetter implements Setter {
2007 private final Reflection.Method setMethod;
2008 private final Material.Type type;
2010 public MaterialSetter(Reflection.Method set, Material.Type type) {
2011 this.setMethod = set;
2016 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
2017 WarningSet warnings) {
2023 if (name.equals("")) {
2024 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2031 str = attributes.remove("density");
2033 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2037 density = Double.parseDouble(str);
2038 } catch (NumberFormatException e) {
2039 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2044 // double thickness = 0;
2045 // str = attributes.remove("thickness");
2048 // thickness = Double.parseDouble(str);
2049 // } catch (NumberFormatException e){
2050 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2054 // Check type if specified
2055 str = attributes.remove("type");
2056 if (str != null && !type.name().toLowerCase(Locale.ENGLISH).equals(str)) {
2057 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
2061 mat = Databases.findMaterial(type, name, density, false);
2063 setMethod.invoke(c, mat);
2070 class PositionSetter implements Setter {
2073 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
2074 WarningSet warnings) {
2076 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
2077 RocketComponent.Position.class);
2079 warnings.add(Warning.FILE_INVALID_PARAMETER);
2085 pos = Double.parseDouble(value);
2086 } catch (NumberFormatException e) {
2087 warnings.add(Warning.FILE_INVALID_PARAMETER);
2091 if (c instanceof FinSet) {
2092 ((FinSet) c).setRelativePosition(type);
2093 c.setPositionValue(pos);
2094 } else if (c instanceof LaunchLug) {
2095 ((LaunchLug) c).setRelativePosition(type);
2096 c.setPositionValue(pos);
2097 } else if (c instanceof InternalComponent) {
2098 ((InternalComponent) c).setRelativePosition(type);
2099 c.setPositionValue(pos);
2101 warnings.add(Warning.FILE_INVALID_PARAMETER);
2108 class FinTabPositionSetter extends DoubleSetter {
2110 public FinTabPositionSetter() {
2111 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2115 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2116 WarningSet warnings) {
2118 if (!(c instanceof FinSet)) {
2119 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2122 String relative = attributes.get("relativeto");
2123 FinSet.TabRelativePosition position =
2124 (TabRelativePosition) DocumentConfig.findEnum(relative,
2125 FinSet.TabRelativePosition.class);
2127 if (position != null) {
2129 ((FinSet) c).setTabRelativePosition(position);
2132 if (relative == null) {
2133 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2135 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2139 super.set(c, s, attributes, warnings);
2146 class ClusterConfigurationSetter implements Setter {
2149 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2150 WarningSet warnings) {
2152 if (!(component instanceof Clusterable)) {
2153 warnings.add("Illegal component defined as cluster.");
2157 ClusterConfiguration config = null;
2158 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2159 if (c.getXMLName().equals(value)) {
2165 if (config == null) {
2166 warnings.add("Illegal cluster configuration specified.");
2170 ((Clusterable) component).setClusterConfiguration(config);