1 package net.sf.openrocket.file.openrocket;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.InvocationTargetException;
7 import java.util.ArrayList;
8 import java.util.HashMap;
11 import net.sf.openrocket.aerodynamics.Warning;
12 import net.sf.openrocket.aerodynamics.WarningSet;
13 import net.sf.openrocket.database.Databases;
14 import net.sf.openrocket.document.OpenRocketDocument;
15 import net.sf.openrocket.document.Simulation;
16 import net.sf.openrocket.document.Simulation.Status;
17 import net.sf.openrocket.document.StorageOptions;
18 import net.sf.openrocket.file.RocketLoadException;
19 import net.sf.openrocket.file.RocketLoader;
20 import net.sf.openrocket.file.simplesax.ElementHandler;
21 import net.sf.openrocket.file.simplesax.PlainTextHandler;
22 import net.sf.openrocket.file.simplesax.SimpleSAX;
23 import net.sf.openrocket.logging.LogHelper;
24 import net.sf.openrocket.material.Material;
25 import net.sf.openrocket.motor.Motor;
26 import net.sf.openrocket.rocketcomponent.BodyComponent;
27 import net.sf.openrocket.rocketcomponent.BodyTube;
28 import net.sf.openrocket.rocketcomponent.Bulkhead;
29 import net.sf.openrocket.rocketcomponent.CenteringRing;
30 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
31 import net.sf.openrocket.rocketcomponent.Clusterable;
32 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
33 import net.sf.openrocket.rocketcomponent.EngineBlock;
34 import net.sf.openrocket.rocketcomponent.ExternalComponent;
35 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
36 import net.sf.openrocket.rocketcomponent.FinSet;
37 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
38 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
39 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
40 import net.sf.openrocket.rocketcomponent.InnerTube;
41 import net.sf.openrocket.rocketcomponent.InternalComponent;
42 import net.sf.openrocket.rocketcomponent.LaunchLug;
43 import net.sf.openrocket.rocketcomponent.MassComponent;
44 import net.sf.openrocket.rocketcomponent.MassObject;
45 import net.sf.openrocket.rocketcomponent.MotorMount;
46 import net.sf.openrocket.rocketcomponent.NoseCone;
47 import net.sf.openrocket.rocketcomponent.Parachute;
48 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
49 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
50 import net.sf.openrocket.rocketcomponent.ReferenceType;
51 import net.sf.openrocket.rocketcomponent.RingComponent;
52 import net.sf.openrocket.rocketcomponent.Rocket;
53 import net.sf.openrocket.rocketcomponent.RocketComponent;
54 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
55 import net.sf.openrocket.rocketcomponent.ShockCord;
56 import net.sf.openrocket.rocketcomponent.Stage;
57 import net.sf.openrocket.rocketcomponent.Streamer;
58 import net.sf.openrocket.rocketcomponent.StructuralComponent;
59 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
60 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
61 import net.sf.openrocket.rocketcomponent.Transition;
62 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
63 import net.sf.openrocket.rocketcomponent.TubeCoupler;
64 import net.sf.openrocket.simulation.FlightData;
65 import net.sf.openrocket.simulation.FlightDataBranch;
66 import net.sf.openrocket.simulation.FlightDataType;
67 import net.sf.openrocket.simulation.FlightEvent;
68 import net.sf.openrocket.simulation.FlightEvent.Type;
69 import net.sf.openrocket.simulation.SimulationOptions;
70 import net.sf.openrocket.startup.Application;
71 import net.sf.openrocket.unit.UnitGroup;
72 import net.sf.openrocket.util.BugException;
73 import net.sf.openrocket.util.Color;
74 import net.sf.openrocket.util.Coordinate;
75 import net.sf.openrocket.util.GeodeticComputationStrategy;
76 import net.sf.openrocket.util.LineStyle;
77 import net.sf.openrocket.util.Reflection;
79 import org.xml.sax.InputSource;
80 import org.xml.sax.SAXException;
84 * Class that loads a rocket definition from an OpenRocket rocket file.
86 * This class uses SAX to read the XML file format. The
87 * {@link #loadFromStream(InputStream)} method simply sets the system up and
88 * starts the parsing, while the actual logic is in the private inner class
89 * <code>OpenRocketHandler</code>.
91 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
93 public class OpenRocketLoader extends RocketLoader {
94 private static final LogHelper log = Application.getLogger();
98 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
100 log.info("Loading .ork file");
102 InputSource xmlSource = new InputSource(source);
103 OpenRocketHandler handler = new OpenRocketHandler();
107 SimpleSAX.readXML(xmlSource, handler, warnings);
108 } catch (SAXException e) {
109 log.warn("Malformed XML in input");
110 throw new RocketLoadException("Malformed XML in input.", e);
114 OpenRocketDocument doc = handler.getDocument();
115 doc.getDefaultConfiguration().setAllStages();
117 // Deduce suitable time skip
118 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
119 for (Simulation s : doc.getSimulations()) {
120 if (s.getStatus() == Simulation.Status.EXTERNAL ||
121 s.getStatus() == Simulation.Status.NOT_SIMULATED)
123 if (s.getSimulatedData() == null)
125 if (s.getSimulatedData().getBranchCount() == 0)
127 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
130 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
134 double previousTime = Double.NaN;
135 for (double time : list) {
136 if (time - previousTime < timeSkip)
137 timeSkip = time - previousTime;
142 timeSkip = Math.rint(timeSkip * 100) / 100;
144 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
145 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
146 doc.getDefaultStorageOptions().setExplicitlySet(false);
149 log.info("Loading done");
157 class DocumentConfig {
159 /* Remember to update OpenRocketSaver as well! */
160 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1", "1.2", "1.3" };
163 //////// Component constructors
164 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
167 // External components
168 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
169 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
170 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
171 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
172 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
173 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
174 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
176 // Internal components
177 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
178 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
179 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
180 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
181 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
183 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
184 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
185 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
186 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
189 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
191 } catch (NoSuchMethodException e) {
192 throw new BugException(
193 "Error in constructing the 'constructors' HashMap.");
198 //////// Parameter setters
200 * The keys are of the form Class:param, where Class is the class name and param
201 * the element name. Setters are searched for in descending class order.
202 * A setter of null means setting the parameter is not allowed.
204 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
207 setters.put("RocketComponent:name", new StringSetter(
208 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
209 setters.put("RocketComponent:color", new ColorSetter(
210 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
211 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
212 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
214 setters.put("RocketComponent:position", new PositionSetter());
215 setters.put("RocketComponent:overridemass", new OverrideSetter(
216 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
217 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
218 setters.put("RocketComponent:overridecg", new OverrideSetter(
219 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
220 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
221 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
222 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
223 setters.put("RocketComponent:comment", new StringSetter(
224 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
227 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
228 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
230 setters.put("ExternalComponent:material", new MaterialSetter(
231 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
232 Material.Type.BULK));
235 setters.put("BodyComponent:length", new DoubleSetter(
236 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
238 // SymmetricComponent
239 setters.put("SymmetricComponent:thickness", new DoubleSetter(
240 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
242 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
245 setters.put("BodyTube:radius", new DoubleSetter(
246 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
248 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
251 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
252 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
253 Transition.Shape.class));
254 setters.put("Transition:shapeclipped", new BooleanSetter(
255 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
256 setters.put("Transition:shapeparameter", new DoubleSetter(
257 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
259 setters.put("Transition:foreradius", new DoubleSetter(
260 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
262 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
263 setters.put("Transition:aftradius", new DoubleSetter(
264 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
266 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
268 setters.put("Transition:foreshoulderradius", new DoubleSetter(
269 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
270 setters.put("Transition:foreshoulderlength", new DoubleSetter(
271 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
272 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
273 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
274 setters.put("Transition:foreshouldercapped", new BooleanSetter(
275 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
277 setters.put("Transition:aftshoulderradius", new DoubleSetter(
278 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
279 setters.put("Transition:aftshoulderlength", new DoubleSetter(
280 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
281 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
282 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
283 setters.put("Transition:aftshouldercapped", new BooleanSetter(
284 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
286 // NoseCone - disable disallowed elements
287 setters.put("NoseCone:foreradius", null);
288 setters.put("NoseCone:foreshoulderradius", null);
289 setters.put("NoseCone:foreshoulderlength", null);
290 setters.put("NoseCone:foreshoulderthickness", null);
291 setters.put("NoseCone:foreshouldercapped", null);
294 setters.put("FinSet:fincount", new IntSetter(
295 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
296 setters.put("FinSet:rotation", new DoubleSetter(
297 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
298 setters.put("FinSet:thickness", new DoubleSetter(
299 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
300 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
301 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
302 FinSet.CrossSection.class));
303 setters.put("FinSet:cant", new DoubleSetter(
304 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
305 setters.put("FinSet:tabheight", new DoubleSetter(
306 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
307 setters.put("FinSet:tablength", new DoubleSetter(
308 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
309 setters.put("FinSet:tabposition", new FinTabPositionSetter());
312 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
313 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
314 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
315 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
316 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
317 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
318 setters.put("TrapezoidFinSet:height", new DoubleSetter(
319 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
322 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
323 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
324 setters.put("EllipticalFinSet:height", new DoubleSetter(
325 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
327 // FreeformFinSet points handled as a special handler
330 setters.put("LaunchLug:radius", new DoubleSetter(
331 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
332 setters.put("LaunchLug:length", new DoubleSetter(
333 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
334 setters.put("LaunchLug:thickness", new DoubleSetter(
335 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
336 setters.put("LaunchLug:radialdirection", new DoubleSetter(
337 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
340 // InternalComponent - nothing
342 // StructuralComponent
343 setters.put("StructuralComponent:material", new MaterialSetter(
344 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
345 Material.Type.BULK));
348 setters.put("RingComponent:length", new DoubleSetter(
349 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
350 setters.put("RingComponent:radialposition", new DoubleSetter(
351 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
352 setters.put("RingComponent:radialdirection", new DoubleSetter(
353 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
356 // ThicknessRingComponent - radius on separate components due to differing automatics
357 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
358 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
361 setters.put("EngineBlock:outerradius", new DoubleSetter(
362 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
364 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
367 setters.put("TubeCoupler:outerradius", new DoubleSetter(
368 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
370 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
373 setters.put("InnerTube:outerradius", new DoubleSetter(
374 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
375 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
376 setters.put("InnerTube:clusterscale", new DoubleSetter(
377 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
378 setters.put("InnerTube:clusterrotation", new DoubleSetter(
379 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
382 // RadiusRingComponent
385 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
386 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
387 setters.put("Bulkhead:outerradius", new DoubleSetter(
388 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
390 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
393 setters.put("CenteringRing:innerradius", new DoubleSetter(
394 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
396 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
397 setters.put("CenteringRing:outerradius", new DoubleSetter(
398 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
400 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
404 setters.put("MassObject:packedlength", new DoubleSetter(
405 Reflection.findMethod(MassObject.class, "setLength", double.class)));
406 setters.put("MassObject:packedradius", new DoubleSetter(
407 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
408 setters.put("MassObject:radialposition", new DoubleSetter(
409 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
410 setters.put("MassObject:radialdirection", new DoubleSetter(
411 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
415 setters.put("MassComponent:mass", new DoubleSetter(
416 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
419 setters.put("ShockCord:cordlength", new DoubleSetter(
420 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
421 setters.put("ShockCord:material", new MaterialSetter(
422 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
423 Material.Type.LINE));
426 setters.put("RecoveryDevice:cd", new DoubleSetter(
427 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
429 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
430 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
431 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
432 RecoveryDevice.DeployEvent.class));
433 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
434 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
435 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
436 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
437 setters.put("RecoveryDevice:material", new MaterialSetter(
438 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
439 Material.Type.SURFACE));
442 setters.put("Parachute:diameter", new DoubleSetter(
443 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
444 setters.put("Parachute:linecount", new IntSetter(
445 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
446 setters.put("Parachute:linelength", new DoubleSetter(
447 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
448 setters.put("Parachute:linematerial", new MaterialSetter(
449 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
450 Material.Type.LINE));
453 setters.put("Streamer:striplength", new DoubleSetter(
454 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
455 setters.put("Streamer:stripwidth", new DoubleSetter(
456 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
459 // <motorconfiguration> handled by separate handler
460 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
461 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
462 ReferenceType.class));
463 setters.put("Rocket:customreference", new DoubleSetter(
464 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
465 setters.put("Rocket:designer", new StringSetter(
466 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
467 setters.put("Rocket:revision", new StringSetter(
468 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
473 * Search for a enum value that has the corresponding name as an XML value. The current
474 * conversion from enum name to XML value is to lowercase the name and strip out all
475 * underscore characters. This method returns a match to these criteria, or <code>null</code>
476 * if no such enum exists.
478 * @param <T> then enum type.
479 * @param name the XML value, null ok.
480 * @param enumClass the class of the enum.
481 * @return the found enum value, or <code>null</code>.
483 public static <T extends Enum<T>> Enum<T> findEnum(String name,
484 Class<? extends Enum<T>> enumClass) {
489 for (Enum<T> e : enumClass.getEnumConstants()) {
490 if (e.name().toLowerCase().replace("_", "").equals(name)) {
499 * Convert a string to a double including formatting specifications of the OpenRocket
500 * file format. This accepts all formatting that is valid for
501 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
503 * @param s the string to parse.
504 * @return the numerical value.
505 * @throws NumberFormatException the the string cannot be parsed.
507 public static double stringToDouble(String s) throws NumberFormatException {
509 throw new NumberFormatException("null string");
510 if (s.equalsIgnoreCase("NaN"))
512 if (s.equalsIgnoreCase("Inf"))
513 return Double.POSITIVE_INFINITY;
514 if (s.equalsIgnoreCase("-Inf"))
515 return Double.NEGATIVE_INFINITY;
516 return Double.parseDouble(s);
525 * The starting point of the handlers. Accepts a single <openrocket> element and hands
526 * the contents to be read by a OpenRocketContentsHandler.
528 class OpenRocketHandler extends ElementHandler {
529 private OpenRocketContentHandler handler = null;
532 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
533 * has not been read yet.
535 * @return the document read, or null.
537 public OpenRocketDocument getDocument() {
538 return handler.getDocument();
542 public ElementHandler openElement(String element, HashMap<String, String> attributes,
543 WarningSet warnings) {
545 // Check for unknown elements
546 if (!element.equals("openrocket")) {
547 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
551 // Check for first call
552 if (handler != null) {
553 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
558 // Check version number
559 String version = null;
560 String creator = attributes.remove("creator");
561 String docVersion = attributes.remove("version");
562 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
563 if (v.equals(docVersion)) {
568 if (version == null) {
569 String str = "Unsupported document version";
570 if (docVersion != null)
571 str += " " + docVersion;
572 if (creator != null && !creator.trim().equals(""))
573 str += " (written using '" + creator.trim() + "')";
574 str += ", attempting to read file anyway.";
578 handler = new OpenRocketContentHandler();
583 public void closeElement(String element, HashMap<String, String> attributes,
584 String content, WarningSet warnings) throws SAXException {
585 attributes.remove("version");
586 attributes.remove("creator");
587 super.closeElement(element, attributes, content, warnings);
595 * Handles the content of the <openrocket> tag.
597 class OpenRocketContentHandler extends ElementHandler {
598 private final OpenRocketDocument doc;
599 private final Rocket rocket;
601 private boolean rocketDefined = false;
602 private boolean simulationsDefined = false;
604 public OpenRocketContentHandler() {
605 this.rocket = new Rocket();
606 this.doc = new OpenRocketDocument(rocket);
610 public OpenRocketDocument getDocument() {
617 public ElementHandler openElement(String element, HashMap<String, String> attributes,
618 WarningSet warnings) {
620 if (element.equals("rocket")) {
623 .fromString("Multiple rocket designs within one document, "
624 + "ignoring later ones."));
627 rocketDefined = true;
628 return new ComponentParameterHandler(rocket);
631 if (element.equals("simulations")) {
632 if (simulationsDefined) {
634 .fromString("Multiple simulation definitions within one document, "
635 + "ignoring later ones."));
638 simulationsDefined = true;
639 return new SimulationsHandler(doc);
642 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
652 * A handler that creates components from the corresponding elements. The control of the
653 * contents is passed on to ComponentParameterHandler.
655 class ComponentHandler extends ElementHandler {
656 private final RocketComponent parent;
658 public ComponentHandler(RocketComponent parent) {
659 this.parent = parent;
663 public ElementHandler openElement(String element, HashMap<String, String> attributes,
664 WarningSet warnings) {
666 // Attempt to construct new component
667 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
669 if (constructor == null) {
670 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
676 c = constructor.newInstance();
677 } catch (InstantiationException e) {
678 throw new BugException("Error constructing component.", e);
679 } catch (IllegalAccessException e) {
680 throw new BugException("Error constructing component.", e);
681 } catch (InvocationTargetException e) {
682 throw Reflection.handleWrappedException(e);
687 return new ComponentParameterHandler(c);
693 * A handler that populates the parameters of a previously constructed rocket component.
694 * This uses the setters, or delegates the handling to another handler for specific
697 class ComponentParameterHandler extends ElementHandler {
698 private final RocketComponent component;
700 public ComponentParameterHandler(RocketComponent c) {
705 public ElementHandler openElement(String element, HashMap<String, String> attributes,
706 WarningSet warnings) {
708 // Check for specific elements that contain other elements
709 if (element.equals("subcomponents")) {
710 return new ComponentHandler(component);
712 if (element.equals("motormount")) {
713 if (!(component instanceof MotorMount)) {
714 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
717 return new MotorMountHandler((MotorMount) component);
719 if (element.equals("finpoints")) {
720 if (!(component instanceof FreeformFinSet)) {
721 warnings.add(Warning.fromString("Illegal component defined for fin points."));
724 return new FinSetPointHandler((FreeformFinSet) component);
726 if (element.equals("motorconfiguration")) {
727 if (!(component instanceof Rocket)) {
728 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
731 return new MotorConfigurationHandler((Rocket) component);
735 return PlainTextHandler.INSTANCE;
739 public void closeElement(String element, HashMap<String, String> attributes,
740 String content, WarningSet warnings) {
742 if (element.equals("subcomponents") || element.equals("motormount") ||
743 element.equals("finpoints") || element.equals("motorconfiguration")) {
747 // Search for the correct setter class
750 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
751 String setterKey = c.getSimpleName() + ":" + element;
752 Setter s = DocumentConfig.setters.get(setterKey);
755 s.set(component, content, attributes, warnings);
758 if (DocumentConfig.setters.containsKey(setterKey)) {
759 // Key exists but is null -> invalid parameter
765 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
766 + component.getComponentName() + ", ignoring."));
773 * A handler that reads the <point> specifications within the freeformfinset's
774 * <finpoints> elements.
776 class FinSetPointHandler extends ElementHandler {
777 private final FreeformFinSet finset;
778 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
780 public FinSetPointHandler(FreeformFinSet finset) {
781 this.finset = finset;
785 public ElementHandler openElement(String element, HashMap<String, String> attributes,
786 WarningSet warnings) {
787 return PlainTextHandler.INSTANCE;
792 public void closeElement(String element, HashMap<String, String> attributes,
793 String content, WarningSet warnings) throws SAXException {
795 String strx = attributes.remove("x");
796 String stry = attributes.remove("y");
797 if (strx == null || stry == null) {
798 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
802 double x = Double.parseDouble(strx);
803 double y = Double.parseDouble(stry);
804 coordinates.add(new Coordinate(x, y));
805 } catch (NumberFormatException e) {
806 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
810 super.closeElement(element, attributes, content, warnings);
814 public void endHandler(String element, HashMap<String, String> attributes,
815 String content, WarningSet warnings) {
817 finset.setPoints(coordinates.toArray(new Coordinate[0]));
818 } catch (IllegalFinPointException e) {
819 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
825 class MotorMountHandler extends ElementHandler {
826 private final MotorMount mount;
827 private MotorHandler motorHandler;
829 public MotorMountHandler(MotorMount mount) {
831 mount.setMotorMount(true);
835 public ElementHandler openElement(String element, HashMap<String, String> attributes,
836 WarningSet warnings) {
838 if (element.equals("motor")) {
839 motorHandler = new MotorHandler();
843 if (element.equals("ignitionevent") ||
844 element.equals("ignitiondelay") ||
845 element.equals("overhang")) {
846 return PlainTextHandler.INSTANCE;
849 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
856 public void closeElement(String element, HashMap<String, String> attributes,
857 String content, WarningSet warnings) throws SAXException {
859 if (element.equals("motor")) {
860 String id = attributes.get("configid");
861 if (id == null || id.equals("")) {
862 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
866 Motor motor = motorHandler.getMotor(warnings);
867 mount.setMotor(id, motor);
868 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
872 if (element.equals("ignitionevent")) {
873 MotorMount.IgnitionEvent event = null;
874 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
875 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
881 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
884 mount.setIgnitionEvent(event);
888 if (element.equals("ignitiondelay")) {
891 d = Double.parseDouble(content);
892 } catch (NumberFormatException nfe) {
893 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
896 mount.setIgnitionDelay(d);
900 if (element.equals("overhang")) {
903 d = Double.parseDouble(content);
904 } catch (NumberFormatException nfe) {
905 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
908 mount.setMotorOverhang(d);
912 super.closeElement(element, attributes, content, warnings);
919 class MotorConfigurationHandler extends ElementHandler {
920 private final Rocket rocket;
921 private String name = null;
922 private boolean inNameElement = false;
924 public MotorConfigurationHandler(Rocket rocket) {
925 this.rocket = rocket;
929 public ElementHandler openElement(String element, HashMap<String, String> attributes,
930 WarningSet warnings) {
932 if (inNameElement || !element.equals("name")) {
933 warnings.add(Warning.FILE_INVALID_PARAMETER);
936 inNameElement = true;
938 return PlainTextHandler.INSTANCE;
942 public void closeElement(String element, HashMap<String, String> attributes,
943 String content, WarningSet warnings) {
948 public void endHandler(String element, HashMap<String, String> attributes,
949 String content, WarningSet warnings) throws SAXException {
951 String configid = attributes.remove("configid");
952 if (configid == null || configid.equals("")) {
953 warnings.add(Warning.FILE_INVALID_PARAMETER);
957 if (!rocket.addMotorConfigurationID(configid)) {
958 warnings.add("Duplicate motor configuration ID used.");
962 if (name != null && name.trim().length() > 0) {
963 rocket.setMotorConfigurationName(configid, name);
966 if ("true".equals(attributes.remove("default"))) {
967 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
970 super.closeElement(element, attributes, content, warnings);
975 class MotorHandler extends ElementHandler {
976 private Motor.Type type = null;
977 private String manufacturer = null;
978 private String designation = null;
979 private String digest = null;
980 private double diameter = Double.NaN;
981 private double length = Double.NaN;
982 private double delay = Double.NaN;
985 public ElementHandler openElement(String element, HashMap<String, String> attributes,
986 WarningSet warnings) {
987 return PlainTextHandler.INSTANCE;
992 * Return the motor to use, or null.
994 public Motor getMotor(WarningSet warnings) {
995 if (designation == null) {
996 warnings.add(Warning.fromString("No motor specified, ignoring."));
1000 List<? extends Motor> motors = Application.getMotorSetDatabase().findMotors(type, manufacturer,
1001 designation, diameter, length);
1004 if (motors.size() == 0) {
1005 String str = "No motor with designation '" + designation + "'";
1006 if (manufacturer != null)
1007 str += " for manufacturer '" + manufacturer + "'";
1014 if (motors.size() == 1) {
1015 Motor m = motors.get(0);
1016 if (digest != null && !digest.equals(m.getDigest())) {
1017 String str = "Motor with designation '" + designation + "'";
1018 if (manufacturer != null)
1019 str += " for manufacturer '" + manufacturer + "'";
1020 str += " has differing thrust curve than the original.";
1026 // Multiple motors, check digest for which one to use
1027 if (digest != null) {
1029 // Check for motor with correct digest
1030 for (Motor m : motors) {
1031 if (digest.equals(m.getDigest())) {
1035 String str = "Motor with designation '" + designation + "'";
1036 if (manufacturer != null)
1037 str += " for manufacturer '" + manufacturer + "'";
1038 str += " has differing thrust curve than the original.";
1043 // No digest, check for preferred digest (OpenRocket <= 1.1.0)
1044 // TODO: MEDIUM: This should only be done for document versions 1.1 and below
1045 for (Motor m : motors) {
1046 if (PreferredMotorDigests.DIGESTS.contains(m.getDigest())) {
1051 String str = "Multiple motors with designation '" + designation + "'";
1052 if (manufacturer != null)
1053 str += " for manufacturer '" + manufacturer + "'";
1054 str += " found, one chosen arbitrarily.";
1058 return motors.get(0);
1062 * Return the delay to use for the motor.
1064 public double getDelay(WarningSet warnings) {
1065 if (Double.isNaN(delay)) {
1066 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1067 return Motor.PLUGGED;
1074 public void closeElement(String element, HashMap<String, String> attributes,
1075 String content, WarningSet warnings) throws SAXException {
1077 content = content.trim();
1079 if (element.equals("type")) {
1083 for (Motor.Type t : Motor.Type.values()) {
1084 if (t.name().toLowerCase().equals(content.trim())) {
1090 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1093 } else if (element.equals("manufacturer")) {
1096 manufacturer = content.trim();
1098 } else if (element.equals("designation")) {
1101 designation = content.trim();
1103 } else if (element.equals("digest")) {
1106 digest = content.trim();
1108 } else if (element.equals("diameter")) {
1111 diameter = Double.NaN;
1113 diameter = Double.parseDouble(content.trim());
1114 } catch (NumberFormatException e) {
1117 if (Double.isNaN(diameter)) {
1118 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1121 } else if (element.equals("length")) {
1124 length = Double.NaN;
1126 length = Double.parseDouble(content.trim());
1127 } catch (NumberFormatException ignore) {
1130 if (Double.isNaN(length)) {
1131 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1134 } else if (element.equals("delay")) {
1138 if (content.equals("none")) {
1139 delay = Motor.PLUGGED;
1142 delay = Double.parseDouble(content.trim());
1143 } catch (NumberFormatException ignore) {
1146 if (Double.isNaN(delay)) {
1147 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1153 super.closeElement(element, attributes, content, warnings);
1161 class SimulationsHandler extends ElementHandler {
1162 private final OpenRocketDocument doc;
1163 private SingleSimulationHandler handler;
1165 public SimulationsHandler(OpenRocketDocument doc) {
1170 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1171 WarningSet warnings) {
1173 if (!element.equals("simulation")) {
1174 warnings.add("Unknown element '" + element + "', ignoring.");
1178 handler = new SingleSimulationHandler(doc);
1183 public void closeElement(String element, HashMap<String, String> attributes,
1184 String content, WarningSet warnings) throws SAXException {
1185 attributes.remove("status");
1186 super.closeElement(element, attributes, content, warnings);
1192 class SingleSimulationHandler extends ElementHandler {
1194 private final OpenRocketDocument doc;
1196 private String name;
1198 private SimulationConditionsHandler conditionHandler;
1199 private FlightDataHandler dataHandler;
1201 private final List<String> listeners = new ArrayList<String>();
1203 public SingleSimulationHandler(OpenRocketDocument doc) {
1210 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1211 WarningSet warnings) {
1213 if (element.equals("name") || element.equals("simulator") ||
1214 element.equals("calculator") || element.equals("listener")) {
1215 return PlainTextHandler.INSTANCE;
1216 } else if (element.equals("conditions")) {
1217 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1218 return conditionHandler;
1219 } else if (element.equals("flightdata")) {
1220 dataHandler = new FlightDataHandler();
1223 warnings.add("Unknown element '" + element + "', ignoring.");
1229 public void closeElement(String element, HashMap<String, String> attributes,
1230 String content, WarningSet warnings) {
1232 if (element.equals("name")) {
1234 } else if (element.equals("simulator")) {
1235 if (!content.trim().equals("RK4Simulator")) {
1236 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1238 } else if (element.equals("calculator")) {
1239 if (!content.trim().equals("BarrowmanCalculator")) {
1240 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1242 } else if (element.equals("listener") && content.trim().length() > 0) {
1243 listeners.add(content.trim());
1249 public void endHandler(String element, HashMap<String, String> attributes,
1250 String content, WarningSet warnings) {
1252 String s = attributes.get("status");
1253 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1254 if (status == null) {
1255 warnings.add("Simulation status unknown, assuming outdated.");
1256 status = Simulation.Status.OUTDATED;
1259 SimulationOptions conditions;
1260 if (conditionHandler != null) {
1261 conditions = conditionHandler.getConditions();
1263 warnings.add("Simulation conditions not defined, using defaults.");
1264 conditions = new SimulationOptions(doc.getRocket());
1268 name = "Simulation";
1271 if (dataHandler == null)
1274 data = dataHandler.getFlightData();
1276 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1277 conditions, listeners, data);
1279 doc.addSimulation(simulation);
1285 class SimulationConditionsHandler extends ElementHandler {
1286 private SimulationOptions conditions;
1287 private AtmosphereHandler atmosphereHandler;
1289 public SimulationConditionsHandler(Rocket rocket) {
1290 conditions = new SimulationOptions(rocket);
1291 // Set up default loading settings (which may differ from the new defaults)
1292 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1295 public SimulationOptions getConditions() {
1300 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1301 WarningSet warnings) {
1302 if (element.equals("atmosphere")) {
1303 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1304 return atmosphereHandler;
1306 return PlainTextHandler.INSTANCE;
1310 public void closeElement(String element, HashMap<String, String> attributes,
1311 String content, WarningSet warnings) {
1313 double d = Double.NaN;
1315 d = Double.parseDouble(content);
1316 } catch (NumberFormatException ignore) {
1320 if (element.equals("configid")) {
1321 if (content.equals("")) {
1322 conditions.setMotorConfigurationID(null);
1324 conditions.setMotorConfigurationID(content);
1326 } else if (element.equals("launchrodlength")) {
1327 if (Double.isNaN(d)) {
1328 warnings.add("Illegal launch rod length defined, ignoring.");
1330 conditions.setLaunchRodLength(d);
1332 } else if (element.equals("launchrodangle")) {
1333 if (Double.isNaN(d)) {
1334 warnings.add("Illegal launch rod angle defined, ignoring.");
1336 conditions.setLaunchRodAngle(d * Math.PI / 180);
1338 } else if (element.equals("launchroddirection")) {
1339 if (Double.isNaN(d)) {
1340 warnings.add("Illegal launch rod direction defined, ignoring.");
1342 conditions.setLaunchRodDirection(d * Math.PI / 180);
1344 } else if (element.equals("windaverage")) {
1345 if (Double.isNaN(d)) {
1346 warnings.add("Illegal average windspeed defined, ignoring.");
1348 conditions.setWindSpeedAverage(d);
1350 } else if (element.equals("windturbulence")) {
1351 if (Double.isNaN(d)) {
1352 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1354 conditions.setWindTurbulenceIntensity(d);
1356 } else if (element.equals("launchaltitude")) {
1357 if (Double.isNaN(d)) {
1358 warnings.add("Illegal launch altitude defined, ignoring.");
1360 conditions.setLaunchAltitude(d);
1362 } else if (element.equals("launchlatitude")) {
1363 if (Double.isNaN(d)) {
1364 warnings.add("Illegal launch latitude defined, ignoring.");
1366 conditions.setLaunchLatitude(d);
1368 } else if (element.equals("launchlongitude")) {
1369 if (Double.isNaN(d)) {
1370 warnings.add("Illegal launch longitude.");
1372 conditions.setLaunchLongitude(d);
1374 } else if (element.equals("geodeticmethod")) {
1375 GeodeticComputationStrategy gcs =
1376 (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1378 conditions.setGeodeticComputation(gcs);
1380 warnings.add("Unknown geodetic computation method '" + content + "'");
1382 } else if (element.equals("atmosphere")) {
1383 atmosphereHandler.storeSettings(conditions, warnings);
1384 } else if (element.equals("timestep")) {
1385 if (Double.isNaN(d)) {
1386 warnings.add("Illegal time step defined, ignoring.");
1388 conditions.setTimeStep(d);
1395 class AtmosphereHandler extends ElementHandler {
1396 private final String model;
1397 private double temperature = Double.NaN;
1398 private double pressure = Double.NaN;
1400 public AtmosphereHandler(String model) {
1405 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1406 WarningSet warnings) {
1407 return PlainTextHandler.INSTANCE;
1411 public void closeElement(String element, HashMap<String, String> attributes,
1412 String content, WarningSet warnings) throws SAXException {
1414 double d = Double.NaN;
1416 d = Double.parseDouble(content);
1417 } catch (NumberFormatException ignore) {
1420 if (element.equals("basetemperature")) {
1421 if (Double.isNaN(d)) {
1422 warnings.add("Illegal base temperature specified, ignoring.");
1425 } else if (element.equals("basepressure")) {
1426 if (Double.isNaN(d)) {
1427 warnings.add("Illegal base pressure specified, ignoring.");
1431 super.closeElement(element, attributes, content, warnings);
1436 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1437 if (!Double.isNaN(pressure)) {
1438 cond.setLaunchPressure(pressure);
1440 if (!Double.isNaN(temperature)) {
1441 cond.setLaunchTemperature(temperature);
1444 if ("isa".equals(model)) {
1445 cond.setISAAtmosphere(true);
1446 } else if ("extendedisa".equals(model)) {
1447 cond.setISAAtmosphere(false);
1449 cond.setISAAtmosphere(true);
1450 warnings.add("Unknown atmospheric model, using ISA.");
1457 class FlightDataHandler extends ElementHandler {
1459 private FlightDataBranchHandler dataHandler;
1460 private WarningSet warningSet = new WarningSet();
1461 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1463 private FlightData data;
1465 public FlightData getFlightData() {
1470 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1471 WarningSet warnings) {
1473 if (element.equals("warning")) {
1474 return PlainTextHandler.INSTANCE;
1476 if (element.equals("databranch")) {
1477 if (attributes.get("name") == null || attributes.get("types") == null) {
1478 warnings.add("Illegal flight data definition, ignoring.");
1481 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1482 attributes.get("types"));
1486 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1492 public void closeElement(String element, HashMap<String, String> attributes,
1493 String content, WarningSet warnings) {
1495 if (element.equals("databranch")) {
1496 FlightDataBranch branch = dataHandler.getBranch();
1497 if (branch.getLength() > 0) {
1498 branches.add(branch);
1500 } else if (element.equals("warning")) {
1501 warningSet.add(Warning.fromString(content));
1507 public void endHandler(String element, HashMap<String, String> attributes,
1508 String content, WarningSet warnings) {
1510 if (branches.size() > 0) {
1511 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1513 double maxAltitude = Double.NaN;
1514 double maxVelocity = Double.NaN;
1515 double maxAcceleration = Double.NaN;
1516 double maxMach = Double.NaN;
1517 double timeToApogee = Double.NaN;
1518 double flightTime = Double.NaN;
1519 double groundHitVelocity = Double.NaN;
1520 double launchRodVelocity = Double.NaN;
1521 double deploymentVelocity = Double.NaN;
1524 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1525 } catch (NumberFormatException ignore) {
1528 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1529 } catch (NumberFormatException ignore) {
1532 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1533 } catch (NumberFormatException ignore) {
1536 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1537 } catch (NumberFormatException ignore) {
1540 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1541 } catch (NumberFormatException ignore) {
1544 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1545 } catch (NumberFormatException ignore) {
1549 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1550 } catch (NumberFormatException ignore) {
1553 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1554 } catch (NumberFormatException ignore) {
1557 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1558 } catch (NumberFormatException ignore) {
1561 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1562 timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1565 data.getWarningSet().addAll(warningSet);
1573 class FlightDataBranchHandler extends ElementHandler {
1574 private final FlightDataType[] types;
1575 private final FlightDataBranch branch;
1577 public FlightDataBranchHandler(String name, String typeList) {
1578 String[] split = typeList.split(",");
1579 types = new FlightDataType[split.length];
1580 for (int i = 0; i < split.length; i++) {
1581 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1584 // TODO: LOW: May throw an IllegalArgumentException
1585 branch = new FlightDataBranch(name, types);
1588 public FlightDataBranch getBranch() {
1594 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1595 WarningSet warnings) {
1597 if (element.equals("datapoint"))
1598 return PlainTextHandler.INSTANCE;
1599 if (element.equals("event"))
1600 return PlainTextHandler.INSTANCE;
1602 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1608 public void closeElement(String element, HashMap<String, String> attributes,
1609 String content, WarningSet warnings) {
1611 if (element.equals("event")) {
1613 FlightEvent.Type type;
1616 time = DocumentConfig.stringToDouble(attributes.get("time"));
1617 } catch (NumberFormatException e) {
1618 warnings.add("Illegal event specification, ignoring.");
1622 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1624 warnings.add("Illegal event specification, ignoring.");
1628 branch.addEvent(new FlightEvent(type, time));
1632 if (!element.equals("datapoint")) {
1633 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1637 // element == "datapoint"
1640 // Check line format
1641 String[] split = content.split(",");
1642 if (split.length != types.length) {
1643 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1647 // Parse the doubles
1648 double[] values = new double[split.length];
1649 for (int i = 0; i < values.length; i++) {
1651 values[i] = DocumentConfig.stringToDouble(split[i]);
1652 } catch (NumberFormatException e) {
1653 warnings.add("Data point format error, ignoring point.");
1658 // Add point to branch
1660 for (int i = 0; i < types.length; i++) {
1661 branch.setValue(types[i], values[i]);
1670 ///////////////// Setters implementation
1676 * Set the specified value to the given component.
1678 * @param component the component to which to set.
1679 * @param value the value within the element.
1680 * @param attributes attributes for the element.
1681 * @param warnings the warning set to use.
1683 public void set(RocketComponent component, String value,
1684 HashMap<String, String> attributes, WarningSet warnings);
1688 //// StringSetter - sets the value to the contained String
1689 class StringSetter implements Setter {
1690 private final Reflection.Method setMethod;
1692 public StringSetter(Reflection.Method set) {
1697 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1698 WarningSet warnings) {
1699 setMethod.invoke(c, s);
1703 //// IntSetter - set an integer value
1704 class IntSetter implements Setter {
1705 private final Reflection.Method setMethod;
1707 public IntSetter(Reflection.Method set) {
1712 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1713 WarningSet warnings) {
1715 int n = Integer.parseInt(s);
1716 setMethod.invoke(c, n);
1717 } catch (NumberFormatException e) {
1718 warnings.add(Warning.FILE_INVALID_PARAMETER);
1724 //// BooleanSetter - set a boolean value
1725 class BooleanSetter implements Setter {
1726 private final Reflection.Method setMethod;
1728 public BooleanSetter(Reflection.Method set) {
1733 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1734 WarningSet warnings) {
1737 if (s.equalsIgnoreCase("true")) {
1738 setMethod.invoke(c, true);
1739 } else if (s.equalsIgnoreCase("false")) {
1740 setMethod.invoke(c, false);
1742 warnings.add(Warning.FILE_INVALID_PARAMETER);
1749 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1750 //// calls a setXXX(boolean) method.
1751 class DoubleSetter implements Setter {
1752 private final Reflection.Method setMethod;
1753 private final String specialString;
1754 private final Reflection.Method specialMethod;
1755 private final double multiplier;
1758 * Set only the double value.
1759 * @param set set method for the double value.
1761 public DoubleSetter(Reflection.Method set) {
1762 this.setMethod = set;
1763 this.specialString = null;
1764 this.specialMethod = null;
1765 this.multiplier = 1.0;
1769 * Multiply with the given multiplier and set the double value.
1770 * @param set set method for the double value.
1771 * @param mul multiplier.
1773 public DoubleSetter(Reflection.Method set, double mul) {
1774 this.setMethod = set;
1775 this.specialString = null;
1776 this.specialMethod = null;
1777 this.multiplier = mul;
1781 * Set the double value, or if the value equals the special string, use the
1782 * special setter and set it to true.
1784 * @param set double setter.
1785 * @param special special string
1786 * @param specialMethod boolean setter.
1788 public DoubleSetter(Reflection.Method set, String special,
1789 Reflection.Method specialMethod) {
1790 this.setMethod = set;
1791 this.specialString = special;
1792 this.specialMethod = specialMethod;
1793 this.multiplier = 1.0;
1798 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1799 WarningSet warnings) {
1803 // Check for special case
1804 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1805 specialMethod.invoke(c, true);
1811 double d = Double.parseDouble(s);
1812 setMethod.invoke(c, d * multiplier);
1813 } catch (NumberFormatException e) {
1814 warnings.add(Warning.FILE_INVALID_PARAMETER);
1820 class OverrideSetter implements Setter {
1821 private final Reflection.Method setMethod;
1822 private final Reflection.Method enabledMethod;
1824 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1825 this.setMethod = set;
1826 this.enabledMethod = enabledMethod;
1830 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1831 WarningSet warnings) {
1834 double d = Double.parseDouble(s);
1835 setMethod.invoke(c, d);
1836 enabledMethod.invoke(c, true);
1837 } catch (NumberFormatException e) {
1838 warnings.add(Warning.FILE_INVALID_PARAMETER);
1843 //// EnumSetter - sets a generic enum type
1844 class EnumSetter<T extends Enum<T>> implements Setter {
1845 private final Reflection.Method setter;
1846 private final Class<T> enumClass;
1848 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1850 this.enumClass = enumClass;
1854 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1855 WarningSet warnings) {
1857 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1858 if (setEnum == null) {
1859 warnings.add(Warning.FILE_INVALID_PARAMETER);
1863 setter.invoke(c, setEnum);
1868 //// ColorSetter - sets a Color value
1869 class ColorSetter implements Setter {
1870 private final Reflection.Method setMethod;
1872 public ColorSetter(Reflection.Method set) {
1877 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1878 WarningSet warnings) {
1880 String red = attributes.get("red");
1881 String green = attributes.get("green");
1882 String blue = attributes.get("blue");
1884 if (red == null || green == null || blue == null) {
1885 warnings.add(Warning.FILE_INVALID_PARAMETER);
1891 r = Integer.parseInt(red);
1892 g = Integer.parseInt(green);
1893 b = Integer.parseInt(blue);
1894 } catch (NumberFormatException e) {
1895 warnings.add(Warning.FILE_INVALID_PARAMETER);
1899 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1900 warnings.add(Warning.FILE_INVALID_PARAMETER);
1904 Color color = new Color(r, g, b);
1905 setMethod.invoke(c, color);
1907 if (!s.trim().equals("")) {
1908 warnings.add(Warning.FILE_INVALID_PARAMETER);
1915 class MaterialSetter implements Setter {
1916 private final Reflection.Method setMethod;
1917 private final Material.Type type;
1919 public MaterialSetter(Reflection.Method set, Material.Type type) {
1920 this.setMethod = set;
1925 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1926 WarningSet warnings) {
1932 if (name.equals("")) {
1933 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1940 str = attributes.remove("density");
1942 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1946 density = Double.parseDouble(str);
1947 } catch (NumberFormatException e) {
1948 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1953 // double thickness = 0;
1954 // str = attributes.remove("thickness");
1957 // thickness = Double.parseDouble(str);
1958 // } catch (NumberFormatException e){
1959 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1963 // Check type if specified
1964 str = attributes.remove("type");
1965 if (str != null && !type.name().toLowerCase().equals(str)) {
1966 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1970 mat = Databases.findMaterial(type, name, density, false);
1972 setMethod.invoke(c, mat);
1979 class PositionSetter implements Setter {
1982 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1983 WarningSet warnings) {
1985 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1986 RocketComponent.Position.class);
1988 warnings.add(Warning.FILE_INVALID_PARAMETER);
1994 pos = Double.parseDouble(value);
1995 } catch (NumberFormatException e) {
1996 warnings.add(Warning.FILE_INVALID_PARAMETER);
2000 if (c instanceof FinSet) {
2001 ((FinSet) c).setRelativePosition(type);
2002 c.setPositionValue(pos);
2003 } else if (c instanceof LaunchLug) {
2004 ((LaunchLug) c).setRelativePosition(type);
2005 c.setPositionValue(pos);
2006 } else if (c instanceof InternalComponent) {
2007 ((InternalComponent) c).setRelativePosition(type);
2008 c.setPositionValue(pos);
2010 warnings.add(Warning.FILE_INVALID_PARAMETER);
2017 class FinTabPositionSetter extends DoubleSetter {
2019 public FinTabPositionSetter() {
2020 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2024 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2025 WarningSet warnings) {
2027 if (!(c instanceof FinSet)) {
2028 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2031 String relative = attributes.get("relativeto");
2032 FinSet.TabRelativePosition position =
2033 (TabRelativePosition) DocumentConfig.findEnum(relative,
2034 FinSet.TabRelativePosition.class);
2036 if (position != null) {
2038 ((FinSet) c).setTabRelativePosition(position);
2041 if (relative == null) {
2042 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2044 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2048 super.set(c, s, attributes, warnings);
2055 class ClusterConfigurationSetter implements Setter {
2058 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2059 WarningSet warnings) {
2061 if (!(component instanceof Clusterable)) {
2062 warnings.add("Illegal component defined as cluster.");
2066 ClusterConfiguration config = null;
2067 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2068 if (c.getXMLName().equals(value)) {
2074 if (config == null) {
2075 warnings.add("Illegal cluster configuration specified.");
2079 ((Clusterable) component).setClusterConfiguration(config);