1 package net.sf.openrocket.file.openrocket;
3 import net.sf.openrocket.aerodynamics.Warning;
4 import net.sf.openrocket.aerodynamics.WarningSet;
5 import net.sf.openrocket.database.Databases;
6 import net.sf.openrocket.document.OpenRocketDocument;
7 import net.sf.openrocket.document.Simulation;
8 import net.sf.openrocket.document.Simulation.Status;
9 import net.sf.openrocket.document.StorageOptions;
10 import net.sf.openrocket.file.RocketLoadException;
11 import net.sf.openrocket.file.RocketLoader;
12 import net.sf.openrocket.file.simplesax.ElementHandler;
13 import net.sf.openrocket.file.simplesax.PlainTextHandler;
14 import net.sf.openrocket.file.simplesax.SimpleSAX;
15 import net.sf.openrocket.logging.LogHelper;
16 import net.sf.openrocket.material.Material;
17 import net.sf.openrocket.motor.Motor;
18 import net.sf.openrocket.motor.MotorDigest;
19 import net.sf.openrocket.motor.ThrustCurveMotor;
20 import net.sf.openrocket.rocketcomponent.BodyComponent;
21 import net.sf.openrocket.rocketcomponent.BodyTube;
22 import net.sf.openrocket.rocketcomponent.Bulkhead;
23 import net.sf.openrocket.rocketcomponent.CenteringRing;
24 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
25 import net.sf.openrocket.rocketcomponent.Clusterable;
26 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
27 import net.sf.openrocket.rocketcomponent.EngineBlock;
28 import net.sf.openrocket.rocketcomponent.ExternalComponent;
29 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
30 import net.sf.openrocket.rocketcomponent.FinSet;
31 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
32 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
33 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
34 import net.sf.openrocket.rocketcomponent.InnerTube;
35 import net.sf.openrocket.rocketcomponent.InternalComponent;
36 import net.sf.openrocket.rocketcomponent.LaunchLug;
37 import net.sf.openrocket.rocketcomponent.MassComponent;
38 import net.sf.openrocket.rocketcomponent.MassObject;
39 import net.sf.openrocket.rocketcomponent.MotorMount;
40 import net.sf.openrocket.rocketcomponent.NoseCone;
41 import net.sf.openrocket.rocketcomponent.Parachute;
42 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
43 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
44 import net.sf.openrocket.rocketcomponent.ReferenceType;
45 import net.sf.openrocket.rocketcomponent.RingComponent;
46 import net.sf.openrocket.rocketcomponent.Rocket;
47 import net.sf.openrocket.rocketcomponent.RocketComponent;
48 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
49 import net.sf.openrocket.rocketcomponent.ShockCord;
50 import net.sf.openrocket.rocketcomponent.Stage;
51 import net.sf.openrocket.rocketcomponent.Streamer;
52 import net.sf.openrocket.rocketcomponent.StructuralComponent;
53 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
54 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
55 import net.sf.openrocket.rocketcomponent.Transition;
56 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
57 import net.sf.openrocket.rocketcomponent.TubeCoupler;
58 import net.sf.openrocket.simulation.FlightData;
59 import net.sf.openrocket.simulation.FlightDataBranch;
60 import net.sf.openrocket.simulation.FlightDataType;
61 import net.sf.openrocket.simulation.FlightEvent;
62 import net.sf.openrocket.simulation.FlightEvent.Type;
63 import net.sf.openrocket.simulation.GUISimulationConditions;
64 import net.sf.openrocket.startup.Application;
65 import net.sf.openrocket.unit.UnitGroup;
66 import net.sf.openrocket.util.BugException;
67 import net.sf.openrocket.util.Coordinate;
68 import net.sf.openrocket.util.LineStyle;
69 import net.sf.openrocket.util.Reflection;
70 import org.xml.sax.InputSource;
71 import org.xml.sax.SAXException;
73 import java.awt.Color;
74 import java.io.IOException;
75 import java.io.InputStream;
76 import java.lang.reflect.Constructor;
77 import java.lang.reflect.InvocationTargetException;
78 import java.util.ArrayList;
79 import java.util.HashMap;
80 import java.util.List;
84 * Class that loads a rocket definition from an OpenRocket rocket file.
86 * This class uses SAX to read the XML file format. The
87 * {@link #loadFromStream(InputStream)} method simply sets the system up and
88 * starts the parsing, while the actual logic is in the private inner class
89 * <code>OpenRocketHandler</code>.
91 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
93 public class OpenRocketLoader extends RocketLoader {
94 private static final LogHelper log = Application.getLogger();
98 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
100 log.info("Loading .ork file");
102 InputSource xmlSource = new InputSource(source);
103 OpenRocketHandler handler = new OpenRocketHandler();
107 SimpleSAX.readXML(xmlSource, handler, warnings);
108 } catch (SAXException e) {
109 log.warn("Malformed XML in input");
110 throw new RocketLoadException("Malformed XML in input.", e);
114 OpenRocketDocument doc = handler.getDocument();
115 doc.getDefaultConfiguration().setAllStages();
117 // Deduce suitable time skip
118 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
119 for (Simulation s : doc.getSimulations()) {
120 if (s.getStatus() == Simulation.Status.EXTERNAL ||
121 s.getStatus() == Simulation.Status.NOT_SIMULATED)
123 if (s.getSimulatedData() == null)
125 if (s.getSimulatedData().getBranchCount() == 0)
127 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
130 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
134 double previousTime = Double.NaN;
135 for (double time : list) {
136 if (time - previousTime < timeSkip)
137 timeSkip = time - previousTime;
142 timeSkip = Math.rint(timeSkip * 100) / 100;
144 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
145 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
146 doc.getDefaultStorageOptions().setExplicitlySet(false);
149 log.info("Loading done");
157 class DocumentConfig {
159 /* Remember to update OpenRocketSaver as well! */
160 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1", "1.2" };
163 //////// Component constructors
164 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
167 // External components
168 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
169 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
170 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
171 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
172 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
173 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
174 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
176 // Internal components
177 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
178 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
179 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
180 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
181 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
183 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
184 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
185 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
186 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
189 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
191 } catch (NoSuchMethodException e) {
192 throw new BugException(
193 "Error in constructing the 'constructors' HashMap.");
198 //////// Parameter setters
200 * The keys are of the form Class:param, where Class is the class name and param
201 * the element name. Setters are searched for in descending class order.
202 * A setter of null means setting the parameter is not allowed.
204 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
207 setters.put("RocketComponent:name", new StringSetter(
208 Reflection.findMethodStatic(RocketComponent.class, "setName", String.class)));
209 setters.put("RocketComponent:color", new ColorSetter(
210 Reflection.findMethodStatic(RocketComponent.class, "setColor", Color.class)));
211 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
212 Reflection.findMethodStatic(RocketComponent.class, "setLineStyle", LineStyle.class),
214 setters.put("RocketComponent:position", new PositionSetter());
215 setters.put("RocketComponent:overridemass", new OverrideSetter(
216 Reflection.findMethodStatic(RocketComponent.class, "setOverrideMass", double.class),
217 Reflection.findMethodStatic(RocketComponent.class, "setMassOverridden", boolean.class)));
218 setters.put("RocketComponent:overridecg", new OverrideSetter(
219 Reflection.findMethodStatic(RocketComponent.class, "setOverrideCGX", double.class),
220 Reflection.findMethodStatic(RocketComponent.class, "setCGOverridden", boolean.class)));
221 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
222 Reflection.findMethodStatic(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
223 setters.put("RocketComponent:comment", new StringSetter(
224 Reflection.findMethodStatic(RocketComponent.class, "setComment", String.class)));
227 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
228 Reflection.findMethodStatic(ExternalComponent.class, "setFinish", Finish.class),
230 setters.put("ExternalComponent:material", new MaterialSetter(
231 Reflection.findMethodStatic(ExternalComponent.class, "setMaterial", Material.class),
232 Material.Type.BULK));
235 setters.put("BodyComponent:length", new DoubleSetter(
236 Reflection.findMethodStatic(BodyComponent.class, "setLength", double.class)));
238 // SymmetricComponent
239 setters.put("SymmetricComponent:thickness", new DoubleSetter(
240 Reflection.findMethodStatic(SymmetricComponent.class, "setThickness", double.class),
242 Reflection.findMethodStatic(SymmetricComponent.class, "setFilled", boolean.class)));
245 setters.put("BodyTube:radius", new DoubleSetter(
246 Reflection.findMethodStatic(BodyTube.class, "setOuterRadius", double.class),
248 Reflection.findMethodStatic(BodyTube.class, "setRadiusAutomatic", boolean.class)));
251 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
252 Reflection.findMethodStatic(Transition.class, "setType", Transition.Shape.class),
253 Transition.Shape.class));
254 setters.put("Transition:shapeclipped", new BooleanSetter(
255 Reflection.findMethodStatic(Transition.class, "setClipped", boolean.class)));
256 setters.put("Transition:shapeparameter", new DoubleSetter(
257 Reflection.findMethodStatic(Transition.class, "setShapeParameter", double.class)));
259 setters.put("Transition:foreradius", new DoubleSetter(
260 Reflection.findMethodStatic(Transition.class, "setForeRadius", double.class),
262 Reflection.findMethodStatic(Transition.class, "setForeRadiusAutomatic", boolean.class)));
263 setters.put("Transition:aftradius", new DoubleSetter(
264 Reflection.findMethodStatic(Transition.class, "setAftRadius", double.class),
266 Reflection.findMethodStatic(Transition.class, "setAftRadiusAutomatic", boolean.class)));
268 setters.put("Transition:foreshoulderradius", new DoubleSetter(
269 Reflection.findMethodStatic(Transition.class, "setForeShoulderRadius", double.class)));
270 setters.put("Transition:foreshoulderlength", new DoubleSetter(
271 Reflection.findMethodStatic(Transition.class, "setForeShoulderLength", double.class)));
272 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
273 Reflection.findMethodStatic(Transition.class, "setForeShoulderThickness", double.class)));
274 setters.put("Transition:foreshouldercapped", new BooleanSetter(
275 Reflection.findMethodStatic(Transition.class, "setForeShoulderCapped", boolean.class)));
277 setters.put("Transition:aftshoulderradius", new DoubleSetter(
278 Reflection.findMethodStatic(Transition.class, "setAftShoulderRadius", double.class)));
279 setters.put("Transition:aftshoulderlength", new DoubleSetter(
280 Reflection.findMethodStatic(Transition.class, "setAftShoulderLength", double.class)));
281 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
282 Reflection.findMethodStatic(Transition.class, "setAftShoulderThickness", double.class)));
283 setters.put("Transition:aftshouldercapped", new BooleanSetter(
284 Reflection.findMethodStatic(Transition.class, "setAftShoulderCapped", boolean.class)));
286 // NoseCone - disable disallowed elements
287 setters.put("NoseCone:foreradius", null);
288 setters.put("NoseCone:foreshoulderradius", null);
289 setters.put("NoseCone:foreshoulderlength", null);
290 setters.put("NoseCone:foreshoulderthickness", null);
291 setters.put("NoseCone:foreshouldercapped", null);
294 setters.put("FinSet:fincount", new IntSetter(
295 Reflection.findMethodStatic(FinSet.class, "setFinCount", int.class)));
296 setters.put("FinSet:rotation", new DoubleSetter(
297 Reflection.findMethodStatic(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
298 setters.put("FinSet:thickness", new DoubleSetter(
299 Reflection.findMethodStatic(FinSet.class, "setThickness", double.class)));
300 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
301 Reflection.findMethodStatic(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
302 FinSet.CrossSection.class));
303 setters.put("FinSet:cant", new DoubleSetter(
304 Reflection.findMethodStatic(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
305 setters.put("FinSet:tabheight", new DoubleSetter(
306 Reflection.findMethodStatic(FinSet.class, "setTabHeight", double.class)));
307 setters.put("FinSet:tablength", new DoubleSetter(
308 Reflection.findMethodStatic(FinSet.class, "setTabLength", double.class)));
309 setters.put("FinSet:tabposition", new FinTabPositionSetter());
312 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
313 Reflection.findMethodStatic(TrapezoidFinSet.class, "setRootChord", double.class)));
314 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
315 Reflection.findMethodStatic(TrapezoidFinSet.class, "setTipChord", double.class)));
316 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
317 Reflection.findMethodStatic(TrapezoidFinSet.class, "setSweep", double.class)));
318 setters.put("TrapezoidFinSet:height", new DoubleSetter(
319 Reflection.findMethodStatic(TrapezoidFinSet.class, "setHeight", double.class)));
322 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
323 Reflection.findMethodStatic(EllipticalFinSet.class, "setLength", double.class)));
324 setters.put("EllipticalFinSet:height", new DoubleSetter(
325 Reflection.findMethodStatic(EllipticalFinSet.class, "setHeight", double.class)));
327 // FreeformFinSet points handled as a special handler
330 setters.put("LaunchLug:radius", new DoubleSetter(
331 Reflection.findMethodStatic(LaunchLug.class, "setOuterRadius", double.class)));
332 setters.put("LaunchLug:length", new DoubleSetter(
333 Reflection.findMethodStatic(LaunchLug.class, "setLength", double.class)));
334 setters.put("LaunchLug:thickness", new DoubleSetter(
335 Reflection.findMethodStatic(LaunchLug.class, "setThickness", double.class)));
336 setters.put("LaunchLug:radialdirection", new DoubleSetter(
337 Reflection.findMethodStatic(LaunchLug.class, "setRadialDirection", double.class),
340 // InternalComponent - nothing
342 // StructuralComponent
343 setters.put("StructuralComponent:material", new MaterialSetter(
344 Reflection.findMethodStatic(StructuralComponent.class, "setMaterial", Material.class),
345 Material.Type.BULK));
348 setters.put("RingComponent:length", new DoubleSetter(
349 Reflection.findMethodStatic(RingComponent.class, "setLength", double.class)));
350 setters.put("RingComponent:radialposition", new DoubleSetter(
351 Reflection.findMethodStatic(RingComponent.class, "setRadialPosition", double.class)));
352 setters.put("RingComponent:radialdirection", new DoubleSetter(
353 Reflection.findMethodStatic(RingComponent.class, "setRadialDirection", double.class),
356 // ThicknessRingComponent - radius on separate components due to differing automatics
357 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
358 Reflection.findMethodStatic(ThicknessRingComponent.class, "setThickness", double.class)));
361 setters.put("EngineBlock:outerradius", new DoubleSetter(
362 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadius", double.class),
364 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
367 setters.put("TubeCoupler:outerradius", new DoubleSetter(
368 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadius", double.class),
370 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
373 setters.put("InnerTube:outerradius", new DoubleSetter(
374 Reflection.findMethodStatic(InnerTube.class, "setOuterRadius", double.class)));
375 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
376 setters.put("InnerTube:clusterscale", new DoubleSetter(
377 Reflection.findMethodStatic(InnerTube.class, "setClusterScale", double.class)));
378 setters.put("InnerTube:clusterrotation", new DoubleSetter(
379 Reflection.findMethodStatic(InnerTube.class, "setClusterRotation", double.class),
382 // RadiusRingComponent
385 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
386 Reflection.findMethodStatic(RadiusRingComponent.class, "setInnerRadius", double.class)));
387 setters.put("Bulkhead:outerradius", new DoubleSetter(
388 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadius", double.class),
390 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
393 setters.put("CenteringRing:innerradius", new DoubleSetter(
394 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadius", double.class),
396 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
397 setters.put("CenteringRing:outerradius", new DoubleSetter(
398 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadius", double.class),
400 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
404 setters.put("MassObject:packedlength", new DoubleSetter(
405 Reflection.findMethodStatic(MassObject.class, "setLength", double.class)));
406 setters.put("MassObject:packedradius", new DoubleSetter(
407 Reflection.findMethodStatic(MassObject.class, "setRadius", double.class)));
408 setters.put("MassObject:radialposition", new DoubleSetter(
409 Reflection.findMethodStatic(MassObject.class, "setRadialPosition", double.class)));
410 setters.put("MassObject:radialdirection", new DoubleSetter(
411 Reflection.findMethodStatic(MassObject.class, "setRadialDirection", double.class),
415 setters.put("MassComponent:mass", new DoubleSetter(
416 Reflection.findMethodStatic(MassComponent.class, "setComponentMass", double.class)));
419 setters.put("ShockCord:cordlength", new DoubleSetter(
420 Reflection.findMethodStatic(ShockCord.class, "setCordLength", double.class)));
421 setters.put("ShockCord:material", new MaterialSetter(
422 Reflection.findMethodStatic(ShockCord.class, "setMaterial", Material.class),
423 Material.Type.LINE));
426 setters.put("RecoveryDevice:cd", new DoubleSetter(
427 Reflection.findMethodStatic(RecoveryDevice.class, "setCD", double.class),
429 Reflection.findMethodStatic(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
430 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
431 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
432 RecoveryDevice.DeployEvent.class));
433 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
434 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployAltitude", double.class)));
435 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
436 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployDelay", double.class)));
437 setters.put("RecoveryDevice:material", new MaterialSetter(
438 Reflection.findMethodStatic(RecoveryDevice.class, "setMaterial", Material.class),
439 Material.Type.SURFACE));
442 setters.put("Parachute:diameter", new DoubleSetter(
443 Reflection.findMethodStatic(Parachute.class, "setDiameter", double.class)));
444 setters.put("Parachute:linecount", new IntSetter(
445 Reflection.findMethodStatic(Parachute.class, "setLineCount", int.class)));
446 setters.put("Parachute:linelength", new DoubleSetter(
447 Reflection.findMethodStatic(Parachute.class, "setLineLength", double.class)));
448 setters.put("Parachute:linematerial", new MaterialSetter(
449 Reflection.findMethodStatic(Parachute.class, "setLineMaterial", Material.class),
450 Material.Type.LINE));
453 setters.put("Streamer:striplength", new DoubleSetter(
454 Reflection.findMethodStatic(Streamer.class, "setStripLength", double.class)));
455 setters.put("Streamer:stripwidth", new DoubleSetter(
456 Reflection.findMethodStatic(Streamer.class, "setStripWidth", double.class)));
459 // <motorconfiguration> handled by separate handler
460 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
461 Reflection.findMethodStatic(Rocket.class, "setReferenceType", ReferenceType.class),
462 ReferenceType.class));
463 setters.put("Rocket:customreference", new DoubleSetter(
464 Reflection.findMethodStatic(Rocket.class, "setCustomReferenceLength", double.class)));
465 setters.put("Rocket:designer", new StringSetter(
466 Reflection.findMethodStatic(Rocket.class, "setDesigner", String.class)));
467 setters.put("Rocket:revision", new StringSetter(
468 Reflection.findMethodStatic(Rocket.class, "setRevision", String.class)));
473 * Search for a enum value that has the corresponding name as an XML value. The current
474 * conversion from enum name to XML value is to lowercase the name and strip out all
475 * underscore characters. This method returns a match to these criteria, or <code>null</code>
476 * if no such enum exists.
478 * @param <T> then enum type.
479 * @param name the XML value, null ok.
480 * @param enumClass the class of the enum.
481 * @return the found enum value, or <code>null</code>.
483 public static <T extends Enum<T>> Enum<T> findEnum(String name,
484 Class<? extends Enum<T>> enumClass) {
489 for (Enum<T> e : enumClass.getEnumConstants()) {
490 if (e.name().toLowerCase().replace("_", "").equals(name)) {
499 * Convert a string to a double including formatting specifications of the OpenRocket
500 * file format. This accepts all formatting that is valid for
501 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
503 * @param s the string to parse.
504 * @return the numerical value.
505 * @throws NumberFormatException the the string cannot be parsed.
507 public static double stringToDouble(String s) throws NumberFormatException {
509 throw new NumberFormatException("null string");
510 if (s.equalsIgnoreCase("NaN"))
512 if (s.equalsIgnoreCase("Inf"))
513 return Double.POSITIVE_INFINITY;
514 if (s.equalsIgnoreCase("-Inf"))
515 return Double.NEGATIVE_INFINITY;
516 return Double.parseDouble(s);
525 * The starting point of the handlers. Accepts a single <openrocket> element and hands
526 * the contents to be read by a OpenRocketContentsHandler.
528 class OpenRocketHandler extends ElementHandler {
529 private OpenRocketContentHandler handler = null;
532 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
533 * has not been read yet.
535 * @return the document read, or null.
537 public OpenRocketDocument getDocument() {
538 return handler.getDocument();
542 public ElementHandler openElement(String element, HashMap<String, String> attributes,
543 WarningSet warnings) {
545 // Check for unknown elements
546 if (!element.equals("openrocket")) {
547 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
551 // Check for first call
552 if (handler != null) {
553 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
558 // Check version number
559 String version = null;
560 String creator = attributes.remove("creator");
561 String docVersion = attributes.remove("version");
562 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
563 if (v.equals(docVersion)) {
568 if (version == null) {
569 String str = "Unsupported document version";
570 if (docVersion != null)
571 str += " " + docVersion;
572 if (creator != null && !creator.trim().equals(""))
573 str += " (written using '" + creator.trim() + "')";
574 str += ", attempting to read file anyway.";
578 handler = new OpenRocketContentHandler();
583 public void closeElement(String element, HashMap<String, String> attributes,
584 String content, WarningSet warnings) throws SAXException {
585 attributes.remove("version");
586 attributes.remove("creator");
587 super.closeElement(element, attributes, content, warnings);
595 * Handles the content of the <openrocket> tag.
597 class OpenRocketContentHandler extends ElementHandler {
598 private final OpenRocketDocument doc;
599 private final Rocket rocket;
601 private boolean rocketDefined = false;
602 private boolean simulationsDefined = false;
604 public OpenRocketContentHandler() {
605 this.rocket = new Rocket();
606 this.doc = new OpenRocketDocument(rocket);
610 public OpenRocketDocument getDocument() {
617 public ElementHandler openElement(String element, HashMap<String, String> attributes,
618 WarningSet warnings) {
620 if (element.equals("rocket")) {
623 .fromString("Multiple rocket designs within one document, "
624 + "ignoring later ones."));
627 rocketDefined = true;
628 return new ComponentParameterHandler(rocket);
631 if (element.equals("simulations")) {
632 if (simulationsDefined) {
634 .fromString("Multiple simulation definitions within one document, "
635 + "ignoring later ones."));
638 simulationsDefined = true;
639 return new SimulationsHandler(doc);
642 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
652 * A handler that creates components from the corresponding elements. The control of the
653 * contents is passed on to ComponentParameterHandler.
655 class ComponentHandler extends ElementHandler {
656 private final RocketComponent parent;
658 public ComponentHandler(RocketComponent parent) {
659 this.parent = parent;
663 public ElementHandler openElement(String element, HashMap<String, String> attributes,
664 WarningSet warnings) {
666 // Attempt to construct new component
667 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
669 if (constructor == null) {
670 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
676 c = constructor.newInstance();
677 } catch (InstantiationException e) {
678 throw new BugException("Error constructing component.", e);
679 } catch (IllegalAccessException e) {
680 throw new BugException("Error constructing component.", e);
681 } catch (InvocationTargetException e) {
682 throw Reflection.handleWrappedException(e);
687 return new ComponentParameterHandler(c);
693 * A handler that populates the parameters of a previously constructed rocket component.
694 * This uses the setters, or delegates the handling to another handler for specific
697 class ComponentParameterHandler extends ElementHandler {
698 private final RocketComponent component;
700 public ComponentParameterHandler(RocketComponent c) {
705 public ElementHandler openElement(String element, HashMap<String, String> attributes,
706 WarningSet warnings) {
708 // Check for specific elements that contain other elements
709 if (element.equals("subcomponents")) {
710 return new ComponentHandler(component);
712 if (element.equals("motormount")) {
713 if (!(component instanceof MotorMount)) {
714 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
717 return new MotorMountHandler((MotorMount) component);
719 if (element.equals("finpoints")) {
720 if (!(component instanceof FreeformFinSet)) {
721 warnings.add(Warning.fromString("Illegal component defined for fin points."));
724 return new FinSetPointHandler((FreeformFinSet) component);
726 if (element.equals("motorconfiguration")) {
727 if (!(component instanceof Rocket)) {
728 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
731 return new MotorConfigurationHandler((Rocket) component);
735 return PlainTextHandler.INSTANCE;
739 public void closeElement(String element, HashMap<String, String> attributes,
740 String content, WarningSet warnings) {
742 if (element.equals("subcomponents") || element.equals("motormount") ||
743 element.equals("finpoints") || element.equals("motorconfiguration")) {
747 // Search for the correct setter class
750 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
751 String setterKey = c.getSimpleName() + ":" + element;
752 Setter s = DocumentConfig.setters.get(setterKey);
755 System.out.println("Calling with key " + setterKey);
756 s.set(component, content, attributes, warnings);
759 if (DocumentConfig.setters.containsKey(setterKey)) {
760 // Key exists but is null -> invalid parameter
766 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
767 + component.getComponentName() + ", ignoring."));
774 * A handler that reads the <point> specifications within the freeformfinset's
775 * <finpoints> elements.
777 class FinSetPointHandler extends ElementHandler {
778 private final FreeformFinSet finset;
779 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
781 public FinSetPointHandler(FreeformFinSet finset) {
782 this.finset = finset;
786 public ElementHandler openElement(String element, HashMap<String, String> attributes,
787 WarningSet warnings) {
788 return PlainTextHandler.INSTANCE;
793 public void closeElement(String element, HashMap<String, String> attributes,
794 String content, WarningSet warnings) throws SAXException {
796 String strx = attributes.remove("x");
797 String stry = attributes.remove("y");
798 if (strx == null || stry == null) {
799 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
803 double x = Double.parseDouble(strx);
804 double y = Double.parseDouble(stry);
805 coordinates.add(new Coordinate(x, y));
806 } catch (NumberFormatException e) {
807 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
811 super.closeElement(element, attributes, content, warnings);
815 public void endHandler(String element, HashMap<String, String> attributes,
816 String content, WarningSet warnings) {
818 finset.setPoints(coordinates.toArray(new Coordinate[0]));
819 } catch (IllegalFinPointException e) {
820 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
826 class MotorMountHandler extends ElementHandler {
827 private final MotorMount mount;
828 private MotorHandler motorHandler;
830 public MotorMountHandler(MotorMount mount) {
832 mount.setMotorMount(true);
836 public ElementHandler openElement(String element, HashMap<String, String> attributes,
837 WarningSet warnings) {
839 if (element.equals("motor")) {
840 motorHandler = new MotorHandler();
844 if (element.equals("ignitionevent") ||
845 element.equals("ignitiondelay") ||
846 element.equals("overhang")) {
847 return PlainTextHandler.INSTANCE;
850 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
857 public void closeElement(String element, HashMap<String, String> attributes,
858 String content, WarningSet warnings) throws SAXException {
860 if (element.equals("motor")) {
861 String id = attributes.get("configid");
862 if (id == null || id.equals("")) {
863 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
867 Motor motor = motorHandler.getMotor(warnings);
868 mount.setMotor(id, motor);
869 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
873 if (element.equals("ignitionevent")) {
874 MotorMount.IgnitionEvent event = null;
875 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
876 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
882 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
885 mount.setIgnitionEvent(event);
889 if (element.equals("ignitiondelay")) {
892 d = Double.parseDouble(content);
893 } catch (NumberFormatException nfe) {
894 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
897 mount.setIgnitionDelay(d);
901 if (element.equals("overhang")) {
904 d = Double.parseDouble(content);
905 } catch (NumberFormatException nfe) {
906 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
909 mount.setMotorOverhang(d);
913 super.closeElement(element, attributes, content, warnings);
920 class MotorConfigurationHandler extends ElementHandler {
921 private final Rocket rocket;
922 private String name = null;
923 private boolean inNameElement = false;
925 public MotorConfigurationHandler(Rocket rocket) {
926 this.rocket = rocket;
930 public ElementHandler openElement(String element, HashMap<String, String> attributes,
931 WarningSet warnings) {
933 if (inNameElement || !element.equals("name")) {
934 warnings.add(Warning.FILE_INVALID_PARAMETER);
937 inNameElement = true;
939 return PlainTextHandler.INSTANCE;
943 public void closeElement(String element, HashMap<String, String> attributes,
944 String content, WarningSet warnings) {
949 public void endHandler(String element, HashMap<String, String> attributes,
950 String content, WarningSet warnings) throws SAXException {
952 String configid = attributes.remove("configid");
953 if (configid == null || configid.equals("")) {
954 warnings.add(Warning.FILE_INVALID_PARAMETER);
958 if (!rocket.addMotorConfigurationID(configid)) {
959 warnings.add("Duplicate motor configuration ID used.");
963 if (name != null && name.trim().length() > 0) {
964 rocket.setMotorConfigurationName(configid, name);
967 if ("true".equals(attributes.remove("default"))) {
968 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
971 super.closeElement(element, attributes, content, warnings);
976 class MotorHandler extends ElementHandler {
977 private Motor.Type type = null;
978 private String manufacturer = null;
979 private String designation = null;
980 private String digest = null;
981 private double diameter = Double.NaN;
982 private double length = Double.NaN;
983 private double delay = Double.NaN;
986 public ElementHandler openElement(String element, HashMap<String, String> attributes,
987 WarningSet warnings) {
988 return PlainTextHandler.INSTANCE;
993 * Return the motor to use, or null.
995 public Motor getMotor(WarningSet warnings) {
996 if (designation == null) {
997 warnings.add(Warning.fromString("No motor specified, ignoring."));
1001 List<ThrustCurveMotor> motors = Application.getMotorSetDatabase().findMotors(type, manufacturer,
1002 designation, diameter, length);
1005 if (motors.size() == 0) {
1006 String str = "No motor with designation '" + designation + "'";
1007 if (manufacturer != null)
1008 str += " for manufacturer '" + manufacturer + "'";
1015 if (motors.size() == 1) {
1016 ThrustCurveMotor m = motors.get(0);
1017 if (digest != null && !MotorDigest.digestMotor(m).equals(digest)) {
1018 String str = "Motor with designation '" + designation + "'";
1019 if (manufacturer != null)
1020 str += " for manufacturer '" + manufacturer + "'";
1021 str += " has differing thrust curve than the original.";
1027 // Multiple motors, check digest for which one to use
1028 if (digest != null) {
1030 // Check for motor with correct digest
1031 for (ThrustCurveMotor m : motors) {
1032 if (MotorDigest.digestMotor(m).equals(digest)) {
1036 String str = "Motor with designation '" + designation + "'";
1037 if (manufacturer != null)
1038 str += " for manufacturer '" + manufacturer + "'";
1039 str += " has differing thrust curve than the original.";
1044 // No digest, check for preferred digest (OpenRocket <= 1.1.0)
1045 // TODO: MEDIUM: This should only be done for document versions 1.1 and below
1046 for (ThrustCurveMotor m : motors) {
1047 if (PreferredMotorDigests.DIGESTS.contains(MotorDigest.digestMotor(m))) {
1052 String str = "Multiple motors with designation '" + designation + "'";
1053 if (manufacturer != null)
1054 str += " for manufacturer '" + manufacturer + "'";
1055 str += " found, one chosen arbitrarily.";
1059 return motors.get(0);
1063 * Return the delay to use for the motor.
1065 public double getDelay(WarningSet warnings) {
1066 if (Double.isNaN(delay)) {
1067 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1068 return Motor.PLUGGED;
1075 public void closeElement(String element, HashMap<String, String> attributes,
1076 String content, WarningSet warnings) throws SAXException {
1078 content = content.trim();
1080 if (element.equals("type")) {
1084 for (Motor.Type t : Motor.Type.values()) {
1085 if (t.name().toLowerCase().equals(content.trim())) {
1091 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1094 } else if (element.equals("manufacturer")) {
1097 manufacturer = content.trim();
1099 } else if (element.equals("designation")) {
1102 designation = content.trim();
1104 } else if (element.equals("digest")) {
1107 digest = content.trim();
1109 } else if (element.equals("diameter")) {
1112 diameter = Double.NaN;
1114 diameter = Double.parseDouble(content.trim());
1115 } catch (NumberFormatException e) {
1118 if (Double.isNaN(diameter)) {
1119 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1122 } else if (element.equals("length")) {
1125 length = Double.NaN;
1127 length = Double.parseDouble(content.trim());
1128 } catch (NumberFormatException ignore) {
1131 if (Double.isNaN(length)) {
1132 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1135 } else if (element.equals("delay")) {
1139 if (content.equals("none")) {
1140 delay = Motor.PLUGGED;
1143 delay = Double.parseDouble(content.trim());
1144 } catch (NumberFormatException ignore) {
1147 if (Double.isNaN(delay)) {
1148 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1154 super.closeElement(element, attributes, content, warnings);
1162 class SimulationsHandler extends ElementHandler {
1163 private final OpenRocketDocument doc;
1164 private SingleSimulationHandler handler;
1166 public SimulationsHandler(OpenRocketDocument doc) {
1171 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1172 WarningSet warnings) {
1174 if (!element.equals("simulation")) {
1175 warnings.add("Unknown element '" + element + "', ignoring.");
1179 handler = new SingleSimulationHandler(doc);
1184 public void closeElement(String element, HashMap<String, String> attributes,
1185 String content, WarningSet warnings) throws SAXException {
1186 attributes.remove("status");
1187 super.closeElement(element, attributes, content, warnings);
1193 class SingleSimulationHandler extends ElementHandler {
1195 private final OpenRocketDocument doc;
1197 private String name;
1199 private SimulationConditionsHandler conditionHandler;
1200 private FlightDataHandler dataHandler;
1202 private final List<String> listeners = new ArrayList<String>();
1204 public SingleSimulationHandler(OpenRocketDocument doc) {
1211 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1212 WarningSet warnings) {
1214 if (element.equals("name") || element.equals("simulator") ||
1215 element.equals("calculator") || element.equals("listener")) {
1216 return PlainTextHandler.INSTANCE;
1217 } else if (element.equals("conditions")) {
1218 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1219 return conditionHandler;
1220 } else if (element.equals("flightdata")) {
1221 dataHandler = new FlightDataHandler();
1224 warnings.add("Unknown element '" + element + "', ignoring.");
1230 public void closeElement(String element, HashMap<String, String> attributes,
1231 String content, WarningSet warnings) {
1233 if (element.equals("name")) {
1235 } else if (element.equals("simulator")) {
1236 if (!content.trim().equals("RK4Simulator")) {
1237 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1239 } else if (element.equals("calculator")) {
1240 if (!content.trim().equals("BarrowmanCalculator")) {
1241 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1243 } else if (element.equals("listener") && content.trim().length() > 0) {
1244 listeners.add(content.trim());
1250 public void endHandler(String element, HashMap<String, String> attributes,
1251 String content, WarningSet warnings) {
1253 String s = attributes.get("status");
1254 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1255 if (status == null) {
1256 warnings.add("Simulation status unknown, assuming outdated.");
1257 status = Simulation.Status.OUTDATED;
1260 GUISimulationConditions conditions;
1261 if (conditionHandler != null) {
1262 conditions = conditionHandler.getConditions();
1264 warnings.add("Simulation conditions not defined, using defaults.");
1265 conditions = new GUISimulationConditions(doc.getRocket());
1269 name = "Simulation";
1272 if (dataHandler == null)
1275 data = dataHandler.getFlightData();
1277 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1278 conditions, listeners, data);
1280 doc.addSimulation(simulation);
1286 class SimulationConditionsHandler extends ElementHandler {
1287 private GUISimulationConditions conditions;
1288 private AtmosphereHandler atmosphereHandler;
1290 public SimulationConditionsHandler(Rocket rocket) {
1291 conditions = new GUISimulationConditions(rocket);
1294 public GUISimulationConditions getConditions() {
1299 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1300 WarningSet warnings) {
1301 if (element.equals("atmosphere")) {
1302 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1303 return atmosphereHandler;
1305 return PlainTextHandler.INSTANCE;
1309 public void closeElement(String element, HashMap<String, String> attributes,
1310 String content, WarningSet warnings) {
1312 double d = Double.NaN;
1314 d = Double.parseDouble(content);
1315 } catch (NumberFormatException ignore) {
1319 if (element.equals("configid")) {
1320 if (content.equals("")) {
1321 conditions.setMotorConfigurationID(null);
1323 conditions.setMotorConfigurationID(content);
1325 } else if (element.equals("launchrodlength")) {
1326 if (Double.isNaN(d)) {
1327 warnings.add("Illegal launch rod length defined, ignoring.");
1329 conditions.setLaunchRodLength(d);
1331 } else if (element.equals("launchrodangle")) {
1332 if (Double.isNaN(d)) {
1333 warnings.add("Illegal launch rod angle defined, ignoring.");
1335 conditions.setLaunchRodAngle(d * Math.PI / 180);
1337 } else if (element.equals("launchroddirection")) {
1338 if (Double.isNaN(d)) {
1339 warnings.add("Illegal launch rod direction defined, ignoring.");
1341 conditions.setLaunchRodDirection(d * Math.PI / 180);
1343 } else if (element.equals("windaverage")) {
1344 if (Double.isNaN(d)) {
1345 warnings.add("Illegal average windspeed defined, ignoring.");
1347 conditions.setWindSpeedAverage(d);
1349 } else if (element.equals("windturbulence")) {
1350 if (Double.isNaN(d)) {
1351 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1353 conditions.setWindTurbulenceIntensity(d);
1355 } else if (element.equals("launchaltitude")) {
1356 if (Double.isNaN(d)) {
1357 warnings.add("Illegal launch altitude defined, ignoring.");
1359 conditions.setLaunchAltitude(d);
1361 } else if (element.equals("launchlatitude")) {
1362 if (Double.isNaN(d)) {
1363 warnings.add("Illegal launch latitude defined, ignoring.");
1365 conditions.setLaunchLatitude(d);
1367 } else if (element.equals("atmosphere")) {
1368 atmosphereHandler.storeSettings(conditions, warnings);
1369 } else if (element.equals("timestep")) {
1370 if (Double.isNaN(d)) {
1371 warnings.add("Illegal time step defined, ignoring.");
1373 conditions.setTimeStep(d);
1380 class AtmosphereHandler extends ElementHandler {
1381 private final String model;
1382 private double temperature = Double.NaN;
1383 private double pressure = Double.NaN;
1385 public AtmosphereHandler(String model) {
1390 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1391 WarningSet warnings) {
1392 return PlainTextHandler.INSTANCE;
1396 public void closeElement(String element, HashMap<String, String> attributes,
1397 String content, WarningSet warnings) throws SAXException {
1399 double d = Double.NaN;
1401 d = Double.parseDouble(content);
1402 } catch (NumberFormatException ignore) {
1405 if (element.equals("basetemperature")) {
1406 if (Double.isNaN(d)) {
1407 warnings.add("Illegal base temperature specified, ignoring.");
1410 } else if (element.equals("basepressure")) {
1411 if (Double.isNaN(d)) {
1412 warnings.add("Illegal base pressure specified, ignoring.");
1416 super.closeElement(element, attributes, content, warnings);
1421 public void storeSettings(GUISimulationConditions cond, WarningSet warnings) {
1422 if (!Double.isNaN(pressure)) {
1423 cond.setLaunchPressure(pressure);
1425 if (!Double.isNaN(temperature)) {
1426 cond.setLaunchTemperature(temperature);
1429 if ("isa".equals(model)) {
1430 cond.setISAAtmosphere(true);
1431 } else if ("extendedisa".equals(model)) {
1432 cond.setISAAtmosphere(false);
1434 cond.setISAAtmosphere(true);
1435 warnings.add("Unknown atmospheric model, using ISA.");
1442 class FlightDataHandler extends ElementHandler {
1444 private FlightDataBranchHandler dataHandler;
1445 private WarningSet warningSet = new WarningSet();
1446 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1448 private FlightData data;
1450 public FlightData getFlightData() {
1455 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1456 WarningSet warnings) {
1458 if (element.equals("warning")) {
1459 return PlainTextHandler.INSTANCE;
1461 if (element.equals("databranch")) {
1462 if (attributes.get("name") == null || attributes.get("types") == null) {
1463 warnings.add("Illegal flight data definition, ignoring.");
1466 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1467 attributes.get("types"));
1471 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1477 public void closeElement(String element, HashMap<String, String> attributes,
1478 String content, WarningSet warnings) {
1480 if (element.equals("databranch")) {
1481 FlightDataBranch branch = dataHandler.getBranch();
1482 if (branch.getLength() > 0) {
1483 branches.add(branch);
1485 } else if (element.equals("warning")) {
1486 warningSet.add(Warning.fromString(content));
1492 public void endHandler(String element, HashMap<String, String> attributes,
1493 String content, WarningSet warnings) {
1495 if (branches.size() > 0) {
1496 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1498 double maxAltitude = Double.NaN;
1499 double maxVelocity = Double.NaN;
1500 double maxAcceleration = Double.NaN;
1501 double maxMach = Double.NaN;
1502 double timeToApogee = Double.NaN;
1503 double flightTime = Double.NaN;
1504 double groundHitVelocity = Double.NaN;
1507 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1508 } catch (NumberFormatException ignore) {
1511 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1512 } catch (NumberFormatException ignore) {
1515 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1516 } catch (NumberFormatException ignore) {
1519 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1520 } catch (NumberFormatException ignore) {
1523 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1524 } catch (NumberFormatException ignore) {
1527 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1528 } catch (NumberFormatException ignore) {
1532 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1533 } catch (NumberFormatException ignore) {
1536 // TODO: HIGH: Store and load launchRodVelocity
1537 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1538 timeToApogee, flightTime, groundHitVelocity, Double.NaN);
1541 data.getWarningSet().addAll(warningSet);
1549 class FlightDataBranchHandler extends ElementHandler {
1550 private final FlightDataType[] types;
1551 private final FlightDataBranch branch;
1553 public FlightDataBranchHandler(String name, String typeList) {
1554 String[] split = typeList.split(",");
1555 types = new FlightDataType[split.length];
1556 for (int i = 0; i < split.length; i++) {
1557 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1560 // TODO: LOW: May throw an IllegalArgumentException
1561 branch = new FlightDataBranch(name, types);
1564 public FlightDataBranch getBranch() {
1570 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1571 WarningSet warnings) {
1573 if (element.equals("datapoint"))
1574 return PlainTextHandler.INSTANCE;
1575 if (element.equals("event"))
1576 return PlainTextHandler.INSTANCE;
1578 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1584 public void closeElement(String element, HashMap<String, String> attributes,
1585 String content, WarningSet warnings) {
1587 if (element.equals("event")) {
1589 FlightEvent.Type type;
1592 time = DocumentConfig.stringToDouble(attributes.get("time"));
1593 } catch (NumberFormatException e) {
1594 warnings.add("Illegal event specification, ignoring.");
1598 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1600 warnings.add("Illegal event specification, ignoring.");
1604 branch.addEvent(new FlightEvent(type, time));
1608 if (!element.equals("datapoint")) {
1609 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1613 // element == "datapoint"
1616 // Check line format
1617 String[] split = content.split(",");
1618 if (split.length != types.length) {
1619 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1623 // Parse the doubles
1624 double[] values = new double[split.length];
1625 for (int i = 0; i < values.length; i++) {
1627 values[i] = DocumentConfig.stringToDouble(split[i]);
1628 } catch (NumberFormatException e) {
1629 warnings.add("Data point format error, ignoring point.");
1634 // Add point to branch
1636 for (int i = 0; i < types.length; i++) {
1637 branch.setValue(types[i], values[i]);
1646 ///////////////// Setters implementation
1652 * Set the specified value to the given component.
1654 * @param component the component to which to set.
1655 * @param value the value within the element.
1656 * @param attributes attributes for the element.
1657 * @param warnings the warning set to use.
1659 public void set(RocketComponent component, String value,
1660 HashMap<String, String> attributes, WarningSet warnings);
1664 //// StringSetter - sets the value to the contained String
1665 class StringSetter implements Setter {
1666 private final Reflection.Method setMethod;
1668 public StringSetter(Reflection.Method set) {
1672 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1673 WarningSet warnings) {
1674 setMethod.invoke(c, s);
1678 //// IntSetter - set an integer value
1679 class IntSetter implements Setter {
1680 private final Reflection.Method setMethod;
1682 public IntSetter(Reflection.Method set) {
1686 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1687 WarningSet warnings) {
1689 int n = Integer.parseInt(s);
1690 setMethod.invoke(c, n);
1691 } catch (NumberFormatException e) {
1692 warnings.add(Warning.FILE_INVALID_PARAMETER);
1698 //// BooleanSetter - set a boolean value
1699 class BooleanSetter implements Setter {
1700 private final Reflection.Method setMethod;
1702 public BooleanSetter(Reflection.Method set) {
1706 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1707 WarningSet warnings) {
1710 if (s.equalsIgnoreCase("true")) {
1711 setMethod.invoke(c, true);
1712 } else if (s.equalsIgnoreCase("false")) {
1713 setMethod.invoke(c, false);
1715 warnings.add(Warning.FILE_INVALID_PARAMETER);
1722 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1723 //// calls a setXXX(boolean) method.
1724 class DoubleSetter implements Setter {
1725 private final Reflection.Method setMethod;
1726 private final String specialString;
1727 private final Reflection.Method specialMethod;
1728 private final double multiplier;
1731 * Set only the double value.
1732 * @param set set method for the double value.
1734 public DoubleSetter(Reflection.Method set) {
1735 this.setMethod = set;
1736 this.specialString = null;
1737 this.specialMethod = null;
1738 this.multiplier = 1.0;
1742 * Multiply with the given multiplier and set the double value.
1743 * @param set set method for the double value.
1744 * @param mul multiplier.
1746 public DoubleSetter(Reflection.Method set, double mul) {
1747 this.setMethod = set;
1748 this.specialString = null;
1749 this.specialMethod = null;
1750 this.multiplier = mul;
1754 * Set the double value, or if the value equals the special string, use the
1755 * special setter and set it to true.
1757 * @param set double setter.
1758 * @param special special string
1759 * @param specialMethod boolean setter.
1761 public DoubleSetter(Reflection.Method set, String special,
1762 Reflection.Method specialMethod) {
1763 this.setMethod = set;
1764 this.specialString = special;
1765 this.specialMethod = specialMethod;
1766 this.multiplier = 1.0;
1770 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1771 WarningSet warnings) {
1775 // Check for special case
1776 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1777 specialMethod.invoke(c, true);
1783 double d = Double.parseDouble(s);
1784 setMethod.invoke(c, d * multiplier);
1785 } catch (NumberFormatException e) {
1786 warnings.add(Warning.FILE_INVALID_PARAMETER);
1792 class OverrideSetter implements Setter {
1793 private final Reflection.Method setMethod;
1794 private final Reflection.Method enabledMethod;
1796 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1797 this.setMethod = set;
1798 this.enabledMethod = enabledMethod;
1801 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1802 WarningSet warnings) {
1805 double d = Double.parseDouble(s);
1806 setMethod.invoke(c, d);
1807 enabledMethod.invoke(c, true);
1808 } catch (NumberFormatException e) {
1809 warnings.add(Warning.FILE_INVALID_PARAMETER);
1814 //// EnumSetter - sets a generic enum type
1815 class EnumSetter<T extends Enum<T>> implements Setter {
1816 private final Reflection.Method setter;
1817 private final Class<T> enumClass;
1819 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1821 this.enumClass = enumClass;
1825 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1826 WarningSet warnings) {
1828 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1829 if (setEnum == null) {
1830 warnings.add(Warning.FILE_INVALID_PARAMETER);
1834 setter.invoke(c, setEnum);
1839 //// ColorSetter - sets a Color value
1840 class ColorSetter implements Setter {
1841 private final Reflection.Method setMethod;
1843 public ColorSetter(Reflection.Method set) {
1847 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1848 WarningSet warnings) {
1850 String red = attributes.get("red");
1851 String green = attributes.get("green");
1852 String blue = attributes.get("blue");
1854 if (red == null || green == null || blue == null) {
1855 warnings.add(Warning.FILE_INVALID_PARAMETER);
1861 r = Integer.parseInt(red);
1862 g = Integer.parseInt(green);
1863 b = Integer.parseInt(blue);
1864 } catch (NumberFormatException e) {
1865 warnings.add(Warning.FILE_INVALID_PARAMETER);
1869 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1870 warnings.add(Warning.FILE_INVALID_PARAMETER);
1874 Color color = new Color(r, g, b);
1875 setMethod.invoke(c, color);
1877 if (!s.trim().equals("")) {
1878 warnings.add(Warning.FILE_INVALID_PARAMETER);
1885 class MaterialSetter implements Setter {
1886 private final Reflection.Method setMethod;
1887 private final Material.Type type;
1889 public MaterialSetter(Reflection.Method set, Material.Type type) {
1890 this.setMethod = set;
1894 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1895 WarningSet warnings) {
1901 if (name.equals("")) {
1902 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1909 str = attributes.remove("density");
1911 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1915 density = Double.parseDouble(str);
1916 } catch (NumberFormatException e) {
1917 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1922 // double thickness = 0;
1923 // str = attributes.remove("thickness");
1926 // thickness = Double.parseDouble(str);
1927 // } catch (NumberFormatException e){
1928 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1932 // Check type if specified
1933 str = attributes.remove("type");
1934 if (str != null && !type.name().toLowerCase().equals(str)) {
1935 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1939 mat = Databases.findMaterial(type, name, density, false);
1941 setMethod.invoke(c, mat);
1948 class PositionSetter implements Setter {
1950 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1951 WarningSet warnings) {
1953 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1954 RocketComponent.Position.class);
1956 warnings.add(Warning.FILE_INVALID_PARAMETER);
1962 pos = Double.parseDouble(value);
1963 } catch (NumberFormatException e) {
1964 warnings.add(Warning.FILE_INVALID_PARAMETER);
1968 if (c instanceof FinSet) {
1969 ((FinSet) c).setRelativePosition(type);
1970 c.setPositionValue(pos);
1971 } else if (c instanceof LaunchLug) {
1972 ((LaunchLug) c).setRelativePosition(type);
1973 c.setPositionValue(pos);
1974 } else if (c instanceof InternalComponent) {
1975 ((InternalComponent) c).setRelativePosition(type);
1976 c.setPositionValue(pos);
1978 warnings.add(Warning.FILE_INVALID_PARAMETER);
1985 class FinTabPositionSetter extends DoubleSetter {
1987 public FinTabPositionSetter() {
1988 super(Reflection.findMethodStatic(FinSet.class, "setTabShift", double.class));
1992 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1993 WarningSet warnings) {
1995 if (!(c instanceof FinSet)) {
1996 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
1999 String relative = attributes.get("relativeto");
2000 FinSet.TabRelativePosition position =
2001 (TabRelativePosition) DocumentConfig.findEnum(relative,
2002 FinSet.TabRelativePosition.class);
2004 if (position != null) {
2006 ((FinSet) c).setTabRelativePosition(position);
2009 if (relative == null) {
2010 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2012 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2016 super.set(c, s, attributes, warnings);
2023 class ClusterConfigurationSetter implements Setter {
2025 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2026 WarningSet warnings) {
2028 if (!(component instanceof Clusterable)) {
2029 warnings.add("Illegal component defined as cluster.");
2033 ClusterConfiguration config = null;
2034 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2035 if (c.getXMLName().equals(value)) {
2041 if (config == null) {
2042 warnings.add("Illegal cluster configuration specified.");
2046 ((Clusterable) component).setClusterConfiguration(config);