1 package net.sf.openrocket.file.openrocket;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.lang.reflect.Constructor;
7 import java.lang.reflect.InvocationTargetException;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.List;
12 import net.sf.openrocket.aerodynamics.Warning;
13 import net.sf.openrocket.aerodynamics.WarningSet;
14 import net.sf.openrocket.database.Databases;
15 import net.sf.openrocket.document.OpenRocketDocument;
16 import net.sf.openrocket.document.Simulation;
17 import net.sf.openrocket.document.Simulation.Status;
18 import net.sf.openrocket.document.StorageOptions;
19 import net.sf.openrocket.file.RocketLoadException;
20 import net.sf.openrocket.file.RocketLoader;
21 import net.sf.openrocket.file.simplesax.ElementHandler;
22 import net.sf.openrocket.file.simplesax.PlainTextHandler;
23 import net.sf.openrocket.file.simplesax.SimpleSAX;
24 import net.sf.openrocket.logging.LogHelper;
25 import net.sf.openrocket.material.Material;
26 import net.sf.openrocket.motor.Motor;
27 import net.sf.openrocket.motor.MotorDigest;
28 import net.sf.openrocket.motor.ThrustCurveMotor;
29 import net.sf.openrocket.rocketcomponent.BodyComponent;
30 import net.sf.openrocket.rocketcomponent.BodyTube;
31 import net.sf.openrocket.rocketcomponent.Bulkhead;
32 import net.sf.openrocket.rocketcomponent.CenteringRing;
33 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
34 import net.sf.openrocket.rocketcomponent.Clusterable;
35 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
36 import net.sf.openrocket.rocketcomponent.EngineBlock;
37 import net.sf.openrocket.rocketcomponent.ExternalComponent;
38 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
39 import net.sf.openrocket.rocketcomponent.FinSet;
40 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
41 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
42 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
43 import net.sf.openrocket.rocketcomponent.InnerTube;
44 import net.sf.openrocket.rocketcomponent.InternalComponent;
45 import net.sf.openrocket.rocketcomponent.LaunchLug;
46 import net.sf.openrocket.rocketcomponent.MassComponent;
47 import net.sf.openrocket.rocketcomponent.MassObject;
48 import net.sf.openrocket.rocketcomponent.MotorMount;
49 import net.sf.openrocket.rocketcomponent.NoseCone;
50 import net.sf.openrocket.rocketcomponent.Parachute;
51 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
52 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
53 import net.sf.openrocket.rocketcomponent.ReferenceType;
54 import net.sf.openrocket.rocketcomponent.RingComponent;
55 import net.sf.openrocket.rocketcomponent.Rocket;
56 import net.sf.openrocket.rocketcomponent.RocketComponent;
57 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
58 import net.sf.openrocket.rocketcomponent.ShockCord;
59 import net.sf.openrocket.rocketcomponent.Stage;
60 import net.sf.openrocket.rocketcomponent.Streamer;
61 import net.sf.openrocket.rocketcomponent.StructuralComponent;
62 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
63 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
64 import net.sf.openrocket.rocketcomponent.Transition;
65 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
66 import net.sf.openrocket.rocketcomponent.TubeCoupler;
67 import net.sf.openrocket.simulation.FlightData;
68 import net.sf.openrocket.simulation.FlightDataBranch;
69 import net.sf.openrocket.simulation.FlightDataType;
70 import net.sf.openrocket.simulation.FlightEvent;
71 import net.sf.openrocket.simulation.FlightEvent.Type;
72 import net.sf.openrocket.simulation.GUISimulationConditions;
73 import net.sf.openrocket.startup.Application;
74 import net.sf.openrocket.unit.UnitGroup;
75 import net.sf.openrocket.util.BugException;
76 import net.sf.openrocket.util.Coordinate;
77 import net.sf.openrocket.util.LineStyle;
78 import net.sf.openrocket.util.Reflection;
80 import org.xml.sax.InputSource;
81 import org.xml.sax.SAXException;
85 * Class that loads a rocket definition from an OpenRocket rocket file.
87 * This class uses SAX to read the XML file format. The
88 * {@link #loadFromStream(InputStream)} method simply sets the system up and
89 * starts the parsing, while the actual logic is in the private inner class
90 * <code>OpenRocketHandler</code>.
92 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
94 public class OpenRocketLoader extends RocketLoader {
95 private static final LogHelper log = Application.getLogger();
99 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
101 log.info("Loading .ork file");
103 InputSource xmlSource = new InputSource(source);
104 OpenRocketHandler handler = new OpenRocketHandler();
108 SimpleSAX.readXML(xmlSource, handler, warnings);
109 } catch (SAXException e) {
110 log.warn("Malformed XML in input");
111 throw new RocketLoadException("Malformed XML in input.", e);
115 OpenRocketDocument doc = handler.getDocument();
116 doc.getDefaultConfiguration().setAllStages();
118 // Deduce suitable time skip
119 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
120 for (Simulation s : doc.getSimulations()) {
121 if (s.getStatus() == Simulation.Status.EXTERNAL ||
122 s.getStatus() == Simulation.Status.NOT_SIMULATED)
124 if (s.getSimulatedData() == null)
126 if (s.getSimulatedData().getBranchCount() == 0)
128 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
131 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
135 double previousTime = Double.NaN;
136 for (double time : list) {
137 if (time - previousTime < timeSkip)
138 timeSkip = time - previousTime;
143 timeSkip = Math.rint(timeSkip * 100) / 100;
145 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
146 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
147 doc.getDefaultStorageOptions().setExplicitlySet(false);
150 log.info("Loading done");
158 class DocumentConfig {
160 /* Remember to update OpenRocketSaver as well! */
161 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1", "1.2" };
164 //////// Component constructors
165 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
168 // External components
169 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
170 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
171 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
172 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
173 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
174 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
175 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
177 // Internal components
178 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
179 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
180 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
181 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
182 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
184 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
185 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
186 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
187 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
190 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
192 } catch (NoSuchMethodException e) {
193 throw new BugException(
194 "Error in constructing the 'constructors' HashMap.");
199 //////// Parameter setters
201 * The keys are of the form Class:param, where Class is the class name and param
202 * the element name. Setters are searched for in descending class order.
203 * A setter of null means setting the parameter is not allowed.
205 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
208 setters.put("RocketComponent:name", new StringSetter(
209 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
210 setters.put("RocketComponent:color", new ColorSetter(
211 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
212 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
213 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
215 setters.put("RocketComponent:position", new PositionSetter());
216 setters.put("RocketComponent:overridemass", new OverrideSetter(
217 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
218 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
219 setters.put("RocketComponent:overridecg", new OverrideSetter(
220 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
221 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
222 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
223 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
224 setters.put("RocketComponent:comment", new StringSetter(
225 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
228 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
229 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
231 setters.put("ExternalComponent:material", new MaterialSetter(
232 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
233 Material.Type.BULK));
236 setters.put("BodyComponent:length", new DoubleSetter(
237 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
239 // SymmetricComponent
240 setters.put("SymmetricComponent:thickness", new DoubleSetter(
241 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
243 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
246 setters.put("BodyTube:radius", new DoubleSetter(
247 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
249 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
252 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
253 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
254 Transition.Shape.class));
255 setters.put("Transition:shapeclipped", new BooleanSetter(
256 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
257 setters.put("Transition:shapeparameter", new DoubleSetter(
258 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
260 setters.put("Transition:foreradius", new DoubleSetter(
261 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
263 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
264 setters.put("Transition:aftradius", new DoubleSetter(
265 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
267 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
269 setters.put("Transition:foreshoulderradius", new DoubleSetter(
270 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
271 setters.put("Transition:foreshoulderlength", new DoubleSetter(
272 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
273 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
274 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
275 setters.put("Transition:foreshouldercapped", new BooleanSetter(
276 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
278 setters.put("Transition:aftshoulderradius", new DoubleSetter(
279 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
280 setters.put("Transition:aftshoulderlength", new DoubleSetter(
281 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
282 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
283 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
284 setters.put("Transition:aftshouldercapped", new BooleanSetter(
285 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
287 // NoseCone - disable disallowed elements
288 setters.put("NoseCone:foreradius", null);
289 setters.put("NoseCone:foreshoulderradius", null);
290 setters.put("NoseCone:foreshoulderlength", null);
291 setters.put("NoseCone:foreshoulderthickness", null);
292 setters.put("NoseCone:foreshouldercapped", null);
295 setters.put("FinSet:fincount", new IntSetter(
296 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
297 setters.put("FinSet:rotation", new DoubleSetter(
298 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
299 setters.put("FinSet:thickness", new DoubleSetter(
300 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
301 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
302 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
303 FinSet.CrossSection.class));
304 setters.put("FinSet:cant", new DoubleSetter(
305 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
306 setters.put("FinSet:tabheight", new DoubleSetter(
307 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
308 setters.put("FinSet:tablength", new DoubleSetter(
309 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
310 setters.put("FinSet:tabposition", new FinTabPositionSetter());
313 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
314 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
315 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
316 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
317 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
318 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
319 setters.put("TrapezoidFinSet:height", new DoubleSetter(
320 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
323 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
324 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
325 setters.put("EllipticalFinSet:height", new DoubleSetter(
326 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
328 // FreeformFinSet points handled as a special handler
331 setters.put("LaunchLug:radius", new DoubleSetter(
332 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
333 setters.put("LaunchLug:length", new DoubleSetter(
334 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
335 setters.put("LaunchLug:thickness", new DoubleSetter(
336 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
337 setters.put("LaunchLug:radialdirection", new DoubleSetter(
338 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
341 // InternalComponent - nothing
343 // StructuralComponent
344 setters.put("StructuralComponent:material", new MaterialSetter(
345 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
346 Material.Type.BULK));
349 setters.put("RingComponent:length", new DoubleSetter(
350 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
351 setters.put("RingComponent:radialposition", new DoubleSetter(
352 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
353 setters.put("RingComponent:radialdirection", new DoubleSetter(
354 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
357 // ThicknessRingComponent - radius on separate components due to differing automatics
358 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
359 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
362 setters.put("EngineBlock:outerradius", new DoubleSetter(
363 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
365 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
368 setters.put("TubeCoupler:outerradius", new DoubleSetter(
369 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
371 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
374 setters.put("InnerTube:outerradius", new DoubleSetter(
375 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
376 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
377 setters.put("InnerTube:clusterscale", new DoubleSetter(
378 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
379 setters.put("InnerTube:clusterrotation", new DoubleSetter(
380 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
383 // RadiusRingComponent
386 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
387 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
388 setters.put("Bulkhead:outerradius", new DoubleSetter(
389 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
391 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
394 setters.put("CenteringRing:innerradius", new DoubleSetter(
395 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
397 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
398 setters.put("CenteringRing:outerradius", new DoubleSetter(
399 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
401 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
405 setters.put("MassObject:packedlength", new DoubleSetter(
406 Reflection.findMethod(MassObject.class, "setLength", double.class)));
407 setters.put("MassObject:packedradius", new DoubleSetter(
408 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
409 setters.put("MassObject:radialposition", new DoubleSetter(
410 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
411 setters.put("MassObject:radialdirection", new DoubleSetter(
412 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
416 setters.put("MassComponent:mass", new DoubleSetter(
417 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
420 setters.put("ShockCord:cordlength", new DoubleSetter(
421 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
422 setters.put("ShockCord:material", new MaterialSetter(
423 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
424 Material.Type.LINE));
427 setters.put("RecoveryDevice:cd", new DoubleSetter(
428 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
430 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
431 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
432 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
433 RecoveryDevice.DeployEvent.class));
434 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
435 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
436 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
437 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
438 setters.put("RecoveryDevice:material", new MaterialSetter(
439 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
440 Material.Type.SURFACE));
443 setters.put("Parachute:diameter", new DoubleSetter(
444 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
445 setters.put("Parachute:linecount", new IntSetter(
446 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
447 setters.put("Parachute:linelength", new DoubleSetter(
448 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
449 setters.put("Parachute:linematerial", new MaterialSetter(
450 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
451 Material.Type.LINE));
454 setters.put("Streamer:striplength", new DoubleSetter(
455 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
456 setters.put("Streamer:stripwidth", new DoubleSetter(
457 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
460 // <motorconfiguration> handled by separate handler
461 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
462 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
463 ReferenceType.class));
464 setters.put("Rocket:customreference", new DoubleSetter(
465 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
466 setters.put("Rocket:designer", new StringSetter(
467 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
468 setters.put("Rocket:revision", new StringSetter(
469 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
474 * Search for a enum value that has the corresponding name as an XML value. The current
475 * conversion from enum name to XML value is to lowercase the name and strip out all
476 * underscore characters. This method returns a match to these criteria, or <code>null</code>
477 * if no such enum exists.
479 * @param <T> then enum type.
480 * @param name the XML value, null ok.
481 * @param enumClass the class of the enum.
482 * @return the found enum value, or <code>null</code>.
484 public static <T extends Enum<T>> Enum<T> findEnum(String name,
485 Class<? extends Enum<T>> enumClass) {
490 for (Enum<T> e : enumClass.getEnumConstants()) {
491 if (e.name().toLowerCase().replace("_", "").equals(name)) {
500 * Convert a string to a double including formatting specifications of the OpenRocket
501 * file format. This accepts all formatting that is valid for
502 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
504 * @param s the string to parse.
505 * @return the numerical value.
506 * @throws NumberFormatException the the string cannot be parsed.
508 public static double stringToDouble(String s) throws NumberFormatException {
510 throw new NumberFormatException("null string");
511 if (s.equalsIgnoreCase("NaN"))
513 if (s.equalsIgnoreCase("Inf"))
514 return Double.POSITIVE_INFINITY;
515 if (s.equalsIgnoreCase("-Inf"))
516 return Double.NEGATIVE_INFINITY;
517 return Double.parseDouble(s);
526 * The starting point of the handlers. Accepts a single <openrocket> element and hands
527 * the contents to be read by a OpenRocketContentsHandler.
529 class OpenRocketHandler extends ElementHandler {
530 private OpenRocketContentHandler handler = null;
533 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
534 * has not been read yet.
536 * @return the document read, or null.
538 public OpenRocketDocument getDocument() {
539 return handler.getDocument();
543 public ElementHandler openElement(String element, HashMap<String, String> attributes,
544 WarningSet warnings) {
546 // Check for unknown elements
547 if (!element.equals("openrocket")) {
548 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
552 // Check for first call
553 if (handler != null) {
554 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
559 // Check version number
560 String version = null;
561 String creator = attributes.remove("creator");
562 String docVersion = attributes.remove("version");
563 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
564 if (v.equals(docVersion)) {
569 if (version == null) {
570 String str = "Unsupported document version";
571 if (docVersion != null)
572 str += " " + docVersion;
573 if (creator != null && !creator.trim().equals(""))
574 str += " (written using '" + creator.trim() + "')";
575 str += ", attempting to read file anyway.";
579 handler = new OpenRocketContentHandler();
584 public void closeElement(String element, HashMap<String, String> attributes,
585 String content, WarningSet warnings) throws SAXException {
586 attributes.remove("version");
587 attributes.remove("creator");
588 super.closeElement(element, attributes, content, warnings);
596 * Handles the content of the <openrocket> tag.
598 class OpenRocketContentHandler extends ElementHandler {
599 private final OpenRocketDocument doc;
600 private final Rocket rocket;
602 private boolean rocketDefined = false;
603 private boolean simulationsDefined = false;
605 public OpenRocketContentHandler() {
606 this.rocket = new Rocket();
607 this.doc = new OpenRocketDocument(rocket);
611 public OpenRocketDocument getDocument() {
618 public ElementHandler openElement(String element, HashMap<String, String> attributes,
619 WarningSet warnings) {
621 if (element.equals("rocket")) {
624 .fromString("Multiple rocket designs within one document, "
625 + "ignoring later ones."));
628 rocketDefined = true;
629 return new ComponentParameterHandler(rocket);
632 if (element.equals("simulations")) {
633 if (simulationsDefined) {
635 .fromString("Multiple simulation definitions within one document, "
636 + "ignoring later ones."));
639 simulationsDefined = true;
640 return new SimulationsHandler(doc);
643 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
653 * A handler that creates components from the corresponding elements. The control of the
654 * contents is passed on to ComponentParameterHandler.
656 class ComponentHandler extends ElementHandler {
657 private final RocketComponent parent;
659 public ComponentHandler(RocketComponent parent) {
660 this.parent = parent;
664 public ElementHandler openElement(String element, HashMap<String, String> attributes,
665 WarningSet warnings) {
667 // Attempt to construct new component
668 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
670 if (constructor == null) {
671 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
677 c = constructor.newInstance();
678 } catch (InstantiationException e) {
679 throw new BugException("Error constructing component.", e);
680 } catch (IllegalAccessException e) {
681 throw new BugException("Error constructing component.", e);
682 } catch (InvocationTargetException e) {
683 throw Reflection.handleWrappedException(e);
688 return new ComponentParameterHandler(c);
694 * A handler that populates the parameters of a previously constructed rocket component.
695 * This uses the setters, or delegates the handling to another handler for specific
698 class ComponentParameterHandler extends ElementHandler {
699 private final RocketComponent component;
701 public ComponentParameterHandler(RocketComponent c) {
706 public ElementHandler openElement(String element, HashMap<String, String> attributes,
707 WarningSet warnings) {
709 // Check for specific elements that contain other elements
710 if (element.equals("subcomponents")) {
711 return new ComponentHandler(component);
713 if (element.equals("motormount")) {
714 if (!(component instanceof MotorMount)) {
715 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
718 return new MotorMountHandler((MotorMount) component);
720 if (element.equals("finpoints")) {
721 if (!(component instanceof FreeformFinSet)) {
722 warnings.add(Warning.fromString("Illegal component defined for fin points."));
725 return new FinSetPointHandler((FreeformFinSet) component);
727 if (element.equals("motorconfiguration")) {
728 if (!(component instanceof Rocket)) {
729 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
732 return new MotorConfigurationHandler((Rocket) component);
736 return PlainTextHandler.INSTANCE;
740 public void closeElement(String element, HashMap<String, String> attributes,
741 String content, WarningSet warnings) {
743 if (element.equals("subcomponents") || element.equals("motormount") ||
744 element.equals("finpoints") || element.equals("motorconfiguration")) {
748 // Search for the correct setter class
751 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
752 String setterKey = c.getSimpleName() + ":" + element;
753 Setter s = DocumentConfig.setters.get(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) {
1673 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1674 WarningSet warnings) {
1675 setMethod.invoke(c, s);
1679 //// IntSetter - set an integer value
1680 class IntSetter implements Setter {
1681 private final Reflection.Method setMethod;
1683 public IntSetter(Reflection.Method set) {
1688 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1689 WarningSet warnings) {
1691 int n = Integer.parseInt(s);
1692 setMethod.invoke(c, n);
1693 } catch (NumberFormatException e) {
1694 warnings.add(Warning.FILE_INVALID_PARAMETER);
1700 //// BooleanSetter - set a boolean value
1701 class BooleanSetter implements Setter {
1702 private final Reflection.Method setMethod;
1704 public BooleanSetter(Reflection.Method set) {
1709 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1710 WarningSet warnings) {
1713 if (s.equalsIgnoreCase("true")) {
1714 setMethod.invoke(c, true);
1715 } else if (s.equalsIgnoreCase("false")) {
1716 setMethod.invoke(c, false);
1718 warnings.add(Warning.FILE_INVALID_PARAMETER);
1725 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1726 //// calls a setXXX(boolean) method.
1727 class DoubleSetter implements Setter {
1728 private final Reflection.Method setMethod;
1729 private final String specialString;
1730 private final Reflection.Method specialMethod;
1731 private final double multiplier;
1734 * Set only the double value.
1735 * @param set set method for the double value.
1737 public DoubleSetter(Reflection.Method set) {
1738 this.setMethod = set;
1739 this.specialString = null;
1740 this.specialMethod = null;
1741 this.multiplier = 1.0;
1745 * Multiply with the given multiplier and set the double value.
1746 * @param set set method for the double value.
1747 * @param mul multiplier.
1749 public DoubleSetter(Reflection.Method set, double mul) {
1750 this.setMethod = set;
1751 this.specialString = null;
1752 this.specialMethod = null;
1753 this.multiplier = mul;
1757 * Set the double value, or if the value equals the special string, use the
1758 * special setter and set it to true.
1760 * @param set double setter.
1761 * @param special special string
1762 * @param specialMethod boolean setter.
1764 public DoubleSetter(Reflection.Method set, String special,
1765 Reflection.Method specialMethod) {
1766 this.setMethod = set;
1767 this.specialString = special;
1768 this.specialMethod = specialMethod;
1769 this.multiplier = 1.0;
1774 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1775 WarningSet warnings) {
1779 // Check for special case
1780 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1781 specialMethod.invoke(c, true);
1787 double d = Double.parseDouble(s);
1788 setMethod.invoke(c, d * multiplier);
1789 } catch (NumberFormatException e) {
1790 warnings.add(Warning.FILE_INVALID_PARAMETER);
1796 class OverrideSetter implements Setter {
1797 private final Reflection.Method setMethod;
1798 private final Reflection.Method enabledMethod;
1800 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1801 this.setMethod = set;
1802 this.enabledMethod = enabledMethod;
1806 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1807 WarningSet warnings) {
1810 double d = Double.parseDouble(s);
1811 setMethod.invoke(c, d);
1812 enabledMethod.invoke(c, true);
1813 } catch (NumberFormatException e) {
1814 warnings.add(Warning.FILE_INVALID_PARAMETER);
1819 //// EnumSetter - sets a generic enum type
1820 class EnumSetter<T extends Enum<T>> implements Setter {
1821 private final Reflection.Method setter;
1822 private final Class<T> enumClass;
1824 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1826 this.enumClass = enumClass;
1830 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1831 WarningSet warnings) {
1833 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1834 if (setEnum == null) {
1835 warnings.add(Warning.FILE_INVALID_PARAMETER);
1839 setter.invoke(c, setEnum);
1844 //// ColorSetter - sets a Color value
1845 class ColorSetter implements Setter {
1846 private final Reflection.Method setMethod;
1848 public ColorSetter(Reflection.Method set) {
1853 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1854 WarningSet warnings) {
1856 String red = attributes.get("red");
1857 String green = attributes.get("green");
1858 String blue = attributes.get("blue");
1860 if (red == null || green == null || blue == null) {
1861 warnings.add(Warning.FILE_INVALID_PARAMETER);
1867 r = Integer.parseInt(red);
1868 g = Integer.parseInt(green);
1869 b = Integer.parseInt(blue);
1870 } catch (NumberFormatException e) {
1871 warnings.add(Warning.FILE_INVALID_PARAMETER);
1875 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1876 warnings.add(Warning.FILE_INVALID_PARAMETER);
1880 Color color = new Color(r, g, b);
1881 setMethod.invoke(c, color);
1883 if (!s.trim().equals("")) {
1884 warnings.add(Warning.FILE_INVALID_PARAMETER);
1891 class MaterialSetter implements Setter {
1892 private final Reflection.Method setMethod;
1893 private final Material.Type type;
1895 public MaterialSetter(Reflection.Method set, Material.Type type) {
1896 this.setMethod = set;
1901 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1902 WarningSet warnings) {
1908 if (name.equals("")) {
1909 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1916 str = attributes.remove("density");
1918 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1922 density = Double.parseDouble(str);
1923 } catch (NumberFormatException e) {
1924 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1929 // double thickness = 0;
1930 // str = attributes.remove("thickness");
1933 // thickness = Double.parseDouble(str);
1934 // } catch (NumberFormatException e){
1935 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1939 // Check type if specified
1940 str = attributes.remove("type");
1941 if (str != null && !type.name().toLowerCase().equals(str)) {
1942 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1946 mat = Databases.findMaterial(type, name, density, false);
1948 setMethod.invoke(c, mat);
1955 class PositionSetter implements Setter {
1958 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1959 WarningSet warnings) {
1961 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1962 RocketComponent.Position.class);
1964 warnings.add(Warning.FILE_INVALID_PARAMETER);
1970 pos = Double.parseDouble(value);
1971 } catch (NumberFormatException e) {
1972 warnings.add(Warning.FILE_INVALID_PARAMETER);
1976 if (c instanceof FinSet) {
1977 ((FinSet) c).setRelativePosition(type);
1978 c.setPositionValue(pos);
1979 } else if (c instanceof LaunchLug) {
1980 ((LaunchLug) c).setRelativePosition(type);
1981 c.setPositionValue(pos);
1982 } else if (c instanceof InternalComponent) {
1983 ((InternalComponent) c).setRelativePosition(type);
1984 c.setPositionValue(pos);
1986 warnings.add(Warning.FILE_INVALID_PARAMETER);
1993 class FinTabPositionSetter extends DoubleSetter {
1995 public FinTabPositionSetter() {
1996 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2000 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2001 WarningSet warnings) {
2003 if (!(c instanceof FinSet)) {
2004 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2007 String relative = attributes.get("relativeto");
2008 FinSet.TabRelativePosition position =
2009 (TabRelativePosition) DocumentConfig.findEnum(relative,
2010 FinSet.TabRelativePosition.class);
2012 if (position != null) {
2014 ((FinSet) c).setTabRelativePosition(position);
2017 if (relative == null) {
2018 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2020 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2024 super.set(c, s, attributes, warnings);
2031 class ClusterConfigurationSetter implements Setter {
2034 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2035 WarningSet warnings) {
2037 if (!(component instanceof Clusterable)) {
2038 warnings.add("Illegal component defined as cluster.");
2042 ClusterConfiguration config = null;
2043 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2044 if (c.getXMLName().equals(value)) {
2050 if (config == null) {
2051 warnings.add("Illegal cluster configuration specified.");
2055 ((Clusterable) component).setClusterConfiguration(config);