1 package net.sf.openrocket.file.openrocket;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.lang.reflect.Constructor;
7 import java.lang.reflect.InvocationTargetException;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.List;
12 import net.sf.openrocket.aerodynamics.Warning;
13 import net.sf.openrocket.aerodynamics.WarningSet;
14 import net.sf.openrocket.database.Databases;
15 import net.sf.openrocket.document.OpenRocketDocument;
16 import net.sf.openrocket.document.Simulation;
17 import net.sf.openrocket.document.Simulation.Status;
18 import net.sf.openrocket.document.StorageOptions;
19 import net.sf.openrocket.file.RocketLoadException;
20 import net.sf.openrocket.file.RocketLoader;
21 import net.sf.openrocket.file.simplesax.ElementHandler;
22 import net.sf.openrocket.file.simplesax.PlainTextHandler;
23 import net.sf.openrocket.file.simplesax.SimpleSAX;
24 import net.sf.openrocket.logging.LogHelper;
25 import net.sf.openrocket.material.Material;
26 import net.sf.openrocket.motor.Motor;
27 import net.sf.openrocket.motor.MotorDigest;
28 import net.sf.openrocket.motor.ThrustCurveMotor;
29 import net.sf.openrocket.rocketcomponent.BodyComponent;
30 import net.sf.openrocket.rocketcomponent.BodyTube;
31 import net.sf.openrocket.rocketcomponent.Bulkhead;
32 import net.sf.openrocket.rocketcomponent.CenteringRing;
33 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
34 import net.sf.openrocket.rocketcomponent.Clusterable;
35 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
36 import net.sf.openrocket.rocketcomponent.EngineBlock;
37 import net.sf.openrocket.rocketcomponent.ExternalComponent;
38 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
39 import net.sf.openrocket.rocketcomponent.FinSet;
40 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
41 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
42 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
43 import net.sf.openrocket.rocketcomponent.InnerTube;
44 import net.sf.openrocket.rocketcomponent.InternalComponent;
45 import net.sf.openrocket.rocketcomponent.LaunchLug;
46 import net.sf.openrocket.rocketcomponent.MassComponent;
47 import net.sf.openrocket.rocketcomponent.MassObject;
48 import net.sf.openrocket.rocketcomponent.MotorMount;
49 import net.sf.openrocket.rocketcomponent.NoseCone;
50 import net.sf.openrocket.rocketcomponent.Parachute;
51 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
52 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
53 import net.sf.openrocket.rocketcomponent.ReferenceType;
54 import net.sf.openrocket.rocketcomponent.RingComponent;
55 import net.sf.openrocket.rocketcomponent.Rocket;
56 import net.sf.openrocket.rocketcomponent.RocketComponent;
57 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
58 import net.sf.openrocket.rocketcomponent.ShockCord;
59 import net.sf.openrocket.rocketcomponent.Stage;
60 import net.sf.openrocket.rocketcomponent.Streamer;
61 import net.sf.openrocket.rocketcomponent.StructuralComponent;
62 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
63 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
64 import net.sf.openrocket.rocketcomponent.Transition;
65 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
66 import net.sf.openrocket.rocketcomponent.TubeCoupler;
67 import net.sf.openrocket.simulation.FlightData;
68 import net.sf.openrocket.simulation.FlightDataBranch;
69 import net.sf.openrocket.simulation.FlightDataType;
70 import net.sf.openrocket.simulation.FlightEvent;
71 import net.sf.openrocket.simulation.FlightEvent.Type;
72 import net.sf.openrocket.simulation.SimulationOptions;
73 import net.sf.openrocket.startup.Application;
74 import net.sf.openrocket.unit.UnitGroup;
75 import net.sf.openrocket.util.BugException;
76 import net.sf.openrocket.util.Coordinate;
77 import net.sf.openrocket.util.GeodeticComputationStrategy;
78 import net.sf.openrocket.util.LineStyle;
79 import net.sf.openrocket.util.Reflection;
81 import org.xml.sax.InputSource;
82 import org.xml.sax.SAXException;
86 * Class that loads a rocket definition from an OpenRocket rocket file.
88 * This class uses SAX to read the XML file format. The
89 * {@link #loadFromStream(InputStream)} method simply sets the system up and
90 * starts the parsing, while the actual logic is in the private inner class
91 * <code>OpenRocketHandler</code>.
93 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
95 public class OpenRocketLoader extends RocketLoader {
96 private static final LogHelper log = Application.getLogger();
100 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
102 log.info("Loading .ork file");
104 InputSource xmlSource = new InputSource(source);
105 OpenRocketHandler handler = new OpenRocketHandler();
109 SimpleSAX.readXML(xmlSource, handler, warnings);
110 } catch (SAXException e) {
111 log.warn("Malformed XML in input");
112 throw new RocketLoadException("Malformed XML in input.", e);
116 OpenRocketDocument doc = handler.getDocument();
117 doc.getDefaultConfiguration().setAllStages();
119 // Deduce suitable time skip
120 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
121 for (Simulation s : doc.getSimulations()) {
122 if (s.getStatus() == Simulation.Status.EXTERNAL ||
123 s.getStatus() == Simulation.Status.NOT_SIMULATED)
125 if (s.getSimulatedData() == null)
127 if (s.getSimulatedData().getBranchCount() == 0)
129 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
132 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
136 double previousTime = Double.NaN;
137 for (double time : list) {
138 if (time - previousTime < timeSkip)
139 timeSkip = time - previousTime;
144 timeSkip = Math.rint(timeSkip * 100) / 100;
146 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
147 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
148 doc.getDefaultStorageOptions().setExplicitlySet(false);
151 log.info("Loading done");
159 class DocumentConfig {
161 /* Remember to update OpenRocketSaver as well! */
162 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1", "1.2", "1.3" };
165 //////// Component constructors
166 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
169 // External components
170 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
171 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
172 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
173 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
174 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
175 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
176 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
178 // Internal components
179 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
180 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
181 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
182 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
183 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
185 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
186 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
187 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
188 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
191 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
193 } catch (NoSuchMethodException e) {
194 throw new BugException(
195 "Error in constructing the 'constructors' HashMap.");
200 //////// Parameter setters
202 * The keys are of the form Class:param, where Class is the class name and param
203 * the element name. Setters are searched for in descending class order.
204 * A setter of null means setting the parameter is not allowed.
206 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
209 setters.put("RocketComponent:name", new StringSetter(
210 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
211 setters.put("RocketComponent:color", new ColorSetter(
212 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
213 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
214 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
216 setters.put("RocketComponent:position", new PositionSetter());
217 setters.put("RocketComponent:overridemass", new OverrideSetter(
218 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
219 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
220 setters.put("RocketComponent:overridecg", new OverrideSetter(
221 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
222 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
223 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
224 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
225 setters.put("RocketComponent:comment", new StringSetter(
226 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
229 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
230 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
232 setters.put("ExternalComponent:material", new MaterialSetter(
233 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
234 Material.Type.BULK));
237 setters.put("BodyComponent:length", new DoubleSetter(
238 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
240 // SymmetricComponent
241 setters.put("SymmetricComponent:thickness", new DoubleSetter(
242 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
244 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
247 setters.put("BodyTube:radius", new DoubleSetter(
248 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
250 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
253 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
254 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
255 Transition.Shape.class));
256 setters.put("Transition:shapeclipped", new BooleanSetter(
257 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
258 setters.put("Transition:shapeparameter", new DoubleSetter(
259 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
261 setters.put("Transition:foreradius", new DoubleSetter(
262 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
264 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
265 setters.put("Transition:aftradius", new DoubleSetter(
266 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
268 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
270 setters.put("Transition:foreshoulderradius", new DoubleSetter(
271 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
272 setters.put("Transition:foreshoulderlength", new DoubleSetter(
273 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
274 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
275 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
276 setters.put("Transition:foreshouldercapped", new BooleanSetter(
277 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
279 setters.put("Transition:aftshoulderradius", new DoubleSetter(
280 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
281 setters.put("Transition:aftshoulderlength", new DoubleSetter(
282 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
283 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
284 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
285 setters.put("Transition:aftshouldercapped", new BooleanSetter(
286 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
288 // NoseCone - disable disallowed elements
289 setters.put("NoseCone:foreradius", null);
290 setters.put("NoseCone:foreshoulderradius", null);
291 setters.put("NoseCone:foreshoulderlength", null);
292 setters.put("NoseCone:foreshoulderthickness", null);
293 setters.put("NoseCone:foreshouldercapped", null);
296 setters.put("FinSet:fincount", new IntSetter(
297 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
298 setters.put("FinSet:rotation", new DoubleSetter(
299 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
300 setters.put("FinSet:thickness", new DoubleSetter(
301 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
302 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
303 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
304 FinSet.CrossSection.class));
305 setters.put("FinSet:cant", new DoubleSetter(
306 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
307 setters.put("FinSet:tabheight", new DoubleSetter(
308 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
309 setters.put("FinSet:tablength", new DoubleSetter(
310 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
311 setters.put("FinSet:tabposition", new FinTabPositionSetter());
314 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
315 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
316 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
317 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
318 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
319 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
320 setters.put("TrapezoidFinSet:height", new DoubleSetter(
321 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
324 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
325 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
326 setters.put("EllipticalFinSet:height", new DoubleSetter(
327 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
329 // FreeformFinSet points handled as a special handler
332 setters.put("LaunchLug:radius", new DoubleSetter(
333 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
334 setters.put("LaunchLug:length", new DoubleSetter(
335 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
336 setters.put("LaunchLug:thickness", new DoubleSetter(
337 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
338 setters.put("LaunchLug:radialdirection", new DoubleSetter(
339 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
342 // InternalComponent - nothing
344 // StructuralComponent
345 setters.put("StructuralComponent:material", new MaterialSetter(
346 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
347 Material.Type.BULK));
350 setters.put("RingComponent:length", new DoubleSetter(
351 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
352 setters.put("RingComponent:radialposition", new DoubleSetter(
353 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
354 setters.put("RingComponent:radialdirection", new DoubleSetter(
355 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
358 // ThicknessRingComponent - radius on separate components due to differing automatics
359 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
360 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
363 setters.put("EngineBlock:outerradius", new DoubleSetter(
364 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
366 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
369 setters.put("TubeCoupler:outerradius", new DoubleSetter(
370 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
372 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
375 setters.put("InnerTube:outerradius", new DoubleSetter(
376 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
377 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
378 setters.put("InnerTube:clusterscale", new DoubleSetter(
379 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
380 setters.put("InnerTube:clusterrotation", new DoubleSetter(
381 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
384 // RadiusRingComponent
387 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
388 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
389 setters.put("Bulkhead:outerradius", new DoubleSetter(
390 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
392 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
395 setters.put("CenteringRing:innerradius", new DoubleSetter(
396 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
398 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
399 setters.put("CenteringRing:outerradius", new DoubleSetter(
400 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
402 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
406 setters.put("MassObject:packedlength", new DoubleSetter(
407 Reflection.findMethod(MassObject.class, "setLength", double.class)));
408 setters.put("MassObject:packedradius", new DoubleSetter(
409 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
410 setters.put("MassObject:radialposition", new DoubleSetter(
411 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
412 setters.put("MassObject:radialdirection", new DoubleSetter(
413 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
417 setters.put("MassComponent:mass", new DoubleSetter(
418 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
421 setters.put("ShockCord:cordlength", new DoubleSetter(
422 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
423 setters.put("ShockCord:material", new MaterialSetter(
424 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
425 Material.Type.LINE));
428 setters.put("RecoveryDevice:cd", new DoubleSetter(
429 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
431 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
432 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
433 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
434 RecoveryDevice.DeployEvent.class));
435 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
436 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
437 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
438 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
439 setters.put("RecoveryDevice:material", new MaterialSetter(
440 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
441 Material.Type.SURFACE));
444 setters.put("Parachute:diameter", new DoubleSetter(
445 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
446 setters.put("Parachute:linecount", new IntSetter(
447 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
448 setters.put("Parachute:linelength", new DoubleSetter(
449 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
450 setters.put("Parachute:linematerial", new MaterialSetter(
451 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
452 Material.Type.LINE));
455 setters.put("Streamer:striplength", new DoubleSetter(
456 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
457 setters.put("Streamer:stripwidth", new DoubleSetter(
458 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
461 // <motorconfiguration> handled by separate handler
462 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
463 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
464 ReferenceType.class));
465 setters.put("Rocket:customreference", new DoubleSetter(
466 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
467 setters.put("Rocket:designer", new StringSetter(
468 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
469 setters.put("Rocket:revision", new StringSetter(
470 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
475 * Search for a enum value that has the corresponding name as an XML value. The current
476 * conversion from enum name to XML value is to lowercase the name and strip out all
477 * underscore characters. This method returns a match to these criteria, or <code>null</code>
478 * if no such enum exists.
480 * @param <T> then enum type.
481 * @param name the XML value, null ok.
482 * @param enumClass the class of the enum.
483 * @return the found enum value, or <code>null</code>.
485 public static <T extends Enum<T>> Enum<T> findEnum(String name,
486 Class<? extends Enum<T>> enumClass) {
491 for (Enum<T> e : enumClass.getEnumConstants()) {
492 if (e.name().toLowerCase().replace("_", "").equals(name)) {
501 * Convert a string to a double including formatting specifications of the OpenRocket
502 * file format. This accepts all formatting that is valid for
503 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
505 * @param s the string to parse.
506 * @return the numerical value.
507 * @throws NumberFormatException the the string cannot be parsed.
509 public static double stringToDouble(String s) throws NumberFormatException {
511 throw new NumberFormatException("null string");
512 if (s.equalsIgnoreCase("NaN"))
514 if (s.equalsIgnoreCase("Inf"))
515 return Double.POSITIVE_INFINITY;
516 if (s.equalsIgnoreCase("-Inf"))
517 return Double.NEGATIVE_INFINITY;
518 return Double.parseDouble(s);
527 * The starting point of the handlers. Accepts a single <openrocket> element and hands
528 * the contents to be read by a OpenRocketContentsHandler.
530 class OpenRocketHandler extends ElementHandler {
531 private OpenRocketContentHandler handler = null;
534 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
535 * has not been read yet.
537 * @return the document read, or null.
539 public OpenRocketDocument getDocument() {
540 return handler.getDocument();
544 public ElementHandler openElement(String element, HashMap<String, String> attributes,
545 WarningSet warnings) {
547 // Check for unknown elements
548 if (!element.equals("openrocket")) {
549 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
553 // Check for first call
554 if (handler != null) {
555 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
560 // Check version number
561 String version = null;
562 String creator = attributes.remove("creator");
563 String docVersion = attributes.remove("version");
564 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
565 if (v.equals(docVersion)) {
570 if (version == null) {
571 String str = "Unsupported document version";
572 if (docVersion != null)
573 str += " " + docVersion;
574 if (creator != null && !creator.trim().equals(""))
575 str += " (written using '" + creator.trim() + "')";
576 str += ", attempting to read file anyway.";
580 handler = new OpenRocketContentHandler();
585 public void closeElement(String element, HashMap<String, String> attributes,
586 String content, WarningSet warnings) throws SAXException {
587 attributes.remove("version");
588 attributes.remove("creator");
589 super.closeElement(element, attributes, content, warnings);
597 * Handles the content of the <openrocket> tag.
599 class OpenRocketContentHandler extends ElementHandler {
600 private final OpenRocketDocument doc;
601 private final Rocket rocket;
603 private boolean rocketDefined = false;
604 private boolean simulationsDefined = false;
606 public OpenRocketContentHandler() {
607 this.rocket = new Rocket();
608 this.doc = new OpenRocketDocument(rocket);
612 public OpenRocketDocument getDocument() {
619 public ElementHandler openElement(String element, HashMap<String, String> attributes,
620 WarningSet warnings) {
622 if (element.equals("rocket")) {
625 .fromString("Multiple rocket designs within one document, "
626 + "ignoring later ones."));
629 rocketDefined = true;
630 return new ComponentParameterHandler(rocket);
633 if (element.equals("simulations")) {
634 if (simulationsDefined) {
636 .fromString("Multiple simulation definitions within one document, "
637 + "ignoring later ones."));
640 simulationsDefined = true;
641 return new SimulationsHandler(doc);
644 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
654 * A handler that creates components from the corresponding elements. The control of the
655 * contents is passed on to ComponentParameterHandler.
657 class ComponentHandler extends ElementHandler {
658 private final RocketComponent parent;
660 public ComponentHandler(RocketComponent parent) {
661 this.parent = parent;
665 public ElementHandler openElement(String element, HashMap<String, String> attributes,
666 WarningSet warnings) {
668 // Attempt to construct new component
669 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
671 if (constructor == null) {
672 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
678 c = constructor.newInstance();
679 } catch (InstantiationException e) {
680 throw new BugException("Error constructing component.", e);
681 } catch (IllegalAccessException e) {
682 throw new BugException("Error constructing component.", e);
683 } catch (InvocationTargetException e) {
684 throw Reflection.handleWrappedException(e);
689 return new ComponentParameterHandler(c);
695 * A handler that populates the parameters of a previously constructed rocket component.
696 * This uses the setters, or delegates the handling to another handler for specific
699 class ComponentParameterHandler extends ElementHandler {
700 private final RocketComponent component;
702 public ComponentParameterHandler(RocketComponent c) {
707 public ElementHandler openElement(String element, HashMap<String, String> attributes,
708 WarningSet warnings) {
710 // Check for specific elements that contain other elements
711 if (element.equals("subcomponents")) {
712 return new ComponentHandler(component);
714 if (element.equals("motormount")) {
715 if (!(component instanceof MotorMount)) {
716 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
719 return new MotorMountHandler((MotorMount) component);
721 if (element.equals("finpoints")) {
722 if (!(component instanceof FreeformFinSet)) {
723 warnings.add(Warning.fromString("Illegal component defined for fin points."));
726 return new FinSetPointHandler((FreeformFinSet) component);
728 if (element.equals("motorconfiguration")) {
729 if (!(component instanceof Rocket)) {
730 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
733 return new MotorConfigurationHandler((Rocket) component);
737 return PlainTextHandler.INSTANCE;
741 public void closeElement(String element, HashMap<String, String> attributes,
742 String content, WarningSet warnings) {
744 if (element.equals("subcomponents") || element.equals("motormount") ||
745 element.equals("finpoints") || element.equals("motorconfiguration")) {
749 // Search for the correct setter class
752 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
753 String setterKey = c.getSimpleName() + ":" + element;
754 Setter s = DocumentConfig.setters.get(setterKey);
757 s.set(component, content, attributes, warnings);
760 if (DocumentConfig.setters.containsKey(setterKey)) {
761 // Key exists but is null -> invalid parameter
767 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
768 + component.getComponentName() + ", ignoring."));
775 * A handler that reads the <point> specifications within the freeformfinset's
776 * <finpoints> elements.
778 class FinSetPointHandler extends ElementHandler {
779 private final FreeformFinSet finset;
780 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
782 public FinSetPointHandler(FreeformFinSet finset) {
783 this.finset = finset;
787 public ElementHandler openElement(String element, HashMap<String, String> attributes,
788 WarningSet warnings) {
789 return PlainTextHandler.INSTANCE;
794 public void closeElement(String element, HashMap<String, String> attributes,
795 String content, WarningSet warnings) throws SAXException {
797 String strx = attributes.remove("x");
798 String stry = attributes.remove("y");
799 if (strx == null || stry == null) {
800 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
804 double x = Double.parseDouble(strx);
805 double y = Double.parseDouble(stry);
806 coordinates.add(new Coordinate(x, y));
807 } catch (NumberFormatException e) {
808 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
812 super.closeElement(element, attributes, content, warnings);
816 public void endHandler(String element, HashMap<String, String> attributes,
817 String content, WarningSet warnings) {
819 finset.setPoints(coordinates.toArray(new Coordinate[0]));
820 } catch (IllegalFinPointException e) {
821 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
827 class MotorMountHandler extends ElementHandler {
828 private final MotorMount mount;
829 private MotorHandler motorHandler;
831 public MotorMountHandler(MotorMount mount) {
833 mount.setMotorMount(true);
837 public ElementHandler openElement(String element, HashMap<String, String> attributes,
838 WarningSet warnings) {
840 if (element.equals("motor")) {
841 motorHandler = new MotorHandler();
845 if (element.equals("ignitionevent") ||
846 element.equals("ignitiondelay") ||
847 element.equals("overhang")) {
848 return PlainTextHandler.INSTANCE;
851 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
858 public void closeElement(String element, HashMap<String, String> attributes,
859 String content, WarningSet warnings) throws SAXException {
861 if (element.equals("motor")) {
862 String id = attributes.get("configid");
863 if (id == null || id.equals("")) {
864 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
868 Motor motor = motorHandler.getMotor(warnings);
869 mount.setMotor(id, motor);
870 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
874 if (element.equals("ignitionevent")) {
875 MotorMount.IgnitionEvent event = null;
876 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
877 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
883 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
886 mount.setIgnitionEvent(event);
890 if (element.equals("ignitiondelay")) {
893 d = Double.parseDouble(content);
894 } catch (NumberFormatException nfe) {
895 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
898 mount.setIgnitionDelay(d);
902 if (element.equals("overhang")) {
905 d = Double.parseDouble(content);
906 } catch (NumberFormatException nfe) {
907 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
910 mount.setMotorOverhang(d);
914 super.closeElement(element, attributes, content, warnings);
921 class MotorConfigurationHandler extends ElementHandler {
922 private final Rocket rocket;
923 private String name = null;
924 private boolean inNameElement = false;
926 public MotorConfigurationHandler(Rocket rocket) {
927 this.rocket = rocket;
931 public ElementHandler openElement(String element, HashMap<String, String> attributes,
932 WarningSet warnings) {
934 if (inNameElement || !element.equals("name")) {
935 warnings.add(Warning.FILE_INVALID_PARAMETER);
938 inNameElement = true;
940 return PlainTextHandler.INSTANCE;
944 public void closeElement(String element, HashMap<String, String> attributes,
945 String content, WarningSet warnings) {
950 public void endHandler(String element, HashMap<String, String> attributes,
951 String content, WarningSet warnings) throws SAXException {
953 String configid = attributes.remove("configid");
954 if (configid == null || configid.equals("")) {
955 warnings.add(Warning.FILE_INVALID_PARAMETER);
959 if (!rocket.addMotorConfigurationID(configid)) {
960 warnings.add("Duplicate motor configuration ID used.");
964 if (name != null && name.trim().length() > 0) {
965 rocket.setMotorConfigurationName(configid, name);
968 if ("true".equals(attributes.remove("default"))) {
969 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
972 super.closeElement(element, attributes, content, warnings);
977 class MotorHandler extends ElementHandler {
978 private Motor.Type type = null;
979 private String manufacturer = null;
980 private String designation = null;
981 private String digest = null;
982 private double diameter = Double.NaN;
983 private double length = Double.NaN;
984 private double delay = Double.NaN;
987 public ElementHandler openElement(String element, HashMap<String, String> attributes,
988 WarningSet warnings) {
989 return PlainTextHandler.INSTANCE;
994 * Return the motor to use, or null.
996 public Motor getMotor(WarningSet warnings) {
997 if (designation == null) {
998 warnings.add(Warning.fromString("No motor specified, ignoring."));
1002 List<ThrustCurveMotor> motors = Application.getMotorSetDatabase().findMotors(type, manufacturer,
1003 designation, diameter, length);
1006 if (motors.size() == 0) {
1007 String str = "No motor with designation '" + designation + "'";
1008 if (manufacturer != null)
1009 str += " for manufacturer '" + manufacturer + "'";
1016 if (motors.size() == 1) {
1017 ThrustCurveMotor m = motors.get(0);
1018 if (digest != null && !MotorDigest.digestMotor(m).equals(digest)) {
1019 String str = "Motor with designation '" + designation + "'";
1020 if (manufacturer != null)
1021 str += " for manufacturer '" + manufacturer + "'";
1022 str += " has differing thrust curve than the original.";
1028 // Multiple motors, check digest for which one to use
1029 if (digest != null) {
1031 // Check for motor with correct digest
1032 for (ThrustCurveMotor m : motors) {
1033 if (MotorDigest.digestMotor(m).equals(digest)) {
1037 String str = "Motor with designation '" + designation + "'";
1038 if (manufacturer != null)
1039 str += " for manufacturer '" + manufacturer + "'";
1040 str += " has differing thrust curve than the original.";
1045 // No digest, check for preferred digest (OpenRocket <= 1.1.0)
1046 // TODO: MEDIUM: This should only be done for document versions 1.1 and below
1047 for (ThrustCurveMotor m : motors) {
1048 if (PreferredMotorDigests.DIGESTS.contains(MotorDigest.digestMotor(m))) {
1053 String str = "Multiple motors with designation '" + designation + "'";
1054 if (manufacturer != null)
1055 str += " for manufacturer '" + manufacturer + "'";
1056 str += " found, one chosen arbitrarily.";
1060 return motors.get(0);
1064 * Return the delay to use for the motor.
1066 public double getDelay(WarningSet warnings) {
1067 if (Double.isNaN(delay)) {
1068 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1069 return Motor.PLUGGED;
1076 public void closeElement(String element, HashMap<String, String> attributes,
1077 String content, WarningSet warnings) throws SAXException {
1079 content = content.trim();
1081 if (element.equals("type")) {
1085 for (Motor.Type t : Motor.Type.values()) {
1086 if (t.name().toLowerCase().equals(content.trim())) {
1092 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1095 } else if (element.equals("manufacturer")) {
1098 manufacturer = content.trim();
1100 } else if (element.equals("designation")) {
1103 designation = content.trim();
1105 } else if (element.equals("digest")) {
1108 digest = content.trim();
1110 } else if (element.equals("diameter")) {
1113 diameter = Double.NaN;
1115 diameter = Double.parseDouble(content.trim());
1116 } catch (NumberFormatException e) {
1119 if (Double.isNaN(diameter)) {
1120 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1123 } else if (element.equals("length")) {
1126 length = Double.NaN;
1128 length = Double.parseDouble(content.trim());
1129 } catch (NumberFormatException ignore) {
1132 if (Double.isNaN(length)) {
1133 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1136 } else if (element.equals("delay")) {
1140 if (content.equals("none")) {
1141 delay = Motor.PLUGGED;
1144 delay = Double.parseDouble(content.trim());
1145 } catch (NumberFormatException ignore) {
1148 if (Double.isNaN(delay)) {
1149 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1155 super.closeElement(element, attributes, content, warnings);
1163 class SimulationsHandler extends ElementHandler {
1164 private final OpenRocketDocument doc;
1165 private SingleSimulationHandler handler;
1167 public SimulationsHandler(OpenRocketDocument doc) {
1172 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1173 WarningSet warnings) {
1175 if (!element.equals("simulation")) {
1176 warnings.add("Unknown element '" + element + "', ignoring.");
1180 handler = new SingleSimulationHandler(doc);
1185 public void closeElement(String element, HashMap<String, String> attributes,
1186 String content, WarningSet warnings) throws SAXException {
1187 attributes.remove("status");
1188 super.closeElement(element, attributes, content, warnings);
1194 class SingleSimulationHandler extends ElementHandler {
1196 private final OpenRocketDocument doc;
1198 private String name;
1200 private SimulationConditionsHandler conditionHandler;
1201 private FlightDataHandler dataHandler;
1203 private final List<String> listeners = new ArrayList<String>();
1205 public SingleSimulationHandler(OpenRocketDocument doc) {
1212 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1213 WarningSet warnings) {
1215 if (element.equals("name") || element.equals("simulator") ||
1216 element.equals("calculator") || element.equals("listener")) {
1217 return PlainTextHandler.INSTANCE;
1218 } else if (element.equals("conditions")) {
1219 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1220 return conditionHandler;
1221 } else if (element.equals("flightdata")) {
1222 dataHandler = new FlightDataHandler();
1225 warnings.add("Unknown element '" + element + "', ignoring.");
1231 public void closeElement(String element, HashMap<String, String> attributes,
1232 String content, WarningSet warnings) {
1234 if (element.equals("name")) {
1236 } else if (element.equals("simulator")) {
1237 if (!content.trim().equals("RK4Simulator")) {
1238 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1240 } else if (element.equals("calculator")) {
1241 if (!content.trim().equals("BarrowmanCalculator")) {
1242 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1244 } else if (element.equals("listener") && content.trim().length() > 0) {
1245 listeners.add(content.trim());
1251 public void endHandler(String element, HashMap<String, String> attributes,
1252 String content, WarningSet warnings) {
1254 String s = attributes.get("status");
1255 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1256 if (status == null) {
1257 warnings.add("Simulation status unknown, assuming outdated.");
1258 status = Simulation.Status.OUTDATED;
1261 SimulationOptions conditions;
1262 if (conditionHandler != null) {
1263 conditions = conditionHandler.getConditions();
1265 warnings.add("Simulation conditions not defined, using defaults.");
1266 conditions = new SimulationOptions(doc.getRocket());
1270 name = "Simulation";
1273 if (dataHandler == null)
1276 data = dataHandler.getFlightData();
1278 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1279 conditions, listeners, data);
1281 doc.addSimulation(simulation);
1287 class SimulationConditionsHandler extends ElementHandler {
1288 private SimulationOptions conditions;
1289 private AtmosphereHandler atmosphereHandler;
1291 public SimulationConditionsHandler(Rocket rocket) {
1292 conditions = new SimulationOptions(rocket);
1293 // Set up default loading settings (which may differ from the new defaults)
1294 conditions.setGeodeticComputation(GeodeticComputationStrategy.NONE);
1297 public SimulationOptions getConditions() {
1302 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1303 WarningSet warnings) {
1304 if (element.equals("atmosphere")) {
1305 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1306 return atmosphereHandler;
1308 return PlainTextHandler.INSTANCE;
1312 public void closeElement(String element, HashMap<String, String> attributes,
1313 String content, WarningSet warnings) {
1315 double d = Double.NaN;
1317 d = Double.parseDouble(content);
1318 } catch (NumberFormatException ignore) {
1322 if (element.equals("configid")) {
1323 if (content.equals("")) {
1324 conditions.setMotorConfigurationID(null);
1326 conditions.setMotorConfigurationID(content);
1328 } else if (element.equals("launchrodlength")) {
1329 if (Double.isNaN(d)) {
1330 warnings.add("Illegal launch rod length defined, ignoring.");
1332 conditions.setLaunchRodLength(d);
1334 } else if (element.equals("launchrodangle")) {
1335 if (Double.isNaN(d)) {
1336 warnings.add("Illegal launch rod angle defined, ignoring.");
1338 conditions.setLaunchRodAngle(d * Math.PI / 180);
1340 } else if (element.equals("launchroddirection")) {
1341 if (Double.isNaN(d)) {
1342 warnings.add("Illegal launch rod direction defined, ignoring.");
1344 conditions.setLaunchRodDirection(d * Math.PI / 180);
1346 } else if (element.equals("windaverage")) {
1347 if (Double.isNaN(d)) {
1348 warnings.add("Illegal average windspeed defined, ignoring.");
1350 conditions.setWindSpeedAverage(d);
1352 } else if (element.equals("windturbulence")) {
1353 if (Double.isNaN(d)) {
1354 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1356 conditions.setWindTurbulenceIntensity(d);
1358 } else if (element.equals("launchaltitude")) {
1359 if (Double.isNaN(d)) {
1360 warnings.add("Illegal launch altitude defined, ignoring.");
1362 conditions.setLaunchAltitude(d);
1364 } else if (element.equals("launchlatitude")) {
1365 if (Double.isNaN(d)) {
1366 warnings.add("Illegal launch latitude defined, ignoring.");
1368 conditions.setLaunchLatitude(d);
1370 } else if (element.equals("launchlongitude")) {
1371 if (Double.isNaN(d)) {
1372 warnings.add("Illegal launch longitude.");
1374 conditions.setLaunchLongitude(d);
1376 } else if (element.equals("geodeticmethod")) {
1377 GeodeticComputationStrategy gcs =
1378 (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1380 conditions.setGeodeticComputation(gcs);
1382 warnings.add("Unknown geodetic computation method '" + content + "'");
1384 } else if (element.equals("atmosphere")) {
1385 atmosphereHandler.storeSettings(conditions, warnings);
1386 } else if (element.equals("timestep")) {
1387 if (Double.isNaN(d)) {
1388 warnings.add("Illegal time step defined, ignoring.");
1390 conditions.setTimeStep(d);
1397 class AtmosphereHandler extends ElementHandler {
1398 private final String model;
1399 private double temperature = Double.NaN;
1400 private double pressure = Double.NaN;
1402 public AtmosphereHandler(String model) {
1407 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1408 WarningSet warnings) {
1409 return PlainTextHandler.INSTANCE;
1413 public void closeElement(String element, HashMap<String, String> attributes,
1414 String content, WarningSet warnings) throws SAXException {
1416 double d = Double.NaN;
1418 d = Double.parseDouble(content);
1419 } catch (NumberFormatException ignore) {
1422 if (element.equals("basetemperature")) {
1423 if (Double.isNaN(d)) {
1424 warnings.add("Illegal base temperature specified, ignoring.");
1427 } else if (element.equals("basepressure")) {
1428 if (Double.isNaN(d)) {
1429 warnings.add("Illegal base pressure specified, ignoring.");
1433 super.closeElement(element, attributes, content, warnings);
1438 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1439 if (!Double.isNaN(pressure)) {
1440 cond.setLaunchPressure(pressure);
1442 if (!Double.isNaN(temperature)) {
1443 cond.setLaunchTemperature(temperature);
1446 if ("isa".equals(model)) {
1447 cond.setISAAtmosphere(true);
1448 } else if ("extendedisa".equals(model)) {
1449 cond.setISAAtmosphere(false);
1451 cond.setISAAtmosphere(true);
1452 warnings.add("Unknown atmospheric model, using ISA.");
1459 class FlightDataHandler extends ElementHandler {
1461 private FlightDataBranchHandler dataHandler;
1462 private WarningSet warningSet = new WarningSet();
1463 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1465 private FlightData data;
1467 public FlightData getFlightData() {
1472 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1473 WarningSet warnings) {
1475 if (element.equals("warning")) {
1476 return PlainTextHandler.INSTANCE;
1478 if (element.equals("databranch")) {
1479 if (attributes.get("name") == null || attributes.get("types") == null) {
1480 warnings.add("Illegal flight data definition, ignoring.");
1483 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1484 attributes.get("types"));
1488 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1494 public void closeElement(String element, HashMap<String, String> attributes,
1495 String content, WarningSet warnings) {
1497 if (element.equals("databranch")) {
1498 FlightDataBranch branch = dataHandler.getBranch();
1499 if (branch.getLength() > 0) {
1500 branches.add(branch);
1502 } else if (element.equals("warning")) {
1503 warningSet.add(Warning.fromString(content));
1509 public void endHandler(String element, HashMap<String, String> attributes,
1510 String content, WarningSet warnings) {
1512 if (branches.size() > 0) {
1513 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1515 double maxAltitude = Double.NaN;
1516 double maxVelocity = Double.NaN;
1517 double maxAcceleration = Double.NaN;
1518 double maxMach = Double.NaN;
1519 double timeToApogee = Double.NaN;
1520 double flightTime = Double.NaN;
1521 double groundHitVelocity = Double.NaN;
1524 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1525 } catch (NumberFormatException ignore) {
1528 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1529 } catch (NumberFormatException ignore) {
1532 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1533 } catch (NumberFormatException ignore) {
1536 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1537 } catch (NumberFormatException ignore) {
1540 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1541 } catch (NumberFormatException ignore) {
1544 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1545 } catch (NumberFormatException ignore) {
1549 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1550 } catch (NumberFormatException ignore) {
1553 // TODO: HIGH: Store and load launchRodVelocity
1554 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1555 timeToApogee, flightTime, groundHitVelocity, Double.NaN);
1558 data.getWarningSet().addAll(warningSet);
1566 class FlightDataBranchHandler extends ElementHandler {
1567 private final FlightDataType[] types;
1568 private final FlightDataBranch branch;
1570 public FlightDataBranchHandler(String name, String typeList) {
1571 String[] split = typeList.split(",");
1572 types = new FlightDataType[split.length];
1573 for (int i = 0; i < split.length; i++) {
1574 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1577 // TODO: LOW: May throw an IllegalArgumentException
1578 branch = new FlightDataBranch(name, types);
1581 public FlightDataBranch getBranch() {
1587 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1588 WarningSet warnings) {
1590 if (element.equals("datapoint"))
1591 return PlainTextHandler.INSTANCE;
1592 if (element.equals("event"))
1593 return PlainTextHandler.INSTANCE;
1595 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1601 public void closeElement(String element, HashMap<String, String> attributes,
1602 String content, WarningSet warnings) {
1604 if (element.equals("event")) {
1606 FlightEvent.Type type;
1609 time = DocumentConfig.stringToDouble(attributes.get("time"));
1610 } catch (NumberFormatException e) {
1611 warnings.add("Illegal event specification, ignoring.");
1615 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1617 warnings.add("Illegal event specification, ignoring.");
1621 branch.addEvent(new FlightEvent(type, time));
1625 if (!element.equals("datapoint")) {
1626 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1630 // element == "datapoint"
1633 // Check line format
1634 String[] split = content.split(",");
1635 if (split.length != types.length) {
1636 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1640 // Parse the doubles
1641 double[] values = new double[split.length];
1642 for (int i = 0; i < values.length; i++) {
1644 values[i] = DocumentConfig.stringToDouble(split[i]);
1645 } catch (NumberFormatException e) {
1646 warnings.add("Data point format error, ignoring point.");
1651 // Add point to branch
1653 for (int i = 0; i < types.length; i++) {
1654 branch.setValue(types[i], values[i]);
1663 ///////////////// Setters implementation
1669 * Set the specified value to the given component.
1671 * @param component the component to which to set.
1672 * @param value the value within the element.
1673 * @param attributes attributes for the element.
1674 * @param warnings the warning set to use.
1676 public void set(RocketComponent component, String value,
1677 HashMap<String, String> attributes, WarningSet warnings);
1681 //// StringSetter - sets the value to the contained String
1682 class StringSetter implements Setter {
1683 private final Reflection.Method setMethod;
1685 public StringSetter(Reflection.Method set) {
1690 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1691 WarningSet warnings) {
1692 setMethod.invoke(c, s);
1696 //// IntSetter - set an integer value
1697 class IntSetter implements Setter {
1698 private final Reflection.Method setMethod;
1700 public IntSetter(Reflection.Method set) {
1705 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1706 WarningSet warnings) {
1708 int n = Integer.parseInt(s);
1709 setMethod.invoke(c, n);
1710 } catch (NumberFormatException e) {
1711 warnings.add(Warning.FILE_INVALID_PARAMETER);
1717 //// BooleanSetter - set a boolean value
1718 class BooleanSetter implements Setter {
1719 private final Reflection.Method setMethod;
1721 public BooleanSetter(Reflection.Method set) {
1726 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1727 WarningSet warnings) {
1730 if (s.equalsIgnoreCase("true")) {
1731 setMethod.invoke(c, true);
1732 } else if (s.equalsIgnoreCase("false")) {
1733 setMethod.invoke(c, false);
1735 warnings.add(Warning.FILE_INVALID_PARAMETER);
1742 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1743 //// calls a setXXX(boolean) method.
1744 class DoubleSetter implements Setter {
1745 private final Reflection.Method setMethod;
1746 private final String specialString;
1747 private final Reflection.Method specialMethod;
1748 private final double multiplier;
1751 * Set only the double value.
1752 * @param set set method for the double value.
1754 public DoubleSetter(Reflection.Method set) {
1755 this.setMethod = set;
1756 this.specialString = null;
1757 this.specialMethod = null;
1758 this.multiplier = 1.0;
1762 * Multiply with the given multiplier and set the double value.
1763 * @param set set method for the double value.
1764 * @param mul multiplier.
1766 public DoubleSetter(Reflection.Method set, double mul) {
1767 this.setMethod = set;
1768 this.specialString = null;
1769 this.specialMethod = null;
1770 this.multiplier = mul;
1774 * Set the double value, or if the value equals the special string, use the
1775 * special setter and set it to true.
1777 * @param set double setter.
1778 * @param special special string
1779 * @param specialMethod boolean setter.
1781 public DoubleSetter(Reflection.Method set, String special,
1782 Reflection.Method specialMethod) {
1783 this.setMethod = set;
1784 this.specialString = special;
1785 this.specialMethod = specialMethod;
1786 this.multiplier = 1.0;
1791 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1792 WarningSet warnings) {
1796 // Check for special case
1797 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1798 specialMethod.invoke(c, true);
1804 double d = Double.parseDouble(s);
1805 setMethod.invoke(c, d * multiplier);
1806 } catch (NumberFormatException e) {
1807 warnings.add(Warning.FILE_INVALID_PARAMETER);
1813 class OverrideSetter implements Setter {
1814 private final Reflection.Method setMethod;
1815 private final Reflection.Method enabledMethod;
1817 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1818 this.setMethod = set;
1819 this.enabledMethod = enabledMethod;
1823 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1824 WarningSet warnings) {
1827 double d = Double.parseDouble(s);
1828 setMethod.invoke(c, d);
1829 enabledMethod.invoke(c, true);
1830 } catch (NumberFormatException e) {
1831 warnings.add(Warning.FILE_INVALID_PARAMETER);
1836 //// EnumSetter - sets a generic enum type
1837 class EnumSetter<T extends Enum<T>> implements Setter {
1838 private final Reflection.Method setter;
1839 private final Class<T> enumClass;
1841 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1843 this.enumClass = enumClass;
1847 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1848 WarningSet warnings) {
1850 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1851 if (setEnum == null) {
1852 warnings.add(Warning.FILE_INVALID_PARAMETER);
1856 setter.invoke(c, setEnum);
1861 //// ColorSetter - sets a Color value
1862 class ColorSetter implements Setter {
1863 private final Reflection.Method setMethod;
1865 public ColorSetter(Reflection.Method set) {
1870 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1871 WarningSet warnings) {
1873 String red = attributes.get("red");
1874 String green = attributes.get("green");
1875 String blue = attributes.get("blue");
1877 if (red == null || green == null || blue == null) {
1878 warnings.add(Warning.FILE_INVALID_PARAMETER);
1884 r = Integer.parseInt(red);
1885 g = Integer.parseInt(green);
1886 b = Integer.parseInt(blue);
1887 } catch (NumberFormatException e) {
1888 warnings.add(Warning.FILE_INVALID_PARAMETER);
1892 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1893 warnings.add(Warning.FILE_INVALID_PARAMETER);
1897 Color color = new Color(r, g, b);
1898 setMethod.invoke(c, color);
1900 if (!s.trim().equals("")) {
1901 warnings.add(Warning.FILE_INVALID_PARAMETER);
1908 class MaterialSetter implements Setter {
1909 private final Reflection.Method setMethod;
1910 private final Material.Type type;
1912 public MaterialSetter(Reflection.Method set, Material.Type type) {
1913 this.setMethod = set;
1918 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1919 WarningSet warnings) {
1925 if (name.equals("")) {
1926 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1933 str = attributes.remove("density");
1935 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1939 density = Double.parseDouble(str);
1940 } catch (NumberFormatException e) {
1941 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1946 // double thickness = 0;
1947 // str = attributes.remove("thickness");
1950 // thickness = Double.parseDouble(str);
1951 // } catch (NumberFormatException e){
1952 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1956 // Check type if specified
1957 str = attributes.remove("type");
1958 if (str != null && !type.name().toLowerCase().equals(str)) {
1959 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1963 mat = Databases.findMaterial(type, name, density, false);
1965 setMethod.invoke(c, mat);
1972 class PositionSetter implements Setter {
1975 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1976 WarningSet warnings) {
1978 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1979 RocketComponent.Position.class);
1981 warnings.add(Warning.FILE_INVALID_PARAMETER);
1987 pos = Double.parseDouble(value);
1988 } catch (NumberFormatException e) {
1989 warnings.add(Warning.FILE_INVALID_PARAMETER);
1993 if (c instanceof FinSet) {
1994 ((FinSet) c).setRelativePosition(type);
1995 c.setPositionValue(pos);
1996 } else if (c instanceof LaunchLug) {
1997 ((LaunchLug) c).setRelativePosition(type);
1998 c.setPositionValue(pos);
1999 } else if (c instanceof InternalComponent) {
2000 ((InternalComponent) c).setRelativePosition(type);
2001 c.setPositionValue(pos);
2003 warnings.add(Warning.FILE_INVALID_PARAMETER);
2010 class FinTabPositionSetter extends DoubleSetter {
2012 public FinTabPositionSetter() {
2013 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2017 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2018 WarningSet warnings) {
2020 if (!(c instanceof FinSet)) {
2021 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2024 String relative = attributes.get("relativeto");
2025 FinSet.TabRelativePosition position =
2026 (TabRelativePosition) DocumentConfig.findEnum(relative,
2027 FinSet.TabRelativePosition.class);
2029 if (position != null) {
2031 ((FinSet) c).setTabRelativePosition(position);
2034 if (relative == null) {
2035 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2037 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2041 super.set(c, s, attributes, warnings);
2048 class ClusterConfigurationSetter implements Setter {
2051 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2052 WarningSet warnings) {
2054 if (!(component instanceof Clusterable)) {
2055 warnings.add("Illegal component defined as cluster.");
2059 ClusterConfiguration config = null;
2060 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2061 if (c.getXMLName().equals(value)) {
2067 if (config == null) {
2068 warnings.add("Illegal cluster configuration specified.");
2072 ((Clusterable) component).setClusterConfiguration(config);