1 package net.sf.openrocket.file.openrocket;
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;
11 import net.sf.openrocket.aerodynamics.Warning;
12 import net.sf.openrocket.aerodynamics.WarningSet;
13 import net.sf.openrocket.database.Databases;
14 import net.sf.openrocket.document.OpenRocketDocument;
15 import net.sf.openrocket.document.Simulation;
16 import net.sf.openrocket.document.Simulation.Status;
17 import net.sf.openrocket.document.StorageOptions;
18 import net.sf.openrocket.file.RocketLoadException;
19 import net.sf.openrocket.file.RocketLoader;
20 import net.sf.openrocket.file.simplesax.ElementHandler;
21 import net.sf.openrocket.file.simplesax.PlainTextHandler;
22 import net.sf.openrocket.file.simplesax.SimpleSAX;
23 import net.sf.openrocket.logging.LogHelper;
24 import net.sf.openrocket.material.Material;
25 import net.sf.openrocket.motor.Motor;
26 import net.sf.openrocket.rocketcomponent.BodyComponent;
27 import net.sf.openrocket.rocketcomponent.BodyTube;
28 import net.sf.openrocket.rocketcomponent.Bulkhead;
29 import net.sf.openrocket.rocketcomponent.CenteringRing;
30 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
31 import net.sf.openrocket.rocketcomponent.Clusterable;
32 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
33 import net.sf.openrocket.rocketcomponent.EngineBlock;
34 import net.sf.openrocket.rocketcomponent.ExternalComponent;
35 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
36 import net.sf.openrocket.rocketcomponent.FinSet;
37 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
38 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
39 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
40 import net.sf.openrocket.rocketcomponent.InnerTube;
41 import net.sf.openrocket.rocketcomponent.InternalComponent;
42 import net.sf.openrocket.rocketcomponent.LaunchLug;
43 import net.sf.openrocket.rocketcomponent.MassComponent;
44 import net.sf.openrocket.rocketcomponent.MassObject;
45 import net.sf.openrocket.rocketcomponent.MotorMount;
46 import net.sf.openrocket.rocketcomponent.NoseCone;
47 import net.sf.openrocket.rocketcomponent.Parachute;
48 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
49 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
50 import net.sf.openrocket.rocketcomponent.ReferenceType;
51 import net.sf.openrocket.rocketcomponent.RingComponent;
52 import net.sf.openrocket.rocketcomponent.Rocket;
53 import net.sf.openrocket.rocketcomponent.RocketComponent;
54 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
55 import net.sf.openrocket.rocketcomponent.ShockCord;
56 import net.sf.openrocket.rocketcomponent.Stage;
57 import net.sf.openrocket.rocketcomponent.Streamer;
58 import net.sf.openrocket.rocketcomponent.StructuralComponent;
59 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
60 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
61 import net.sf.openrocket.rocketcomponent.Transition;
62 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
63 import net.sf.openrocket.rocketcomponent.TubeCoupler;
64 import net.sf.openrocket.simulation.FlightData;
65 import net.sf.openrocket.simulation.FlightDataBranch;
66 import net.sf.openrocket.simulation.FlightDataType;
67 import net.sf.openrocket.simulation.FlightEvent;
68 import net.sf.openrocket.simulation.FlightEvent.Type;
69 import net.sf.openrocket.simulation.SimulationOptions;
70 import net.sf.openrocket.startup.Application;
71 import net.sf.openrocket.unit.UnitGroup;
72 import net.sf.openrocket.util.BugException;
73 import net.sf.openrocket.util.Color;
74 import net.sf.openrocket.util.Coordinate;
75 import net.sf.openrocket.util.GeodeticComputationStrategy;
76 import net.sf.openrocket.util.LineStyle;
77 import net.sf.openrocket.util.Reflection;
79 import org.xml.sax.InputSource;
80 import org.xml.sax.SAXException;
84 * Class that loads a rocket definition from an OpenRocket rocket file.
86 * This class uses SAX to read the XML file format. The
87 * {@link #loadFromStream(InputStream)} method simply sets the system up and
88 * starts the parsing, while the actual logic is in the private inner class
89 * <code>OpenRocketHandler</code>.
91 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
93 public class OpenRocketLoader extends RocketLoader {
94 private static final LogHelper log = Application.getLogger();
98 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
100 log.info("Loading .ork file");
102 InputSource xmlSource = new InputSource(source);
103 OpenRocketHandler handler = new OpenRocketHandler();
107 SimpleSAX.readXML(xmlSource, handler, warnings);
108 } catch (SAXException e) {
109 log.warn("Malformed XML in input");
110 throw new RocketLoadException("Malformed XML in input.", e);
114 OpenRocketDocument doc = handler.getDocument();
115 doc.getDefaultConfiguration().setAllStages();
117 // Deduce suitable time skip
118 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
119 for (Simulation s : doc.getSimulations()) {
120 if (s.getStatus() == Simulation.Status.EXTERNAL ||
121 s.getStatus() == Simulation.Status.NOT_SIMULATED)
123 if (s.getSimulatedData() == null)
125 if (s.getSimulatedData().getBranchCount() == 0)
127 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
130 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
134 double previousTime = Double.NaN;
135 for (double time : list) {
136 if (time - previousTime < timeSkip)
137 timeSkip = time - previousTime;
142 timeSkip = Math.rint(timeSkip * 100) / 100;
144 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
145 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
146 doc.getDefaultStorageOptions().setExplicitlySet(false);
149 log.info("Loading done");
157 class DocumentConfig {
159 /* Remember to update OpenRocketSaver as well! */
160 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1", "1.2", "1.3" };
163 //////// Component constructors
164 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
167 // External components
168 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
169 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
170 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
171 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
172 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
173 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
174 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
176 // Internal components
177 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
178 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
179 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
180 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
181 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
183 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
184 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
185 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
186 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
189 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
191 } catch (NoSuchMethodException e) {
192 throw new BugException(
193 "Error in constructing the 'constructors' HashMap.");
198 //////// Parameter setters
200 * The keys are of the form Class:param, where Class is the class name and param
201 * the element name. Setters are searched for in descending class order.
202 * A setter of null means setting the parameter is not allowed.
204 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
207 setters.put("RocketComponent:name", new StringSetter(
208 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
209 setters.put("RocketComponent:color", new ColorSetter(
210 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
211 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
212 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
214 setters.put("RocketComponent:position", new PositionSetter());
215 setters.put("RocketComponent:overridemass", new OverrideSetter(
216 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
217 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
218 setters.put("RocketComponent:overridecg", new OverrideSetter(
219 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
220 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
221 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
222 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
223 setters.put("RocketComponent:comment", new StringSetter(
224 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
227 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
228 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
230 setters.put("ExternalComponent:material", new MaterialSetter(
231 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
232 Material.Type.BULK));
235 setters.put("BodyComponent:length", new DoubleSetter(
236 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
238 // SymmetricComponent
239 setters.put("SymmetricComponent:thickness", new DoubleSetter(
240 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
242 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
245 setters.put("BodyTube:radius", new DoubleSetter(
246 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
248 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
251 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
252 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
253 Transition.Shape.class));
254 setters.put("Transition:shapeclipped", new BooleanSetter(
255 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
256 setters.put("Transition:shapeparameter", new DoubleSetter(
257 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
259 setters.put("Transition:foreradius", new DoubleSetter(
260 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
262 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
263 setters.put("Transition:aftradius", new DoubleSetter(
264 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
266 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
268 setters.put("Transition:foreshoulderradius", new DoubleSetter(
269 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
270 setters.put("Transition:foreshoulderlength", new DoubleSetter(
271 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
272 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
273 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
274 setters.put("Transition:foreshouldercapped", new BooleanSetter(
275 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
277 setters.put("Transition:aftshoulderradius", new DoubleSetter(
278 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
279 setters.put("Transition:aftshoulderlength", new DoubleSetter(
280 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
281 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
282 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
283 setters.put("Transition:aftshouldercapped", new BooleanSetter(
284 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
286 // NoseCone - disable disallowed elements
287 setters.put("NoseCone:foreradius", null);
288 setters.put("NoseCone:foreshoulderradius", null);
289 setters.put("NoseCone:foreshoulderlength", null);
290 setters.put("NoseCone:foreshoulderthickness", null);
291 setters.put("NoseCone:foreshouldercapped", null);
294 setters.put("FinSet:fincount", new IntSetter(
295 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
296 setters.put("FinSet:rotation", new DoubleSetter(
297 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
298 setters.put("FinSet:thickness", new DoubleSetter(
299 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
300 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
301 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
302 FinSet.CrossSection.class));
303 setters.put("FinSet:cant", new DoubleSetter(
304 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
305 setters.put("FinSet:tabheight", new DoubleSetter(
306 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
307 setters.put("FinSet:tablength", new DoubleSetter(
308 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
309 setters.put("FinSet:tabposition", new FinTabPositionSetter());
312 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
313 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
314 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
315 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
316 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
317 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
318 setters.put("TrapezoidFinSet:height", new DoubleSetter(
319 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
322 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
323 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
324 setters.put("EllipticalFinSet:height", new DoubleSetter(
325 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
327 // FreeformFinSet points handled as a special handler
330 setters.put("LaunchLug:radius", new DoubleSetter(
331 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
332 setters.put("LaunchLug:length", new DoubleSetter(
333 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
334 setters.put("LaunchLug:thickness", new DoubleSetter(
335 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
336 setters.put("LaunchLug:radialdirection", new DoubleSetter(
337 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
340 // InternalComponent - nothing
342 // StructuralComponent
343 setters.put("StructuralComponent:material", new MaterialSetter(
344 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
345 Material.Type.BULK));
348 setters.put("RingComponent:length", new DoubleSetter(
349 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
350 setters.put("RingComponent:radialposition", new DoubleSetter(
351 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
352 setters.put("RingComponent:radialdirection", new DoubleSetter(
353 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
356 // ThicknessRingComponent - radius on separate components due to differing automatics
357 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
358 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
361 setters.put("EngineBlock:outerradius", new DoubleSetter(
362 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
364 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
367 setters.put("TubeCoupler:outerradius", new DoubleSetter(
368 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
370 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
373 setters.put("InnerTube:outerradius", new DoubleSetter(
374 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
375 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
376 setters.put("InnerTube:clusterscale", new DoubleSetter(
377 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
378 setters.put("InnerTube:clusterrotation", new DoubleSetter(
379 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
382 // RadiusRingComponent
385 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
386 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
387 setters.put("Bulkhead:outerradius", new DoubleSetter(
388 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
390 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
393 setters.put("CenteringRing:innerradius", new DoubleSetter(
394 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
396 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
397 setters.put("CenteringRing:outerradius", new DoubleSetter(
398 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
400 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
404 setters.put("MassObject:packedlength", new DoubleSetter(
405 Reflection.findMethod(MassObject.class, "setLength", double.class)));
406 setters.put("MassObject:packedradius", new DoubleSetter(
407 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
408 setters.put("MassObject:radialposition", new DoubleSetter(
409 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
410 setters.put("MassObject:radialdirection", new DoubleSetter(
411 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
415 setters.put("MassComponent:mass", new DoubleSetter(
416 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
419 setters.put("ShockCord:cordlength", new DoubleSetter(
420 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
421 setters.put("ShockCord:material", new MaterialSetter(
422 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
423 Material.Type.LINE));
426 setters.put("RecoveryDevice:cd", new DoubleSetter(
427 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
429 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
430 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
431 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
432 RecoveryDevice.DeployEvent.class));
433 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
434 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
435 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
436 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
437 setters.put("RecoveryDevice:material", new MaterialSetter(
438 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
439 Material.Type.SURFACE));
442 setters.put("Parachute:diameter", new DoubleSetter(
443 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
444 setters.put("Parachute:linecount", new IntSetter(
445 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
446 setters.put("Parachute:linelength", new DoubleSetter(
447 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
448 setters.put("Parachute:linematerial", new MaterialSetter(
449 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
450 Material.Type.LINE));
453 setters.put("Streamer:striplength", new DoubleSetter(
454 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
455 setters.put("Streamer:stripwidth", new DoubleSetter(
456 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
459 // <motorconfiguration> handled by separate handler
460 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
461 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
462 ReferenceType.class));
463 setters.put("Rocket:customreference", new DoubleSetter(
464 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
465 setters.put("Rocket:designer", new StringSetter(
466 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
467 setters.put("Rocket:revision", new StringSetter(
468 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
473 * Search for a enum value that has the corresponding name as an XML value. The current
474 * conversion from enum name to XML value is to lowercase the name and strip out all
475 * underscore characters. This method returns a match to these criteria, or <code>null</code>
476 * if no such enum exists.
478 * @param <T> then enum type.
479 * @param name the XML value, null ok.
480 * @param enumClass the class of the enum.
481 * @return the found enum value, or <code>null</code>.
483 public static <T extends Enum<T>> Enum<T> findEnum(String name,
484 Class<? extends Enum<T>> enumClass) {
489 for (Enum<T> e : enumClass.getEnumConstants()) {
490 if (e.name().toLowerCase().replace("_", "").equals(name)) {
499 * Convert a string to a double including formatting specifications of the OpenRocket
500 * file format. This accepts all formatting that is valid for
501 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
503 * @param s the string to parse.
504 * @return the numerical value.
505 * @throws NumberFormatException the the string cannot be parsed.
507 public static double stringToDouble(String s) throws NumberFormatException {
509 throw new NumberFormatException("null string");
510 if (s.equalsIgnoreCase("NaN"))
512 if (s.equalsIgnoreCase("Inf"))
513 return Double.POSITIVE_INFINITY;
514 if (s.equalsIgnoreCase("-Inf"))
515 return Double.NEGATIVE_INFINITY;
516 return Double.parseDouble(s);
525 * The starting point of the handlers. Accepts a single <openrocket> element and hands
526 * the contents to be read by a OpenRocketContentsHandler.
528 class OpenRocketHandler extends ElementHandler {
529 private OpenRocketContentHandler handler = null;
532 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
533 * has not been read yet.
535 * @return the document read, or null.
537 public OpenRocketDocument getDocument() {
538 return handler.getDocument();
542 public ElementHandler openElement(String element, HashMap<String, String> attributes,
543 WarningSet warnings) {
545 // Check for unknown elements
546 if (!element.equals("openrocket")) {
547 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
551 // Check for first call
552 if (handler != null) {
553 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
558 // Check version number
559 String version = null;
560 String creator = attributes.remove("creator");
561 String docVersion = attributes.remove("version");
562 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
563 if (v.equals(docVersion)) {
568 if (version == null) {
569 String str = "Unsupported document version";
570 if (docVersion != null)
571 str += " " + docVersion;
572 if (creator != null && !creator.trim().equals(""))
573 str += " (written using '" + creator.trim() + "')";
574 str += ", attempting to read file anyway.";
578 handler = new OpenRocketContentHandler();
583 public void closeElement(String element, HashMap<String, String> attributes,
584 String content, WarningSet warnings) throws SAXException {
585 attributes.remove("version");
586 attributes.remove("creator");
587 super.closeElement(element, attributes, content, warnings);
595 * Handles the content of the <openrocket> tag.
597 class OpenRocketContentHandler extends ElementHandler {
598 private final OpenRocketDocument doc;
599 private final Rocket rocket;
601 private boolean rocketDefined = false;
602 private boolean simulationsDefined = false;
604 public OpenRocketContentHandler() {
605 this.rocket = new Rocket();
606 this.doc = new OpenRocketDocument(rocket);
610 public OpenRocketDocument getDocument() {
617 public ElementHandler openElement(String element, HashMap<String, String> attributes,
618 WarningSet warnings) {
620 if (element.equals("rocket")) {
623 .fromString("Multiple rocket designs within one document, "
624 + "ignoring later ones."));
627 rocketDefined = true;
628 return new ComponentParameterHandler(rocket);
631 if (element.equals("simulations")) {
632 if (simulationsDefined) {
634 .fromString("Multiple simulation definitions within one document, "
635 + "ignoring later ones."));
638 simulationsDefined = true;
639 return new SimulationsHandler(doc);
642 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
652 * A handler that creates components from the corresponding elements. The control of the
653 * contents is passed on to ComponentParameterHandler.
655 class ComponentHandler extends ElementHandler {
656 private final RocketComponent parent;
658 public ComponentHandler(RocketComponent parent) {
659 this.parent = parent;
663 public ElementHandler openElement(String element, HashMap<String, String> attributes,
664 WarningSet warnings) {
666 // Attempt to construct new component
667 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
669 if (constructor == null) {
670 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
676 c = constructor.newInstance();
677 } catch (InstantiationException e) {
678 throw new BugException("Error constructing component.", e);
679 } catch (IllegalAccessException e) {
680 throw new BugException("Error constructing component.", e);
681 } catch (InvocationTargetException e) {
682 throw Reflection.handleWrappedException(e);
687 return new ComponentParameterHandler(c);
693 * A handler that populates the parameters of a previously constructed rocket component.
694 * This uses the setters, or delegates the handling to another handler for specific
697 class ComponentParameterHandler extends ElementHandler {
698 private final RocketComponent component;
700 public ComponentParameterHandler(RocketComponent c) {
705 public ElementHandler openElement(String element, HashMap<String, String> attributes,
706 WarningSet warnings) {
708 // Check for specific elements that contain other elements
709 if (element.equals("subcomponents")) {
710 return new ComponentHandler(component);
712 if (element.equals("motormount")) {
713 if (!(component instanceof MotorMount)) {
714 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
717 return new MotorMountHandler((MotorMount) component);
719 if (element.equals("finpoints")) {
720 if (!(component instanceof FreeformFinSet)) {
721 warnings.add(Warning.fromString("Illegal component defined for fin points."));
724 return new FinSetPointHandler((FreeformFinSet) component);
726 if (element.equals("motorconfiguration")) {
727 if (!(component instanceof Rocket)) {
728 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
731 return new MotorConfigurationHandler((Rocket) component);
735 return PlainTextHandler.INSTANCE;
739 public void closeElement(String element, HashMap<String, String> attributes,
740 String content, WarningSet warnings) {
742 if (element.equals("subcomponents") || element.equals("motormount") ||
743 element.equals("finpoints") || element.equals("motorconfiguration")) {
747 // Search for the correct setter class
750 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
751 String setterKey = c.getSimpleName() + ":" + element;
752 Setter s = DocumentConfig.setters.get(setterKey);
755 s.set(component, content, attributes, warnings);
758 if (DocumentConfig.setters.containsKey(setterKey)) {
759 // Key exists but is null -> invalid parameter
765 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
766 + component.getComponentName() + ", ignoring."));
773 * A handler that reads the <point> specifications within the freeformfinset's
774 * <finpoints> elements.
776 class FinSetPointHandler extends ElementHandler {
777 private final FreeformFinSet finset;
778 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
780 public FinSetPointHandler(FreeformFinSet finset) {
781 this.finset = finset;
785 public ElementHandler openElement(String element, HashMap<String, String> attributes,
786 WarningSet warnings) {
787 return PlainTextHandler.INSTANCE;
792 public void closeElement(String element, HashMap<String, String> attributes,
793 String content, WarningSet warnings) throws SAXException {
795 String strx = attributes.remove("x");
796 String stry = attributes.remove("y");
797 if (strx == null || stry == null) {
798 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
802 double x = Double.parseDouble(strx);
803 double y = Double.parseDouble(stry);
804 coordinates.add(new Coordinate(x, y));
805 } catch (NumberFormatException e) {
806 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
810 super.closeElement(element, attributes, content, warnings);
814 public void endHandler(String element, HashMap<String, String> attributes,
815 String content, WarningSet warnings) {
817 finset.setPoints(coordinates.toArray(new Coordinate[0]));
818 } catch (IllegalFinPointException e) {
819 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
825 class MotorMountHandler extends ElementHandler {
826 private final MotorMount mount;
827 private MotorHandler motorHandler;
829 public MotorMountHandler(MotorMount mount) {
831 mount.setMotorMount(true);
835 public ElementHandler openElement(String element, HashMap<String, String> attributes,
836 WarningSet warnings) {
838 if (element.equals("motor")) {
839 motorHandler = new MotorHandler();
843 if (element.equals("ignitionevent") ||
844 element.equals("ignitiondelay") ||
845 element.equals("overhang")) {
846 return PlainTextHandler.INSTANCE;
849 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
856 public void closeElement(String element, HashMap<String, String> attributes,
857 String content, WarningSet warnings) throws SAXException {
859 if (element.equals("motor")) {
860 String id = attributes.get("configid");
861 if (id == null || id.equals("")) {
862 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
866 Motor motor = motorHandler.getMotor(warnings);
867 mount.setMotor(id, motor);
868 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
872 if (element.equals("ignitionevent")) {
873 MotorMount.IgnitionEvent event = null;
874 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
875 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
881 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
884 mount.setIgnitionEvent(event);
888 if (element.equals("ignitiondelay")) {
891 d = Double.parseDouble(content);
892 } catch (NumberFormatException nfe) {
893 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
896 mount.setIgnitionDelay(d);
900 if (element.equals("overhang")) {
903 d = Double.parseDouble(content);
904 } catch (NumberFormatException nfe) {
905 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
908 mount.setMotorOverhang(d);
912 super.closeElement(element, attributes, content, warnings);
919 class MotorConfigurationHandler extends ElementHandler {
920 private final Rocket rocket;
921 private String name = null;
922 private boolean inNameElement = false;
924 public MotorConfigurationHandler(Rocket rocket) {
925 this.rocket = rocket;
929 public ElementHandler openElement(String element, HashMap<String, String> attributes,
930 WarningSet warnings) {
932 if (inNameElement || !element.equals("name")) {
933 warnings.add(Warning.FILE_INVALID_PARAMETER);
936 inNameElement = true;
938 return PlainTextHandler.INSTANCE;
942 public void closeElement(String element, HashMap<String, String> attributes,
943 String content, WarningSet warnings) {
948 public void endHandler(String element, HashMap<String, String> attributes,
949 String content, WarningSet warnings) throws SAXException {
951 String configid = attributes.remove("configid");
952 if (configid == null || configid.equals("")) {
953 warnings.add(Warning.FILE_INVALID_PARAMETER);
957 if (!rocket.addMotorConfigurationID(configid)) {
958 warnings.add("Duplicate motor configuration ID used.");
962 if (name != null && name.trim().length() > 0) {
963 rocket.setMotorConfigurationName(configid, name);
966 if ("true".equals(attributes.remove("default"))) {
967 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
970 super.closeElement(element, attributes, content, warnings);
975 class MotorHandler extends ElementHandler {
976 private Motor.Type type = null;
977 private String manufacturer = null;
978 private String designation = null;
979 private String digest = null;
980 private double diameter = Double.NaN;
981 private double length = Double.NaN;
982 private double delay = Double.NaN;
985 public ElementHandler openElement(String element, HashMap<String, String> attributes,
986 WarningSet warnings) {
987 return PlainTextHandler.INSTANCE;
992 * Return the motor to use, or null.
994 public Motor getMotor(WarningSet warnings) {
995 if (designation == null) {
996 warnings.add(Warning.fromString("No motor specified, ignoring."));
1000 List<? extends Motor> motors = Application.getMotorSetDatabase().findMotors(type, manufacturer,
1001 designation, diameter, length);
1004 if (motors.size() == 0) {
1005 Warning.MissingMotor mmw = new Warning.MissingMotor();
1006 mmw.setDesignation(designation);
1007 mmw.setDigest(digest);
1008 mmw.setDiameter(diameter);
1009 mmw.setLength(length);
1010 mmw.setManufacturer(manufacturer);
1017 if (motors.size() == 1) {
1018 Motor m = motors.get(0);
1019 if (digest != null && !digest.equals(m.getDigest())) {
1020 String str = "Motor with designation '" + designation + "'";
1021 if (manufacturer != null)
1022 str += " for manufacturer '" + manufacturer + "'";
1023 str += " has differing thrust curve than the original.";
1029 // Multiple motors, check digest for which one to use
1030 if (digest != null) {
1032 // Check for motor with correct digest
1033 for (Motor m : motors) {
1034 if (digest.equals(m.getDigest())) {
1038 String str = "Motor with designation '" + designation + "'";
1039 if (manufacturer != null)
1040 str += " for manufacturer '" + manufacturer + "'";
1041 str += " has differing thrust curve than the original.";
1046 // No digest, check for preferred digest (OpenRocket <= 1.1.0)
1047 // TODO: MEDIUM: This should only be done for document versions 1.1 and below
1048 for (Motor m : motors) {
1049 if (PreferredMotorDigests.DIGESTS.contains(m.getDigest())) {
1054 String str = "Multiple motors with designation '" + designation + "'";
1055 if (manufacturer != null)
1056 str += " for manufacturer '" + manufacturer + "'";
1057 str += " found, one chosen arbitrarily.";
1061 return motors.get(0);
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")) {
1109 digest = content.trim();
1111 } else if (element.equals("diameter")) {
1114 diameter = Double.NaN;
1116 diameter = Double.parseDouble(content.trim());
1117 } catch (NumberFormatException e) {
1120 if (Double.isNaN(diameter)) {
1121 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1124 } else if (element.equals("length")) {
1127 length = Double.NaN;
1129 length = Double.parseDouble(content.trim());
1130 } catch (NumberFormatException ignore) {
1133 if (Double.isNaN(length)) {
1134 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1137 } else if (element.equals("delay")) {
1141 if (content.equals("none")) {
1142 delay = Motor.PLUGGED;
1145 delay = Double.parseDouble(content.trim());
1146 } catch (NumberFormatException ignore) {
1149 if (Double.isNaN(delay)) {
1150 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1156 super.closeElement(element, attributes, content, warnings);
1164 class SimulationsHandler extends ElementHandler {
1165 private final OpenRocketDocument doc;
1166 private SingleSimulationHandler handler;
1168 public SimulationsHandler(OpenRocketDocument doc) {
1173 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1174 WarningSet warnings) {
1176 if (!element.equals("simulation")) {
1177 warnings.add("Unknown element '" + element + "', ignoring.");
1181 handler = new SingleSimulationHandler(doc);
1186 public void closeElement(String element, HashMap<String, String> attributes,
1187 String content, WarningSet warnings) throws SAXException {
1188 attributes.remove("status");
1189 super.closeElement(element, attributes, content, warnings);
1195 class SingleSimulationHandler extends ElementHandler {
1197 private final OpenRocketDocument doc;
1199 private String name;
1201 private SimulationConditionsHandler conditionHandler;
1202 private FlightDataHandler dataHandler;
1204 private final List<String> listeners = new ArrayList<String>();
1206 public SingleSimulationHandler(OpenRocketDocument doc) {
1213 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1214 WarningSet warnings) {
1216 if (element.equals("name") || element.equals("simulator") ||
1217 element.equals("calculator") || element.equals("listener")) {
1218 return PlainTextHandler.INSTANCE;
1219 } else if (element.equals("conditions")) {
1220 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1221 return conditionHandler;
1222 } else if (element.equals("flightdata")) {
1223 dataHandler = new FlightDataHandler();
1226 warnings.add("Unknown element '" + element + "', ignoring.");
1232 public void closeElement(String element, HashMap<String, String> attributes,
1233 String content, WarningSet warnings) {
1235 if (element.equals("name")) {
1237 } else if (element.equals("simulator")) {
1238 if (!content.trim().equals("RK4Simulator")) {
1239 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1241 } else if (element.equals("calculator")) {
1242 if (!content.trim().equals("BarrowmanCalculator")) {
1243 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1245 } else if (element.equals("listener") && content.trim().length() > 0) {
1246 listeners.add(content.trim());
1252 public void endHandler(String element, HashMap<String, String> attributes,
1253 String content, WarningSet warnings) {
1255 String s = attributes.get("status");
1256 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1257 if (status == null) {
1258 warnings.add("Simulation status unknown, assuming outdated.");
1259 status = Simulation.Status.OUTDATED;
1262 SimulationOptions conditions;
1263 if (conditionHandler != null) {
1264 conditions = conditionHandler.getConditions();
1266 warnings.add("Simulation conditions not defined, using defaults.");
1267 conditions = new SimulationOptions(doc.getRocket());
1271 name = "Simulation";
1274 if (dataHandler == null)
1277 data = dataHandler.getFlightData();
1279 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1280 conditions, listeners, data);
1282 doc.addSimulation(simulation);
1288 class SimulationConditionsHandler extends ElementHandler {
1289 private SimulationOptions conditions;
1290 private AtmosphereHandler atmosphereHandler;
1292 public SimulationConditionsHandler(Rocket rocket) {
1293 conditions = new SimulationOptions(rocket);
1294 // Set up default loading settings (which may differ from the new defaults)
1295 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1298 public SimulationOptions getConditions() {
1303 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1304 WarningSet warnings) {
1305 if (element.equals("atmosphere")) {
1306 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1307 return atmosphereHandler;
1309 return PlainTextHandler.INSTANCE;
1313 public void closeElement(String element, HashMap<String, String> attributes,
1314 String content, WarningSet warnings) {
1316 double d = Double.NaN;
1318 d = Double.parseDouble(content);
1319 } catch (NumberFormatException ignore) {
1323 if (element.equals("configid")) {
1324 if (content.equals("")) {
1325 conditions.setMotorConfigurationID(null);
1327 conditions.setMotorConfigurationID(content);
1329 } else if (element.equals("launchrodlength")) {
1330 if (Double.isNaN(d)) {
1331 warnings.add("Illegal launch rod length defined, ignoring.");
1333 conditions.setLaunchRodLength(d);
1335 } else if (element.equals("launchrodangle")) {
1336 if (Double.isNaN(d)) {
1337 warnings.add("Illegal launch rod angle defined, ignoring.");
1339 conditions.setLaunchRodAngle(d * Math.PI / 180);
1341 } else if (element.equals("launchroddirection")) {
1342 if (Double.isNaN(d)) {
1343 warnings.add("Illegal launch rod direction defined, ignoring.");
1345 conditions.setLaunchRodDirection(d * Math.PI / 180);
1347 } else if (element.equals("windaverage")) {
1348 if (Double.isNaN(d)) {
1349 warnings.add("Illegal average windspeed defined, ignoring.");
1351 conditions.setWindSpeedAverage(d);
1353 } else if (element.equals("windturbulence")) {
1354 if (Double.isNaN(d)) {
1355 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1357 conditions.setWindTurbulenceIntensity(d);
1359 } else if (element.equals("launchaltitude")) {
1360 if (Double.isNaN(d)) {
1361 warnings.add("Illegal launch altitude defined, ignoring.");
1363 conditions.setLaunchAltitude(d);
1365 } else if (element.equals("launchlatitude")) {
1366 if (Double.isNaN(d)) {
1367 warnings.add("Illegal launch latitude defined, ignoring.");
1369 conditions.setLaunchLatitude(d);
1371 } else if (element.equals("launchlongitude")) {
1372 if (Double.isNaN(d)) {
1373 warnings.add("Illegal launch longitude.");
1375 conditions.setLaunchLongitude(d);
1377 } else if (element.equals("geodeticmethod")) {
1378 GeodeticComputationStrategy gcs =
1379 (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1381 conditions.setGeodeticComputation(gcs);
1383 warnings.add("Unknown geodetic computation method '" + content + "'");
1385 } else if (element.equals("atmosphere")) {
1386 atmosphereHandler.storeSettings(conditions, warnings);
1387 } else if (element.equals("timestep")) {
1388 if (Double.isNaN(d)) {
1389 warnings.add("Illegal time step defined, ignoring.");
1391 conditions.setTimeStep(d);
1398 class AtmosphereHandler extends ElementHandler {
1399 private final String model;
1400 private double temperature = Double.NaN;
1401 private double pressure = Double.NaN;
1403 public AtmosphereHandler(String model) {
1408 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1409 WarningSet warnings) {
1410 return PlainTextHandler.INSTANCE;
1414 public void closeElement(String element, HashMap<String, String> attributes,
1415 String content, WarningSet warnings) throws SAXException {
1417 double d = Double.NaN;
1419 d = Double.parseDouble(content);
1420 } catch (NumberFormatException ignore) {
1423 if (element.equals("basetemperature")) {
1424 if (Double.isNaN(d)) {
1425 warnings.add("Illegal base temperature specified, ignoring.");
1428 } else if (element.equals("basepressure")) {
1429 if (Double.isNaN(d)) {
1430 warnings.add("Illegal base pressure specified, ignoring.");
1434 super.closeElement(element, attributes, content, warnings);
1439 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1440 if (!Double.isNaN(pressure)) {
1441 cond.setLaunchPressure(pressure);
1443 if (!Double.isNaN(temperature)) {
1444 cond.setLaunchTemperature(temperature);
1447 if ("isa".equals(model)) {
1448 cond.setISAAtmosphere(true);
1449 } else if ("extendedisa".equals(model)) {
1450 cond.setISAAtmosphere(false);
1452 cond.setISAAtmosphere(true);
1453 warnings.add("Unknown atmospheric model, using ISA.");
1460 class FlightDataHandler extends ElementHandler {
1462 private FlightDataBranchHandler dataHandler;
1463 private WarningSet warningSet = new WarningSet();
1464 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1466 private FlightData data;
1468 public FlightData getFlightData() {
1473 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1474 WarningSet warnings) {
1476 if (element.equals("warning")) {
1477 return PlainTextHandler.INSTANCE;
1479 if (element.equals("databranch")) {
1480 if (attributes.get("name") == null || attributes.get("types") == null) {
1481 warnings.add("Illegal flight data definition, ignoring.");
1484 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1485 attributes.get("types"));
1489 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1495 public void closeElement(String element, HashMap<String, String> attributes,
1496 String content, WarningSet warnings) {
1498 if (element.equals("databranch")) {
1499 FlightDataBranch branch = dataHandler.getBranch();
1500 if (branch.getLength() > 0) {
1501 branches.add(branch);
1503 } else if (element.equals("warning")) {
1504 warningSet.add(Warning.fromString(content));
1510 public void endHandler(String element, HashMap<String, String> attributes,
1511 String content, WarningSet warnings) {
1513 if (branches.size() > 0) {
1514 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1516 double maxAltitude = Double.NaN;
1517 double maxVelocity = Double.NaN;
1518 double maxAcceleration = Double.NaN;
1519 double maxMach = Double.NaN;
1520 double timeToApogee = Double.NaN;
1521 double flightTime = Double.NaN;
1522 double groundHitVelocity = Double.NaN;
1523 double launchRodVelocity = Double.NaN;
1524 double deploymentVelocity = Double.NaN;
1527 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1528 } catch (NumberFormatException ignore) {
1531 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1532 } catch (NumberFormatException ignore) {
1535 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1536 } catch (NumberFormatException ignore) {
1539 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1540 } catch (NumberFormatException ignore) {
1543 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1544 } catch (NumberFormatException ignore) {
1547 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1548 } catch (NumberFormatException ignore) {
1552 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1553 } catch (NumberFormatException ignore) {
1556 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1557 } catch (NumberFormatException ignore) {
1560 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1561 } catch (NumberFormatException ignore) {
1564 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1565 timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1568 data.getWarningSet().addAll(warningSet);
1576 class FlightDataBranchHandler extends ElementHandler {
1577 private final FlightDataType[] types;
1578 private final FlightDataBranch branch;
1580 public FlightDataBranchHandler(String name, String typeList) {
1581 String[] split = typeList.split(",");
1582 types = new FlightDataType[split.length];
1583 for (int i = 0; i < split.length; i++) {
1584 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1587 // TODO: LOW: May throw an IllegalArgumentException
1588 branch = new FlightDataBranch(name, types);
1591 public FlightDataBranch getBranch() {
1597 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1598 WarningSet warnings) {
1600 if (element.equals("datapoint"))
1601 return PlainTextHandler.INSTANCE;
1602 if (element.equals("event"))
1603 return PlainTextHandler.INSTANCE;
1605 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1611 public void closeElement(String element, HashMap<String, String> attributes,
1612 String content, WarningSet warnings) {
1614 if (element.equals("event")) {
1616 FlightEvent.Type type;
1619 time = DocumentConfig.stringToDouble(attributes.get("time"));
1620 } catch (NumberFormatException e) {
1621 warnings.add("Illegal event specification, ignoring.");
1625 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1627 warnings.add("Illegal event specification, ignoring.");
1631 branch.addEvent(new FlightEvent(type, time));
1635 if (!element.equals("datapoint")) {
1636 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1640 // element == "datapoint"
1643 // Check line format
1644 String[] split = content.split(",");
1645 if (split.length != types.length) {
1646 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1650 // Parse the doubles
1651 double[] values = new double[split.length];
1652 for (int i = 0; i < values.length; i++) {
1654 values[i] = DocumentConfig.stringToDouble(split[i]);
1655 } catch (NumberFormatException e) {
1656 warnings.add("Data point format error, ignoring point.");
1661 // Add point to branch
1663 for (int i = 0; i < types.length; i++) {
1664 branch.setValue(types[i], values[i]);
1673 ///////////////// Setters implementation
1679 * Set the specified value to the given component.
1681 * @param component the component to which to set.
1682 * @param value the value within the element.
1683 * @param attributes attributes for the element.
1684 * @param warnings the warning set to use.
1686 public void set(RocketComponent component, String value,
1687 HashMap<String, String> attributes, WarningSet warnings);
1691 //// StringSetter - sets the value to the contained String
1692 class StringSetter implements Setter {
1693 private final Reflection.Method setMethod;
1695 public StringSetter(Reflection.Method set) {
1700 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1701 WarningSet warnings) {
1702 setMethod.invoke(c, s);
1706 //// IntSetter - set an integer value
1707 class IntSetter implements Setter {
1708 private final Reflection.Method setMethod;
1710 public IntSetter(Reflection.Method set) {
1715 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1716 WarningSet warnings) {
1718 int n = Integer.parseInt(s);
1719 setMethod.invoke(c, n);
1720 } catch (NumberFormatException e) {
1721 warnings.add(Warning.FILE_INVALID_PARAMETER);
1727 //// BooleanSetter - set a boolean value
1728 class BooleanSetter implements Setter {
1729 private final Reflection.Method setMethod;
1731 public BooleanSetter(Reflection.Method set) {
1736 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1737 WarningSet warnings) {
1740 if (s.equalsIgnoreCase("true")) {
1741 setMethod.invoke(c, true);
1742 } else if (s.equalsIgnoreCase("false")) {
1743 setMethod.invoke(c, false);
1745 warnings.add(Warning.FILE_INVALID_PARAMETER);
1752 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1753 //// calls a setXXX(boolean) method.
1754 class DoubleSetter implements Setter {
1755 private final Reflection.Method setMethod;
1756 private final String specialString;
1757 private final Reflection.Method specialMethod;
1758 private final double multiplier;
1761 * Set only the double value.
1762 * @param set set method for the double value.
1764 public DoubleSetter(Reflection.Method set) {
1765 this.setMethod = set;
1766 this.specialString = null;
1767 this.specialMethod = null;
1768 this.multiplier = 1.0;
1772 * Multiply with the given multiplier and set the double value.
1773 * @param set set method for the double value.
1774 * @param mul multiplier.
1776 public DoubleSetter(Reflection.Method set, double mul) {
1777 this.setMethod = set;
1778 this.specialString = null;
1779 this.specialMethod = null;
1780 this.multiplier = mul;
1784 * Set the double value, or if the value equals the special string, use the
1785 * special setter and set it to true.
1787 * @param set double setter.
1788 * @param special special string
1789 * @param specialMethod boolean setter.
1791 public DoubleSetter(Reflection.Method set, String special,
1792 Reflection.Method specialMethod) {
1793 this.setMethod = set;
1794 this.specialString = special;
1795 this.specialMethod = specialMethod;
1796 this.multiplier = 1.0;
1801 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1802 WarningSet warnings) {
1806 // Check for special case
1807 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1808 specialMethod.invoke(c, true);
1814 double d = Double.parseDouble(s);
1815 setMethod.invoke(c, d * multiplier);
1816 } catch (NumberFormatException e) {
1817 warnings.add(Warning.FILE_INVALID_PARAMETER);
1823 class OverrideSetter implements Setter {
1824 private final Reflection.Method setMethod;
1825 private final Reflection.Method enabledMethod;
1827 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1828 this.setMethod = set;
1829 this.enabledMethod = enabledMethod;
1833 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1834 WarningSet warnings) {
1837 double d = Double.parseDouble(s);
1838 setMethod.invoke(c, d);
1839 enabledMethod.invoke(c, true);
1840 } catch (NumberFormatException e) {
1841 warnings.add(Warning.FILE_INVALID_PARAMETER);
1846 //// EnumSetter - sets a generic enum type
1847 class EnumSetter<T extends Enum<T>> implements Setter {
1848 private final Reflection.Method setter;
1849 private final Class<T> enumClass;
1851 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1853 this.enumClass = enumClass;
1857 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1858 WarningSet warnings) {
1860 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1861 if (setEnum == null) {
1862 warnings.add(Warning.FILE_INVALID_PARAMETER);
1866 setter.invoke(c, setEnum);
1871 //// ColorSetter - sets a Color value
1872 class ColorSetter implements Setter {
1873 private final Reflection.Method setMethod;
1875 public ColorSetter(Reflection.Method set) {
1880 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1881 WarningSet warnings) {
1883 String red = attributes.get("red");
1884 String green = attributes.get("green");
1885 String blue = attributes.get("blue");
1887 if (red == null || green == null || blue == null) {
1888 warnings.add(Warning.FILE_INVALID_PARAMETER);
1894 r = Integer.parseInt(red);
1895 g = Integer.parseInt(green);
1896 b = Integer.parseInt(blue);
1897 } catch (NumberFormatException e) {
1898 warnings.add(Warning.FILE_INVALID_PARAMETER);
1902 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1903 warnings.add(Warning.FILE_INVALID_PARAMETER);
1907 Color color = new Color(r, g, b);
1908 setMethod.invoke(c, color);
1910 if (!s.trim().equals("")) {
1911 warnings.add(Warning.FILE_INVALID_PARAMETER);
1918 class MaterialSetter implements Setter {
1919 private final Reflection.Method setMethod;
1920 private final Material.Type type;
1922 public MaterialSetter(Reflection.Method set, Material.Type type) {
1923 this.setMethod = set;
1928 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1929 WarningSet warnings) {
1935 if (name.equals("")) {
1936 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1943 str = attributes.remove("density");
1945 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1949 density = Double.parseDouble(str);
1950 } catch (NumberFormatException e) {
1951 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1956 // double thickness = 0;
1957 // str = attributes.remove("thickness");
1960 // thickness = Double.parseDouble(str);
1961 // } catch (NumberFormatException e){
1962 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1966 // Check type if specified
1967 str = attributes.remove("type");
1968 if (str != null && !type.name().toLowerCase().equals(str)) {
1969 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1973 mat = Databases.findMaterial(type, name, density, false);
1975 setMethod.invoke(c, mat);
1982 class PositionSetter implements Setter {
1985 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1986 WarningSet warnings) {
1988 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1989 RocketComponent.Position.class);
1991 warnings.add(Warning.FILE_INVALID_PARAMETER);
1997 pos = Double.parseDouble(value);
1998 } catch (NumberFormatException e) {
1999 warnings.add(Warning.FILE_INVALID_PARAMETER);
2003 if (c instanceof FinSet) {
2004 ((FinSet) c).setRelativePosition(type);
2005 c.setPositionValue(pos);
2006 } else if (c instanceof LaunchLug) {
2007 ((LaunchLug) c).setRelativePosition(type);
2008 c.setPositionValue(pos);
2009 } else if (c instanceof InternalComponent) {
2010 ((InternalComponent) c).setRelativePosition(type);
2011 c.setPositionValue(pos);
2013 warnings.add(Warning.FILE_INVALID_PARAMETER);
2020 class FinTabPositionSetter extends DoubleSetter {
2022 public FinTabPositionSetter() {
2023 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2027 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2028 WarningSet warnings) {
2030 if (!(c instanceof FinSet)) {
2031 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2034 String relative = attributes.get("relativeto");
2035 FinSet.TabRelativePosition position =
2036 (TabRelativePosition) DocumentConfig.findEnum(relative,
2037 FinSet.TabRelativePosition.class);
2039 if (position != null) {
2041 ((FinSet) c).setTabRelativePosition(position);
2044 if (relative == null) {
2045 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2047 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2051 super.set(c, s, attributes, warnings);
2058 class ClusterConfigurationSetter implements Setter {
2061 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2062 WarningSet warnings) {
2064 if (!(component instanceof Clusterable)) {
2065 warnings.add("Illegal component defined as cluster.");
2069 ClusterConfiguration config = null;
2070 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2071 if (c.getXMLName().equals(value)) {
2077 if (config == null) {
2078 warnings.add("Illegal cluster configuration specified.");
2082 ((Clusterable) component).setClusterConfiguration(config);