1 package net.sf.openrocket.file.openrocket.importt;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.InvocationTargetException;
7 import java.util.ArrayList;
8 import java.util.HashMap;
10 import java.util.regex.Matcher;
11 import java.util.regex.Pattern;
13 import net.sf.openrocket.aerodynamics.Warning;
14 import net.sf.openrocket.aerodynamics.WarningSet;
15 import net.sf.openrocket.database.Databases;
16 import net.sf.openrocket.document.OpenRocketDocument;
17 import net.sf.openrocket.document.Simulation;
18 import net.sf.openrocket.document.Simulation.Status;
19 import net.sf.openrocket.document.StorageOptions;
20 import net.sf.openrocket.file.AbstractRocketLoader;
21 import net.sf.openrocket.file.MotorFinder;
22 import net.sf.openrocket.file.RocketLoadException;
23 import net.sf.openrocket.file.simplesax.ElementHandler;
24 import net.sf.openrocket.file.simplesax.PlainTextHandler;
25 import net.sf.openrocket.file.simplesax.SimpleSAX;
26 import net.sf.openrocket.logging.LogHelper;
27 import net.sf.openrocket.material.Material;
28 import net.sf.openrocket.motor.Motor;
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.Color;
77 import net.sf.openrocket.util.Coordinate;
78 import net.sf.openrocket.util.GeodeticComputationStrategy;
79 import net.sf.openrocket.util.LineStyle;
80 import net.sf.openrocket.util.Reflection;
82 import org.xml.sax.InputSource;
83 import org.xml.sax.SAXException;
87 * Class that loads a rocket definition from an OpenRocket rocket file.
89 * This class uses SAX to read the XML file format. The
90 * #loadFromStream(InputStream) method simply sets the system up and
91 * starts the parsing, while the actual logic is in the private inner class
92 * <code>OpenRocketHandler</code>.
94 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
96 public class OpenRocketLoader extends AbstractRocketLoader {
97 private static final LogHelper log = Application.getLogger();
101 public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException,
103 log.info("Loading .ork file");
104 DocumentLoadingContext context = new DocumentLoadingContext();
105 context.setMotorFinder(motorFinder);
107 InputSource xmlSource = new InputSource(source);
108 OpenRocketHandler handler = new OpenRocketHandler(context);
112 SimpleSAX.readXML(xmlSource, handler, warnings);
113 } catch (SAXException e) {
114 log.warn("Malformed XML in input");
115 throw new RocketLoadException("Malformed XML in input.", e);
119 OpenRocketDocument doc = handler.getDocument();
120 doc.getDefaultConfiguration().setAllStages();
122 // Deduce suitable time skip
123 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
124 for (Simulation s : doc.getSimulations()) {
125 if (s.getStatus() == Simulation.Status.EXTERNAL ||
126 s.getStatus() == Simulation.Status.NOT_SIMULATED)
128 if (s.getSimulatedData() == null)
130 if (s.getSimulatedData().getBranchCount() == 0)
132 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
135 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
139 double previousTime = Double.NaN;
140 for (double time : list) {
141 if (time - previousTime < timeSkip)
142 timeSkip = time - previousTime;
147 timeSkip = Math.rint(timeSkip * 100) / 100;
149 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
150 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
151 doc.getDefaultStorageOptions().setExplicitlySet(false);
154 log.info("Loading done");
162 class DocumentConfig {
164 /* Remember to update OpenRocketSaver as well! */
165 public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4" };
168 * Divisor used in converting an integer version to the point-represented version.
169 * The integer version divided by this value is the major version and the remainder is
170 * the minor version. For example 101 corresponds to file version "1.1".
172 public static final int FILE_VERSION_DIVISOR = 100;
175 //////// Component constructors
176 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
179 // External components
180 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
181 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
182 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
183 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
184 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
185 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
186 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
188 // Internal components
189 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
190 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
191 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
192 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
193 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
195 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
196 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
197 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
198 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
201 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
203 } catch (NoSuchMethodException e) {
204 throw new BugException(
205 "Error in constructing the 'constructors' HashMap.");
210 //////// Parameter setters
212 * The keys are of the form Class:param, where Class is the class name and param
213 * the element name. Setters are searched for in descending class order.
214 * A setter of null means setting the parameter is not allowed.
216 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
219 setters.put("RocketComponent:name", new StringSetter(
220 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
221 setters.put("RocketComponent:color", new ColorSetter(
222 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
223 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
224 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
226 setters.put("RocketComponent:position", new PositionSetter());
227 setters.put("RocketComponent:overridemass", new OverrideSetter(
228 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
229 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
230 setters.put("RocketComponent:overridecg", new OverrideSetter(
231 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
232 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
233 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
234 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
235 setters.put("RocketComponent:comment", new StringSetter(
236 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
239 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
240 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
242 setters.put("ExternalComponent:material", new MaterialSetter(
243 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
244 Material.Type.BULK));
247 setters.put("BodyComponent:length", new DoubleSetter(
248 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
250 // SymmetricComponent
251 setters.put("SymmetricComponent:thickness", new DoubleSetter(
252 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
254 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
257 setters.put("BodyTube:radius", new DoubleSetter(
258 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
260 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
263 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
264 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
265 Transition.Shape.class));
266 setters.put("Transition:shapeclipped", new BooleanSetter(
267 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
268 setters.put("Transition:shapeparameter", new DoubleSetter(
269 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
271 setters.put("Transition:foreradius", new DoubleSetter(
272 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
274 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
275 setters.put("Transition:aftradius", new DoubleSetter(
276 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
278 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
280 setters.put("Transition:foreshoulderradius", new DoubleSetter(
281 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
282 setters.put("Transition:foreshoulderlength", new DoubleSetter(
283 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
284 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
285 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
286 setters.put("Transition:foreshouldercapped", new BooleanSetter(
287 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
289 setters.put("Transition:aftshoulderradius", new DoubleSetter(
290 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
291 setters.put("Transition:aftshoulderlength", new DoubleSetter(
292 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
293 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
294 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
295 setters.put("Transition:aftshouldercapped", new BooleanSetter(
296 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
298 // NoseCone - disable disallowed elements
299 setters.put("NoseCone:foreradius", null);
300 setters.put("NoseCone:foreshoulderradius", null);
301 setters.put("NoseCone:foreshoulderlength", null);
302 setters.put("NoseCone:foreshoulderthickness", null);
303 setters.put("NoseCone:foreshouldercapped", null);
306 setters.put("FinSet:fincount", new IntSetter(
307 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
308 setters.put("FinSet:rotation", new DoubleSetter(
309 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
310 setters.put("FinSet:thickness", new DoubleSetter(
311 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
312 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
313 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
314 FinSet.CrossSection.class));
315 setters.put("FinSet:cant", new DoubleSetter(
316 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
317 setters.put("FinSet:tabheight", new DoubleSetter(
318 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
319 setters.put("FinSet:tablength", new DoubleSetter(
320 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
321 setters.put("FinSet:tabposition", new FinTabPositionSetter());
324 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
325 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
326 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
327 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
328 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
329 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
330 setters.put("TrapezoidFinSet:height", new DoubleSetter(
331 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
334 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
335 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
336 setters.put("EllipticalFinSet:height", new DoubleSetter(
337 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
339 // FreeformFinSet points handled as a special handler
342 setters.put("LaunchLug:radius", new DoubleSetter(
343 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
344 setters.put("LaunchLug:length", new DoubleSetter(
345 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
346 setters.put("LaunchLug:thickness", new DoubleSetter(
347 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
348 setters.put("LaunchLug:radialdirection", new DoubleSetter(
349 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
352 // InternalComponent - nothing
354 // StructuralComponent
355 setters.put("StructuralComponent:material", new MaterialSetter(
356 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
357 Material.Type.BULK));
360 setters.put("RingComponent:length", new DoubleSetter(
361 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
362 setters.put("RingComponent:radialposition", new DoubleSetter(
363 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
364 setters.put("RingComponent:radialdirection", new DoubleSetter(
365 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
368 // ThicknessRingComponent - radius on separate components due to differing automatics
369 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
370 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
373 setters.put("EngineBlock:outerradius", new DoubleSetter(
374 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
376 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
379 setters.put("TubeCoupler:outerradius", new DoubleSetter(
380 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
382 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
385 setters.put("InnerTube:outerradius", new DoubleSetter(
386 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
387 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
388 setters.put("InnerTube:clusterscale", new DoubleSetter(
389 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
390 setters.put("InnerTube:clusterrotation", new DoubleSetter(
391 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
394 // RadiusRingComponent
397 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
398 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
399 setters.put("Bulkhead:outerradius", new DoubleSetter(
400 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
402 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
405 setters.put("CenteringRing:innerradius", new DoubleSetter(
406 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
408 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
409 setters.put("CenteringRing:outerradius", new DoubleSetter(
410 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
412 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
416 setters.put("MassObject:packedlength", new DoubleSetter(
417 Reflection.findMethod(MassObject.class, "setLength", double.class)));
418 setters.put("MassObject:packedradius", new DoubleSetter(
419 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
420 setters.put("MassObject:radialposition", new DoubleSetter(
421 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
422 setters.put("MassObject:radialdirection", new DoubleSetter(
423 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
427 setters.put("MassComponent:mass", new DoubleSetter(
428 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
431 setters.put("ShockCord:cordlength", new DoubleSetter(
432 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
433 setters.put("ShockCord:material", new MaterialSetter(
434 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
435 Material.Type.LINE));
438 setters.put("RecoveryDevice:cd", new DoubleSetter(
439 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
441 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
442 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
443 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
444 RecoveryDevice.DeployEvent.class));
445 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
446 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
447 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
448 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
449 setters.put("RecoveryDevice:material", new MaterialSetter(
450 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
451 Material.Type.SURFACE));
454 setters.put("Parachute:diameter", new DoubleSetter(
455 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
456 setters.put("Parachute:linecount", new IntSetter(
457 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
458 setters.put("Parachute:linelength", new DoubleSetter(
459 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
460 setters.put("Parachute:linematerial", new MaterialSetter(
461 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
462 Material.Type.LINE));
465 setters.put("Streamer:striplength", new DoubleSetter(
466 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
467 setters.put("Streamer:stripwidth", new DoubleSetter(
468 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
471 // <motorconfiguration> handled by separate handler
472 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
473 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
474 ReferenceType.class));
475 setters.put("Rocket:customreference", new DoubleSetter(
476 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
477 setters.put("Rocket:designer", new StringSetter(
478 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
479 setters.put("Rocket:revision", new StringSetter(
480 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
485 * Search for a enum value that has the corresponding name as an XML value. The current
486 * conversion from enum name to XML value is to lowercase the name and strip out all
487 * underscore characters. This method returns a match to these criteria, or <code>null</code>
488 * if no such enum exists.
490 * @param <T> then enum type.
491 * @param name the XML value, null ok.
492 * @param enumClass the class of the enum.
493 * @return the found enum value, or <code>null</code>.
495 public static <T extends Enum<T>> Enum<T> findEnum(String name,
496 Class<? extends Enum<T>> enumClass) {
501 for (Enum<T> e : enumClass.getEnumConstants()) {
502 if (e.name().toLowerCase().replace("_", "").equals(name)) {
511 * Convert a string to a double including formatting specifications of the OpenRocket
512 * file format. This accepts all formatting that is valid for
513 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
515 * @param s the string to parse.
516 * @return the numerical value.
517 * @throws NumberFormatException the the string cannot be parsed.
519 public static double stringToDouble(String s) throws NumberFormatException {
521 throw new NumberFormatException("null string");
522 if (s.equalsIgnoreCase("NaN"))
524 if (s.equalsIgnoreCase("Inf"))
525 return Double.POSITIVE_INFINITY;
526 if (s.equalsIgnoreCase("-Inf"))
527 return Double.NEGATIVE_INFINITY;
528 return Double.parseDouble(s);
537 * The starting point of the handlers. Accepts a single <openrocket> element and hands
538 * the contents to be read by a OpenRocketContentsHandler.
540 class OpenRocketHandler extends ElementHandler {
541 private final DocumentLoadingContext context;
542 private OpenRocketContentHandler handler = null;
544 public OpenRocketHandler(DocumentLoadingContext context) {
545 this.context = context;
549 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
550 * has not been read yet.
552 * @return the document read, or null.
554 public OpenRocketDocument getDocument() {
555 return handler.getDocument();
559 public ElementHandler openElement(String element, HashMap<String, String> attributes,
560 WarningSet warnings) {
562 // Check for unknown elements
563 if (!element.equals("openrocket")) {
564 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
568 // Check for first call
569 if (handler != null) {
570 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
575 // Check version number
576 String version = null;
577 String creator = attributes.remove("creator");
578 String docVersion = attributes.remove("version");
579 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
580 if (v.equals(docVersion)) {
585 if (version == null) {
586 String str = "Unsupported document version";
587 if (docVersion != null)
588 str += " " + docVersion;
589 if (creator != null && !creator.trim().equals(""))
590 str += " (written using '" + creator.trim() + "')";
591 str += ", attempting to read file anyway.";
595 context.setFileVersion(parseVersion(docVersion));
597 handler = new OpenRocketContentHandler(context);
602 private int parseVersion(String docVersion) {
603 if (docVersion == null)
606 Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion);
608 int major = Integer.parseInt(m.group(1));
609 int minor = Integer.parseInt(m.group(2));
610 return major * DocumentConfig.FILE_VERSION_DIVISOR + minor;
617 public void closeElement(String element, HashMap<String, String> attributes,
618 String content, WarningSet warnings) throws SAXException {
619 attributes.remove("version");
620 attributes.remove("creator");
621 super.closeElement(element, attributes, content, warnings);
629 * Handles the content of the <openrocket> tag.
631 class OpenRocketContentHandler extends ElementHandler {
632 private final DocumentLoadingContext context;
633 private final OpenRocketDocument doc;
634 private final Rocket rocket;
636 private boolean rocketDefined = false;
637 private boolean simulationsDefined = false;
639 public OpenRocketContentHandler(DocumentLoadingContext context) {
640 this.context = context;
641 this.rocket = new Rocket();
642 this.doc = new OpenRocketDocument(rocket);
646 public OpenRocketDocument getDocument() {
653 public ElementHandler openElement(String element, HashMap<String, String> attributes,
654 WarningSet warnings) {
656 if (element.equals("rocket")) {
659 .fromString("Multiple rocket designs within one document, "
660 + "ignoring later ones."));
663 rocketDefined = true;
664 return new ComponentParameterHandler(rocket, context);
667 if (element.equals("simulations")) {
668 if (simulationsDefined) {
670 .fromString("Multiple simulation definitions within one document, "
671 + "ignoring later ones."));
674 simulationsDefined = true;
675 return new SimulationsHandler(doc, context);
678 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
688 * A handler that creates components from the corresponding elements. The control of the
689 * contents is passed on to ComponentParameterHandler.
691 class ComponentHandler extends ElementHandler {
692 private final DocumentLoadingContext context;
693 private final RocketComponent parent;
695 public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) {
696 this.parent = parent;
697 this.context = context;
701 public ElementHandler openElement(String element, HashMap<String, String> attributes,
702 WarningSet warnings) {
704 // Attempt to construct new component
705 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
707 if (constructor == null) {
708 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
714 c = constructor.newInstance();
715 } catch (InstantiationException e) {
716 throw new BugException("Error constructing component.", e);
717 } catch (IllegalAccessException e) {
718 throw new BugException("Error constructing component.", e);
719 } catch (InvocationTargetException e) {
720 throw Reflection.handleWrappedException(e);
725 return new ComponentParameterHandler(c, context);
731 * A handler that populates the parameters of a previously constructed rocket component.
732 * This uses the setters, or delegates the handling to another handler for specific
735 class ComponentParameterHandler extends ElementHandler {
736 private final DocumentLoadingContext context;
737 private final RocketComponent component;
739 public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) {
741 this.context = context;
745 public ElementHandler openElement(String element, HashMap<String, String> attributes,
746 WarningSet warnings) {
748 // Check for specific elements that contain other elements
749 if (element.equals("subcomponents")) {
750 return new ComponentHandler(component, context);
752 if (element.equals("motormount")) {
753 if (!(component instanceof MotorMount)) {
754 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
757 return new MotorMountHandler((MotorMount) component, context);
759 if (element.equals("finpoints")) {
760 if (!(component instanceof FreeformFinSet)) {
761 warnings.add(Warning.fromString("Illegal component defined for fin points."));
764 return new FinSetPointHandler((FreeformFinSet) component, context);
766 if (element.equals("motorconfiguration")) {
767 if (!(component instanceof Rocket)) {
768 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
771 return new MotorConfigurationHandler((Rocket) component, context);
775 return PlainTextHandler.INSTANCE;
779 public void closeElement(String element, HashMap<String, String> attributes,
780 String content, WarningSet warnings) {
782 if (element.equals("subcomponents") || element.equals("motormount") ||
783 element.equals("finpoints") || element.equals("motorconfiguration")) {
787 // Search for the correct setter class
790 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
791 String setterKey = c.getSimpleName() + ":" + element;
792 Setter s = DocumentConfig.setters.get(setterKey);
795 s.set(component, content, attributes, warnings);
798 if (DocumentConfig.setters.containsKey(setterKey)) {
799 // Key exists but is null -> invalid parameter
805 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
806 + component.getComponentName() + ", ignoring."));
813 * A handler that reads the <point> specifications within the freeformfinset's
814 * <finpoints> elements.
816 class FinSetPointHandler extends ElementHandler {
817 @SuppressWarnings("unused")
818 private final DocumentLoadingContext context;
819 private final FreeformFinSet finset;
820 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
822 public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) {
823 this.finset = finset;
824 this.context = context;
828 public ElementHandler openElement(String element, HashMap<String, String> attributes,
829 WarningSet warnings) {
830 return PlainTextHandler.INSTANCE;
835 public void closeElement(String element, HashMap<String, String> attributes,
836 String content, WarningSet warnings) throws SAXException {
838 String strx = attributes.remove("x");
839 String stry = attributes.remove("y");
840 if (strx == null || stry == null) {
841 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
845 double x = Double.parseDouble(strx);
846 double y = Double.parseDouble(stry);
847 coordinates.add(new Coordinate(x, y));
848 } catch (NumberFormatException e) {
849 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
853 super.closeElement(element, attributes, content, warnings);
857 public void endHandler(String element, HashMap<String, String> attributes,
858 String content, WarningSet warnings) {
860 finset.setPoints(coordinates.toArray(new Coordinate[0]));
861 } catch (IllegalFinPointException e) {
862 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
868 class MotorMountHandler extends ElementHandler {
869 private final DocumentLoadingContext context;
870 private final MotorMount mount;
871 private MotorHandler motorHandler;
873 public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) {
875 this.context = context;
876 mount.setMotorMount(true);
880 public ElementHandler openElement(String element, HashMap<String, String> attributes,
881 WarningSet warnings) {
883 if (element.equals("motor")) {
884 motorHandler = new MotorHandler(context);
888 if (element.equals("ignitionevent") ||
889 element.equals("ignitiondelay") ||
890 element.equals("overhang")) {
891 return PlainTextHandler.INSTANCE;
894 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
901 public void closeElement(String element, HashMap<String, String> attributes,
902 String content, WarningSet warnings) throws SAXException {
904 if (element.equals("motor")) {
905 String id = attributes.get("configid");
906 if (id == null || id.equals("")) {
907 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
911 Motor motor = motorHandler.getMotor(warnings);
912 mount.setMotor(id, motor);
913 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
917 if (element.equals("ignitionevent")) {
918 MotorMount.IgnitionEvent event = null;
919 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
920 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
926 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
929 mount.setIgnitionEvent(event);
933 if (element.equals("ignitiondelay")) {
936 d = Double.parseDouble(content);
937 } catch (NumberFormatException nfe) {
938 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
941 mount.setIgnitionDelay(d);
945 if (element.equals("overhang")) {
948 d = Double.parseDouble(content);
949 } catch (NumberFormatException nfe) {
950 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
953 mount.setMotorOverhang(d);
957 super.closeElement(element, attributes, content, warnings);
964 class MotorConfigurationHandler extends ElementHandler {
965 @SuppressWarnings("unused")
966 private final DocumentLoadingContext context;
967 private final Rocket rocket;
968 private String name = null;
969 private boolean inNameElement = false;
971 public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) {
972 this.rocket = rocket;
973 this.context = context;
977 public ElementHandler openElement(String element, HashMap<String, String> attributes,
978 WarningSet warnings) {
980 if (inNameElement || !element.equals("name")) {
981 warnings.add(Warning.FILE_INVALID_PARAMETER);
984 inNameElement = true;
986 return PlainTextHandler.INSTANCE;
990 public void closeElement(String element, HashMap<String, String> attributes,
991 String content, WarningSet warnings) {
996 public void endHandler(String element, HashMap<String, String> attributes,
997 String content, WarningSet warnings) throws SAXException {
999 String configid = attributes.remove("configid");
1000 if (configid == null || configid.equals("")) {
1001 warnings.add(Warning.FILE_INVALID_PARAMETER);
1005 if (!rocket.addMotorConfigurationID(configid)) {
1006 warnings.add("Duplicate motor configuration ID used.");
1010 if (name != null && name.trim().length() > 0) {
1011 rocket.setMotorConfigurationName(configid, name);
1014 if ("true".equals(attributes.remove("default"))) {
1015 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
1018 super.closeElement(element, attributes, content, warnings);
1023 class MotorHandler extends ElementHandler {
1024 /** File version where latest digest format was introduced */
1025 private static final int MOTOR_DIGEST_VERSION = 104;
1027 private final DocumentLoadingContext context;
1028 private Motor.Type type = null;
1029 private String manufacturer = null;
1030 private String designation = null;
1031 private String digest = null;
1032 private double diameter = Double.NaN;
1033 private double length = Double.NaN;
1034 private double delay = Double.NaN;
1036 public MotorHandler(DocumentLoadingContext context) {
1037 this.context = context;
1042 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1043 WarningSet warnings) {
1044 return PlainTextHandler.INSTANCE;
1049 * Return the motor to use, or null.
1051 public Motor getMotor(WarningSet warnings) {
1052 return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings);
1056 * Return the delay to use for the motor.
1058 public double getDelay(WarningSet warnings) {
1059 if (Double.isNaN(delay)) {
1060 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1061 return Motor.PLUGGED;
1068 public void closeElement(String element, HashMap<String, String> attributes,
1069 String content, WarningSet warnings) throws SAXException {
1071 content = content.trim();
1073 if (element.equals("type")) {
1077 for (Motor.Type t : Motor.Type.values()) {
1078 if (t.name().toLowerCase().equals(content.trim())) {
1084 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1087 } else if (element.equals("manufacturer")) {
1090 manufacturer = content.trim();
1092 } else if (element.equals("designation")) {
1095 designation = content.trim();
1097 } else if (element.equals("digest")) {
1099 // Digest is used only for file versions saved using the same digest algorithm
1100 if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) {
1101 digest = content.trim();
1104 } else if (element.equals("diameter")) {
1107 diameter = Double.NaN;
1109 diameter = Double.parseDouble(content.trim());
1110 } catch (NumberFormatException e) {
1113 if (Double.isNaN(diameter)) {
1114 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1117 } else if (element.equals("length")) {
1120 length = Double.NaN;
1122 length = Double.parseDouble(content.trim());
1123 } catch (NumberFormatException ignore) {
1126 if (Double.isNaN(length)) {
1127 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1130 } else if (element.equals("delay")) {
1134 if (content.equals("none")) {
1135 delay = Motor.PLUGGED;
1138 delay = Double.parseDouble(content.trim());
1139 } catch (NumberFormatException ignore) {
1142 if (Double.isNaN(delay)) {
1143 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1149 super.closeElement(element, attributes, content, warnings);
1157 class SimulationsHandler extends ElementHandler {
1158 private final DocumentLoadingContext context;
1159 private final OpenRocketDocument doc;
1160 private SingleSimulationHandler handler;
1162 public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1164 this.context = context;
1168 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1169 WarningSet warnings) {
1171 if (!element.equals("simulation")) {
1172 warnings.add("Unknown element '" + element + "', ignoring.");
1176 handler = new SingleSimulationHandler(doc, context);
1181 public void closeElement(String element, HashMap<String, String> attributes,
1182 String content, WarningSet warnings) throws SAXException {
1183 attributes.remove("status");
1184 super.closeElement(element, attributes, content, warnings);
1190 class SingleSimulationHandler extends ElementHandler {
1191 private final DocumentLoadingContext context;
1193 private final OpenRocketDocument doc;
1195 private String name;
1197 private SimulationConditionsHandler conditionHandler;
1198 private FlightDataHandler dataHandler;
1200 private final List<String> listeners = new ArrayList<String>();
1202 public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1204 this.context = context;
1210 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1211 WarningSet warnings) {
1213 if (element.equals("name") || element.equals("simulator") ||
1214 element.equals("calculator") || element.equals("listener")) {
1215 return PlainTextHandler.INSTANCE;
1216 } else if (element.equals("conditions")) {
1217 conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context);
1218 return conditionHandler;
1219 } else if (element.equals("flightdata")) {
1220 dataHandler = new FlightDataHandler(context);
1223 warnings.add("Unknown element '" + element + "', ignoring.");
1229 public void closeElement(String element, HashMap<String, String> attributes,
1230 String content, WarningSet warnings) {
1232 if (element.equals("name")) {
1234 } else if (element.equals("simulator")) {
1235 if (!content.trim().equals("RK4Simulator")) {
1236 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1238 } else if (element.equals("calculator")) {
1239 if (!content.trim().equals("BarrowmanCalculator")) {
1240 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1242 } else if (element.equals("listener") && content.trim().length() > 0) {
1243 listeners.add(content.trim());
1249 public void endHandler(String element, HashMap<String, String> attributes,
1250 String content, WarningSet warnings) {
1252 String s = attributes.get("status");
1253 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1254 if (status == null) {
1255 warnings.add("Simulation status unknown, assuming outdated.");
1256 status = Simulation.Status.OUTDATED;
1259 SimulationOptions conditions;
1260 if (conditionHandler != null) {
1261 conditions = conditionHandler.getConditions();
1263 warnings.add("Simulation conditions not defined, using defaults.");
1264 conditions = new SimulationOptions(doc.getRocket());
1268 name = "Simulation";
1271 if (dataHandler == null)
1274 data = dataHandler.getFlightData();
1276 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1277 conditions, listeners, data);
1279 doc.addSimulation(simulation);
1285 class SimulationConditionsHandler extends ElementHandler {
1286 private final DocumentLoadingContext context;
1287 private SimulationOptions conditions;
1288 private AtmosphereHandler atmosphereHandler;
1290 public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) {
1291 this.context = context;
1292 conditions = new SimulationOptions(rocket);
1293 // Set up default loading settings (which may differ from the new defaults)
1294 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
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"), context);
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 @SuppressWarnings("unused")
1399 private final DocumentLoadingContext context;
1400 private final String model;
1401 private double temperature = Double.NaN;
1402 private double pressure = Double.NaN;
1404 public AtmosphereHandler(String model, DocumentLoadingContext context) {
1406 this.context = context;
1410 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1411 WarningSet warnings) {
1412 return PlainTextHandler.INSTANCE;
1416 public void closeElement(String element, HashMap<String, String> attributes,
1417 String content, WarningSet warnings) throws SAXException {
1419 double d = Double.NaN;
1421 d = Double.parseDouble(content);
1422 } catch (NumberFormatException ignore) {
1425 if (element.equals("basetemperature")) {
1426 if (Double.isNaN(d)) {
1427 warnings.add("Illegal base temperature specified, ignoring.");
1430 } else if (element.equals("basepressure")) {
1431 if (Double.isNaN(d)) {
1432 warnings.add("Illegal base pressure specified, ignoring.");
1436 super.closeElement(element, attributes, content, warnings);
1441 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1442 if (!Double.isNaN(pressure)) {
1443 cond.setLaunchPressure(pressure);
1445 if (!Double.isNaN(temperature)) {
1446 cond.setLaunchTemperature(temperature);
1449 if ("isa".equals(model)) {
1450 cond.setISAAtmosphere(true);
1451 } else if ("extendedisa".equals(model)) {
1452 cond.setISAAtmosphere(false);
1454 cond.setISAAtmosphere(true);
1455 warnings.add("Unknown atmospheric model, using ISA.");
1462 class FlightDataHandler extends ElementHandler {
1463 private final DocumentLoadingContext context;
1465 private FlightDataBranchHandler dataHandler;
1466 private WarningSet warningSet = new WarningSet();
1467 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1469 private FlightData data;
1472 public FlightDataHandler(DocumentLoadingContext context) {
1473 this.context = context;
1476 public FlightData getFlightData() {
1481 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1482 WarningSet warnings) {
1484 if (element.equals("warning")) {
1485 return PlainTextHandler.INSTANCE;
1487 if (element.equals("databranch")) {
1488 if (attributes.get("name") == null || attributes.get("types") == null) {
1489 warnings.add("Illegal flight data definition, ignoring.");
1492 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1493 attributes.get("types"), context);
1497 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1503 public void closeElement(String element, HashMap<String, String> attributes,
1504 String content, WarningSet warnings) {
1506 if (element.equals("databranch")) {
1507 FlightDataBranch branch = dataHandler.getBranch();
1508 if (branch.getLength() > 0) {
1509 branches.add(branch);
1511 } else if (element.equals("warning")) {
1512 warningSet.add(Warning.fromString(content));
1518 public void endHandler(String element, HashMap<String, String> attributes,
1519 String content, WarningSet warnings) {
1521 if (branches.size() > 0) {
1522 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1524 double maxAltitude = Double.NaN;
1525 double maxVelocity = Double.NaN;
1526 double maxAcceleration = Double.NaN;
1527 double maxMach = Double.NaN;
1528 double timeToApogee = Double.NaN;
1529 double flightTime = Double.NaN;
1530 double groundHitVelocity = Double.NaN;
1531 double launchRodVelocity = Double.NaN;
1532 double deploymentVelocity = Double.NaN;
1535 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1536 } catch (NumberFormatException ignore) {
1539 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1540 } catch (NumberFormatException ignore) {
1543 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1544 } catch (NumberFormatException ignore) {
1547 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1548 } catch (NumberFormatException ignore) {
1551 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1552 } catch (NumberFormatException ignore) {
1555 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1556 } catch (NumberFormatException ignore) {
1560 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1561 } catch (NumberFormatException ignore) {
1564 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1565 } catch (NumberFormatException ignore) {
1568 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1569 } catch (NumberFormatException ignore) {
1572 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1573 timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1576 data.getWarningSet().addAll(warningSet);
1584 class FlightDataBranchHandler extends ElementHandler {
1585 @SuppressWarnings("unused")
1586 private final DocumentLoadingContext context;
1587 private final FlightDataType[] types;
1588 private final FlightDataBranch branch;
1590 public FlightDataBranchHandler(String name, String typeList, DocumentLoadingContext context) {
1591 this.context = context;
1592 String[] split = typeList.split(",");
1593 types = new FlightDataType[split.length];
1594 for (int i = 0; i < split.length; i++) {
1595 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1598 // TODO: LOW: May throw an IllegalArgumentException
1599 branch = new FlightDataBranch(name, types);
1602 public FlightDataBranch getBranch() {
1608 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1609 WarningSet warnings) {
1611 if (element.equals("datapoint"))
1612 return PlainTextHandler.INSTANCE;
1613 if (element.equals("event"))
1614 return PlainTextHandler.INSTANCE;
1616 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1622 public void closeElement(String element, HashMap<String, String> attributes,
1623 String content, WarningSet warnings) {
1625 if (element.equals("event")) {
1627 FlightEvent.Type type;
1630 time = DocumentConfig.stringToDouble(attributes.get("time"));
1631 } catch (NumberFormatException e) {
1632 warnings.add("Illegal event specification, ignoring.");
1636 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1638 warnings.add("Illegal event specification, ignoring.");
1642 branch.addEvent(new FlightEvent(type, time));
1646 if (!element.equals("datapoint")) {
1647 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1651 // element == "datapoint"
1654 // Check line format
1655 String[] split = content.split(",");
1656 if (split.length != types.length) {
1657 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1661 // Parse the doubles
1662 double[] values = new double[split.length];
1663 for (int i = 0; i < values.length; i++) {
1665 values[i] = DocumentConfig.stringToDouble(split[i]);
1666 } catch (NumberFormatException e) {
1667 warnings.add("Data point format error, ignoring point.");
1672 // Add point to branch
1674 for (int i = 0; i < types.length; i++) {
1675 branch.setValue(types[i], values[i]);
1684 ///////////////// Setters implementation
1690 * Set the specified value to the given component.
1692 * @param component the component to which to set.
1693 * @param value the value within the element.
1694 * @param attributes attributes for the element.
1695 * @param warnings the warning set to use.
1697 public void set(RocketComponent component, String value,
1698 HashMap<String, String> attributes, WarningSet warnings);
1702 //// StringSetter - sets the value to the contained String
1703 class StringSetter implements Setter {
1704 private final Reflection.Method setMethod;
1706 public StringSetter(Reflection.Method set) {
1711 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1712 WarningSet warnings) {
1713 setMethod.invoke(c, s);
1717 //// IntSetter - set an integer value
1718 class IntSetter implements Setter {
1719 private final Reflection.Method setMethod;
1721 public IntSetter(Reflection.Method set) {
1726 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1727 WarningSet warnings) {
1729 int n = Integer.parseInt(s);
1730 setMethod.invoke(c, n);
1731 } catch (NumberFormatException e) {
1732 warnings.add(Warning.FILE_INVALID_PARAMETER);
1738 //// BooleanSetter - set a boolean value
1739 class BooleanSetter implements Setter {
1740 private final Reflection.Method setMethod;
1742 public BooleanSetter(Reflection.Method set) {
1747 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1748 WarningSet warnings) {
1751 if (s.equalsIgnoreCase("true")) {
1752 setMethod.invoke(c, true);
1753 } else if (s.equalsIgnoreCase("false")) {
1754 setMethod.invoke(c, false);
1756 warnings.add(Warning.FILE_INVALID_PARAMETER);
1763 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1764 //// calls a setXXX(boolean) method.
1765 class DoubleSetter implements Setter {
1766 private final Reflection.Method setMethod;
1767 private final String specialString;
1768 private final Reflection.Method specialMethod;
1769 private final double multiplier;
1772 * Set only the double value.
1773 * @param set set method for the double value.
1775 public DoubleSetter(Reflection.Method set) {
1776 this.setMethod = set;
1777 this.specialString = null;
1778 this.specialMethod = null;
1779 this.multiplier = 1.0;
1783 * Multiply with the given multiplier and set the double value.
1784 * @param set set method for the double value.
1785 * @param mul multiplier.
1787 public DoubleSetter(Reflection.Method set, double mul) {
1788 this.setMethod = set;
1789 this.specialString = null;
1790 this.specialMethod = null;
1791 this.multiplier = mul;
1795 * Set the double value, or if the value equals the special string, use the
1796 * special setter and set it to true.
1798 * @param set double setter.
1799 * @param special special string
1800 * @param specialMethod boolean setter.
1802 public DoubleSetter(Reflection.Method set, String special,
1803 Reflection.Method specialMethod) {
1804 this.setMethod = set;
1805 this.specialString = special;
1806 this.specialMethod = specialMethod;
1807 this.multiplier = 1.0;
1812 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1813 WarningSet warnings) {
1817 // Check for special case
1818 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1819 specialMethod.invoke(c, true);
1825 double d = Double.parseDouble(s);
1826 setMethod.invoke(c, d * multiplier);
1827 } catch (NumberFormatException e) {
1828 warnings.add(Warning.FILE_INVALID_PARAMETER);
1834 class OverrideSetter implements Setter {
1835 private final Reflection.Method setMethod;
1836 private final Reflection.Method enabledMethod;
1838 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1839 this.setMethod = set;
1840 this.enabledMethod = enabledMethod;
1844 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1845 WarningSet warnings) {
1848 double d = Double.parseDouble(s);
1849 setMethod.invoke(c, d);
1850 enabledMethod.invoke(c, true);
1851 } catch (NumberFormatException e) {
1852 warnings.add(Warning.FILE_INVALID_PARAMETER);
1857 //// EnumSetter - sets a generic enum type
1858 class EnumSetter<T extends Enum<T>> implements Setter {
1859 private final Reflection.Method setter;
1860 private final Class<T> enumClass;
1862 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1864 this.enumClass = enumClass;
1868 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1869 WarningSet warnings) {
1871 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1872 if (setEnum == null) {
1873 warnings.add(Warning.FILE_INVALID_PARAMETER);
1877 setter.invoke(c, setEnum);
1882 //// ColorSetter - sets a Color value
1883 class ColorSetter implements Setter {
1884 private final Reflection.Method setMethod;
1886 public ColorSetter(Reflection.Method set) {
1891 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1892 WarningSet warnings) {
1894 String red = attributes.get("red");
1895 String green = attributes.get("green");
1896 String blue = attributes.get("blue");
1898 if (red == null || green == null || blue == null) {
1899 warnings.add(Warning.FILE_INVALID_PARAMETER);
1905 r = Integer.parseInt(red);
1906 g = Integer.parseInt(green);
1907 b = Integer.parseInt(blue);
1908 } catch (NumberFormatException e) {
1909 warnings.add(Warning.FILE_INVALID_PARAMETER);
1913 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1914 warnings.add(Warning.FILE_INVALID_PARAMETER);
1918 Color color = new Color(r, g, b);
1919 setMethod.invoke(c, color);
1921 if (!s.trim().equals("")) {
1922 warnings.add(Warning.FILE_INVALID_PARAMETER);
1929 class MaterialSetter implements Setter {
1930 private final Reflection.Method setMethod;
1931 private final Material.Type type;
1933 public MaterialSetter(Reflection.Method set, Material.Type type) {
1934 this.setMethod = set;
1939 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1940 WarningSet warnings) {
1946 if (name.equals("")) {
1947 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1954 str = attributes.remove("density");
1956 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1960 density = Double.parseDouble(str);
1961 } catch (NumberFormatException e) {
1962 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1967 // double thickness = 0;
1968 // str = attributes.remove("thickness");
1971 // thickness = Double.parseDouble(str);
1972 // } catch (NumberFormatException e){
1973 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1977 // Check type if specified
1978 str = attributes.remove("type");
1979 if (str != null && !type.name().toLowerCase().equals(str)) {
1980 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1984 mat = Databases.findMaterial(type, name, density, false);
1986 setMethod.invoke(c, mat);
1993 class PositionSetter implements Setter {
1996 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1997 WarningSet warnings) {
1999 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
2000 RocketComponent.Position.class);
2002 warnings.add(Warning.FILE_INVALID_PARAMETER);
2008 pos = Double.parseDouble(value);
2009 } catch (NumberFormatException e) {
2010 warnings.add(Warning.FILE_INVALID_PARAMETER);
2014 if (c instanceof FinSet) {
2015 ((FinSet) c).setRelativePosition(type);
2016 c.setPositionValue(pos);
2017 } else if (c instanceof LaunchLug) {
2018 ((LaunchLug) c).setRelativePosition(type);
2019 c.setPositionValue(pos);
2020 } else if (c instanceof InternalComponent) {
2021 ((InternalComponent) c).setRelativePosition(type);
2022 c.setPositionValue(pos);
2024 warnings.add(Warning.FILE_INVALID_PARAMETER);
2031 class FinTabPositionSetter extends DoubleSetter {
2033 public FinTabPositionSetter() {
2034 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2038 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2039 WarningSet warnings) {
2041 if (!(c instanceof FinSet)) {
2042 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2045 String relative = attributes.get("relativeto");
2046 FinSet.TabRelativePosition position =
2047 (TabRelativePosition) DocumentConfig.findEnum(relative,
2048 FinSet.TabRelativePosition.class);
2050 if (position != null) {
2052 ((FinSet) c).setTabRelativePosition(position);
2055 if (relative == null) {
2056 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2058 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2062 super.set(c, s, attributes, warnings);
2069 class ClusterConfigurationSetter implements Setter {
2072 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2073 WarningSet warnings) {
2075 if (!(component instanceof Clusterable)) {
2076 warnings.add("Illegal component defined as cluster.");
2080 ClusterConfiguration config = null;
2081 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2082 if (c.getXMLName().equals(value)) {
2088 if (config == null) {
2089 warnings.add("Illegal cluster configuration specified.");
2093 ((Clusterable) component).setClusterConfiguration(config);