1 package net.sf.openrocket.file;
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.StorageOptions;
18 import net.sf.openrocket.document.Simulation.Status;
19 import net.sf.openrocket.file.simplesax.ElementHandler;
20 import net.sf.openrocket.file.simplesax.PlainTextHandler;
21 import net.sf.openrocket.file.simplesax.SimpleSAX;
22 import net.sf.openrocket.material.Material;
23 import net.sf.openrocket.rocketcomponent.BodyComponent;
24 import net.sf.openrocket.rocketcomponent.BodyTube;
25 import net.sf.openrocket.rocketcomponent.Bulkhead;
26 import net.sf.openrocket.rocketcomponent.CenteringRing;
27 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
28 import net.sf.openrocket.rocketcomponent.Clusterable;
29 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
30 import net.sf.openrocket.rocketcomponent.EngineBlock;
31 import net.sf.openrocket.rocketcomponent.ExternalComponent;
32 import net.sf.openrocket.rocketcomponent.FinSet;
33 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
34 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
35 import net.sf.openrocket.rocketcomponent.InnerTube;
36 import net.sf.openrocket.rocketcomponent.InternalComponent;
37 import net.sf.openrocket.rocketcomponent.LaunchLug;
38 import net.sf.openrocket.rocketcomponent.MassComponent;
39 import net.sf.openrocket.rocketcomponent.MassObject;
40 import net.sf.openrocket.rocketcomponent.Motor;
41 import net.sf.openrocket.rocketcomponent.MotorMount;
42 import net.sf.openrocket.rocketcomponent.NoseCone;
43 import net.sf.openrocket.rocketcomponent.Parachute;
44 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
45 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
46 import net.sf.openrocket.rocketcomponent.ReferenceType;
47 import net.sf.openrocket.rocketcomponent.RingComponent;
48 import net.sf.openrocket.rocketcomponent.Rocket;
49 import net.sf.openrocket.rocketcomponent.RocketComponent;
50 import net.sf.openrocket.rocketcomponent.ShockCord;
51 import net.sf.openrocket.rocketcomponent.Stage;
52 import net.sf.openrocket.rocketcomponent.Streamer;
53 import net.sf.openrocket.rocketcomponent.StructuralComponent;
54 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
55 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
56 import net.sf.openrocket.rocketcomponent.Transition;
57 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
58 import net.sf.openrocket.rocketcomponent.TubeCoupler;
59 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
60 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
61 import net.sf.openrocket.simulation.FlightData;
62 import net.sf.openrocket.simulation.FlightDataBranch;
63 import net.sf.openrocket.simulation.FlightEvent;
64 import net.sf.openrocket.simulation.SimulationConditions;
65 import net.sf.openrocket.simulation.FlightEvent.Type;
66 import net.sf.openrocket.unit.UnitGroup;
67 import net.sf.openrocket.util.Coordinate;
68 import net.sf.openrocket.util.LineStyle;
69 import net.sf.openrocket.util.Reflection;
71 import org.xml.sax.InputSource;
72 import org.xml.sax.SAXException;
76 * Class that loads a rocket definition from an OpenRocket rocket file.
78 * This class uses SAX to read the XML file format. The
79 * {@link #loadFromStream(InputStream)} method simply sets the system up and
80 * starts the parsing, while the actual logic is in the private inner class
81 * <code>OpenRocketHandler</code>.
83 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
86 public class OpenRocketLoader extends RocketLoader {
89 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
91 InputSource xmlSource = new InputSource(source);
92 OpenRocketHandler handler = new OpenRocketHandler();
96 SimpleSAX.readXML(xmlSource, handler, warnings);
97 } catch (SAXException e) {
98 throw new RocketLoadException("Malformed XML in input.", e);
102 OpenRocketDocument doc = handler.getDocument();
103 doc.getDefaultConfiguration().setAllStages();
105 // Deduce suitable time skip
106 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
107 for (Simulation s: doc.getSimulations()) {
108 if (s.getStatus() == Simulation.Status.EXTERNAL ||
109 s.getStatus() == Simulation.Status.NOT_SIMULATED)
111 if (s.getSimulatedData() == null)
113 if (s.getSimulatedData().getBranchCount() == 0)
115 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
118 List<Double> list = branch.get(FlightDataBranch.TYPE_TIME);
122 double previousTime = Double.NaN;
123 for (double time: list) {
124 if (time - previousTime < timeSkip)
125 timeSkip = time-previousTime;
130 timeSkip = Math.rint(timeSkip*100)/100;
132 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
133 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
134 doc.getDefaultStorageOptions().setExplicitlySet(false);
144 class DocumentConfig {
146 /* Remember to update OpenRocketSaver as well! */
147 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0" };
150 //////// Component constructors
151 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
154 // External components
155 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
156 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
157 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
158 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
159 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
160 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
161 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
163 // Internal components
164 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
165 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
166 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
167 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
168 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
170 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
171 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
172 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
173 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
176 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
178 } catch (NoSuchMethodException e) {
179 throw new RuntimeException(
180 "Error in constructing the 'constructors' HashMap.");
185 //////// Parameter setters
187 * The keys are of the form Class:param, where Class is the class name and param
188 * the element name. Setters are searched for in descending class order.
189 * A setter of null means setting the parameter is not allowed.
191 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
194 setters.put("RocketComponent:name", new StringSetter(
195 Reflection.findMethodStatic(RocketComponent.class, "setName", String.class)));
196 setters.put("RocketComponent:color", new ColorSetter(
197 Reflection.findMethodStatic(RocketComponent.class, "setColor", Color.class)));
198 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
199 Reflection.findMethodStatic(RocketComponent.class, "setLineStyle", LineStyle.class),
201 setters.put("RocketComponent:position", new PositionSetter());
202 setters.put("RocketComponent:overridemass", new OverrideSetter(
203 Reflection.findMethodStatic(RocketComponent.class, "setOverrideMass", double.class),
204 Reflection.findMethodStatic(RocketComponent.class, "setMassOverridden", boolean.class)));
205 setters.put("RocketComponent:overridecg", new OverrideSetter(
206 Reflection.findMethodStatic(RocketComponent.class, "setOverrideCGX", double.class),
207 Reflection.findMethodStatic(RocketComponent.class, "setCGOverridden", boolean.class)));
208 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
209 Reflection.findMethodStatic(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
210 setters.put("RocketComponent:comment", new StringSetter(
211 Reflection.findMethodStatic(RocketComponent.class, "setComment", String.class)));
214 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
215 Reflection.findMethodStatic(ExternalComponent.class, "setFinish", Finish.class),
217 setters.put("ExternalComponent:material", new MaterialSetter(
218 Reflection.findMethodStatic(ExternalComponent.class, "setMaterial", Material.class),
219 Material.Type.BULK));
222 setters.put("BodyComponent:length", new DoubleSetter(
223 Reflection.findMethodStatic(BodyComponent.class, "setLength", double.class)));
225 // SymmetricComponent
226 setters.put("SymmetricComponent:thickness", new DoubleSetter(
227 Reflection.findMethodStatic(SymmetricComponent.class,"setThickness", double.class),
229 Reflection.findMethodStatic(SymmetricComponent.class,"setFilled", boolean.class)));
232 setters.put("BodyTube:radius", new DoubleSetter(
233 Reflection.findMethodStatic(BodyTube.class, "setRadius", double.class),
235 Reflection.findMethodStatic(BodyTube.class,"setRadiusAutomatic", boolean.class)));
238 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
239 Reflection.findMethodStatic(Transition.class, "setType", Transition.Shape.class),
240 Transition.Shape.class));
241 setters.put("Transition:shapeclipped", new BooleanSetter(
242 Reflection.findMethodStatic(Transition.class, "setClipped", boolean.class)));
243 setters.put("Transition:shapeparameter", new DoubleSetter(
244 Reflection.findMethodStatic(Transition.class, "setShapeParameter", double.class)));
246 setters.put("Transition:foreradius", new DoubleSetter(
247 Reflection.findMethodStatic(Transition.class, "setForeRadius", double.class),
249 Reflection.findMethodStatic(Transition.class, "setForeRadiusAutomatic", boolean.class)));
250 setters.put("Transition:aftradius", new DoubleSetter(
251 Reflection.findMethodStatic(Transition.class, "setAftRadius", double.class),
253 Reflection.findMethodStatic(Transition.class, "setAftRadiusAutomatic", boolean.class)));
255 setters.put("Transition:foreshoulderradius", new DoubleSetter(
256 Reflection.findMethodStatic(Transition.class, "setForeShoulderRadius", double.class)));
257 setters.put("Transition:foreshoulderlength", new DoubleSetter(
258 Reflection.findMethodStatic(Transition.class, "setForeShoulderLength", double.class)));
259 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
260 Reflection.findMethodStatic(Transition.class, "setForeShoulderThickness", double.class)));
261 setters.put("Transition:foreshouldercapped", new BooleanSetter(
262 Reflection.findMethodStatic(Transition.class, "setForeShoulderCapped", boolean.class)));
264 setters.put("Transition:aftshoulderradius", new DoubleSetter(
265 Reflection.findMethodStatic(Transition.class, "setAftShoulderRadius", double.class)));
266 setters.put("Transition:aftshoulderlength", new DoubleSetter(
267 Reflection.findMethodStatic(Transition.class, "setAftShoulderLength", double.class)));
268 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
269 Reflection.findMethodStatic(Transition.class, "setAftShoulderThickness", double.class)));
270 setters.put("Transition:aftshouldercapped", new BooleanSetter(
271 Reflection.findMethodStatic(Transition.class, "setAftShoulderCapped", boolean.class)));
273 // NoseCone - disable disallowed elements
274 setters.put("NoseCone:foreradius", null);
275 setters.put("NoseCone:foreshoulderradius", null);
276 setters.put("NoseCone:foreshoulderlength", null);
277 setters.put("NoseCone:foreshoulderthickness", null);
278 setters.put("NoseCone:foreshouldercapped", null);
281 setters.put("FinSet:fincount", new IntSetter(
282 Reflection.findMethodStatic(FinSet.class, "setFinCount", int.class)));
283 setters.put("FinSet:rotation", new DoubleSetter(
284 Reflection.findMethodStatic(FinSet.class, "setBaseRotation", double.class), Math.PI/180.0));
285 setters.put("FinSet:thickness", new DoubleSetter(
286 Reflection.findMethodStatic(FinSet.class, "setThickness", double.class)));
287 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
288 Reflection.findMethodStatic(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
289 FinSet.CrossSection.class));
290 setters.put("FinSet:cant", new DoubleSetter(
291 Reflection.findMethodStatic(FinSet.class, "setCantAngle", double.class), Math.PI/180.0));
294 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
295 Reflection.findMethodStatic(TrapezoidFinSet.class, "setRootChord", double.class)));
296 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
297 Reflection.findMethodStatic(TrapezoidFinSet.class, "setTipChord", double.class)));
298 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
299 Reflection.findMethodStatic(TrapezoidFinSet.class, "setSweep", double.class)));
300 setters.put("TrapezoidFinSet:height", new DoubleSetter(
301 Reflection.findMethodStatic(TrapezoidFinSet.class, "setHeight", double.class)));
304 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
305 Reflection.findMethodStatic(EllipticalFinSet.class, "setLength", double.class)));
306 setters.put("EllipticalFinSet:height", new DoubleSetter(
307 Reflection.findMethodStatic(EllipticalFinSet.class, "setHeight", double.class)));
309 // FreeformFinSet points handled as a special handler
312 setters.put("LaunchLug:radius", new DoubleSetter(
313 Reflection.findMethodStatic(LaunchLug.class, "setRadius", double.class)));
314 setters.put("LaunchLug:length", new DoubleSetter(
315 Reflection.findMethodStatic(LaunchLug.class, "setLength", double.class)));
316 setters.put("LaunchLug:thickness", new DoubleSetter(
317 Reflection.findMethodStatic(LaunchLug.class, "setThickness", double.class)));
318 setters.put("LaunchLug:radialdirection", new DoubleSetter(
319 Reflection.findMethodStatic(LaunchLug.class, "setRadialDirection", double.class),
322 // InternalComponent - nothing
324 // StructuralComponent
325 setters.put("StructuralComponent:material", new MaterialSetter(
326 Reflection.findMethodStatic(StructuralComponent.class, "setMaterial", Material.class),
327 Material.Type.BULK));
330 setters.put("RingComponent:length", new DoubleSetter(
331 Reflection.findMethodStatic(RingComponent.class, "setLength", double.class)));
332 setters.put("RingComponent:radialposition", new DoubleSetter(
333 Reflection.findMethodStatic(RingComponent.class, "setRadialPosition", double.class)));
334 setters.put("RingComponent:radialdirection", new DoubleSetter(
335 Reflection.findMethodStatic(RingComponent.class, "setRadialDirection", double.class),
338 // ThicknessRingComponent - radius on separate components due to differing automatics
339 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
340 Reflection.findMethodStatic(ThicknessRingComponent.class, "setThickness", double.class)));
343 setters.put("EngineBlock:outerradius", new DoubleSetter(
344 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadius", double.class),
346 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
349 setters.put("TubeCoupler:outerradius", new DoubleSetter(
350 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadius", double.class),
352 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
355 setters.put("InnerTube:outerradius", new DoubleSetter(
356 Reflection.findMethodStatic(InnerTube.class, "setOuterRadius", double.class)));
357 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
358 setters.put("InnerTube:clusterscale", new DoubleSetter(
359 Reflection.findMethodStatic(InnerTube.class, "setClusterScale", double.class)));
360 setters.put("InnerTube:clusterrotation", new DoubleSetter(
361 Reflection.findMethodStatic(InnerTube.class, "setClusterRotation", double.class),
364 // RadiusRingComponent
367 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
368 Reflection.findMethodStatic(RadiusRingComponent.class, "setInnerRadius", double.class)));
369 setters.put("Bulkhead:outerradius", new DoubleSetter(
370 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadius", double.class),
372 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
375 setters.put("CenteringRing:innerradius", new DoubleSetter(
376 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadius", double.class),
378 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
379 setters.put("CenteringRing:outerradius", new DoubleSetter(
380 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadius", double.class),
382 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
386 setters.put("MassObject:packedlength", new DoubleSetter(
387 Reflection.findMethodStatic(MassObject.class, "setLength", double.class)));
388 setters.put("MassObject:packedradius", new DoubleSetter(
389 Reflection.findMethodStatic(MassObject.class, "setRadius", double.class)));
390 setters.put("MassObject:radialposition", new DoubleSetter(
391 Reflection.findMethodStatic(MassObject.class, "setRadialPosition", double.class)));
392 setters.put("MassObject:radialdirection", new DoubleSetter(
393 Reflection.findMethodStatic(MassObject.class, "setRadialDirection", double.class),
397 setters.put("MassComponent:mass", new DoubleSetter(
398 Reflection.findMethodStatic(MassComponent.class, "setComponentMass", double.class)));
401 setters.put("ShockCord:cordlength", new DoubleSetter(
402 Reflection.findMethodStatic(ShockCord.class, "setCordLength", double.class)));
403 setters.put("ShockCord:material", new MaterialSetter(
404 Reflection.findMethodStatic(ShockCord.class, "setMaterial", Material.class),
405 Material.Type.LINE));
408 setters.put("RecoveryDevice:cd", new DoubleSetter(
409 Reflection.findMethodStatic(RecoveryDevice.class, "setCD", double.class),
411 Reflection.findMethodStatic(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
412 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
413 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
414 RecoveryDevice.DeployEvent.class));
415 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
416 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployAltitude", double.class)));
417 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
418 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployDelay", double.class)));
419 setters.put("RecoveryDevice:material", new MaterialSetter(
420 Reflection.findMethodStatic(RecoveryDevice.class, "setMaterial", Material.class),
421 Material.Type.SURFACE));
424 setters.put("Parachute:diameter", new DoubleSetter(
425 Reflection.findMethodStatic(Parachute.class, "setDiameter", double.class)));
426 setters.put("Parachute:linecount", new IntSetter(
427 Reflection.findMethodStatic(Parachute.class, "setLineCount", int.class)));
428 setters.put("Parachute:linelength", new DoubleSetter(
429 Reflection.findMethodStatic(Parachute.class, "setLineLength", double.class)));
430 setters.put("Parachute:linematerial", new MaterialSetter(
431 Reflection.findMethodStatic(Parachute.class, "setLineMaterial", Material.class),
432 Material.Type.LINE));
435 setters.put("Streamer:striplength", new DoubleSetter(
436 Reflection.findMethodStatic(Streamer.class, "setStripLength", double.class)));
437 setters.put("Streamer:stripwidth", new DoubleSetter(
438 Reflection.findMethodStatic(Streamer.class, "setStripWidth", double.class)));
441 // <motorconfiguration> handled by separate handler
442 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
443 Reflection.findMethodStatic(Rocket.class, "setReferenceType", ReferenceType.class),
444 ReferenceType.class));
445 setters.put("Rocket:customreference", new DoubleSetter(
446 Reflection.findMethodStatic(Rocket.class, "setCustomReferenceLength", double.class)));
447 setters.put("Rocket:designer", new StringSetter(
448 Reflection.findMethodStatic(Rocket.class, "setDesigner", String.class)));
449 setters.put("Rocket:revision", new StringSetter(
450 Reflection.findMethodStatic(Rocket.class, "setRevision", String.class)));
455 * Search for a enum value that has the corresponding name as an XML value. The current
456 * conversion from enum name to XML value is to lowercase the name and strip out all
457 * underscore characters. This method returns a match to these criteria, or <code>null</code>
458 * if no such enum exists.
460 * @param <T> then enum type.
461 * @param name the XML value, null ok.
462 * @param enumClass the class of the enum.
463 * @return the found enum value, or <code>null</code>.
465 public static <T extends Enum<T>> Enum<T> findEnum(String name, Class<? extends Enum<T>> enumClass) {
470 for (Enum<T> e: enumClass.getEnumConstants()) {
471 if (e.name().toLowerCase().replace("_", "").equals(name)) {
480 * Convert a string to a double including formatting specifications of the OpenRocket
481 * file format. This accepts all formatting that is valid for
482 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
484 * @param s the string to parse.
485 * @return the numerical value.
486 * @throws NumberFormatException the the string cannot be parsed.
488 public static double stringToDouble(String s) throws NumberFormatException {
490 throw new NumberFormatException("null string");
491 if (s.equalsIgnoreCase("NaN"))
493 if (s.equalsIgnoreCase("Inf"))
494 return Double.POSITIVE_INFINITY;
495 if (s.equalsIgnoreCase("-Inf"))
496 return Double.NEGATIVE_INFINITY;
497 return Double.parseDouble(s);
506 * The starting point of the handlers. Accepts a single <openrocket> element and hands
507 * the contents to be read by a OpenRocketContentsHandler.
509 class OpenRocketHandler extends ElementHandler {
510 private OpenRocketContentHandler handler = null;
513 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
514 * has not been read yet.
516 * @return the document read, or null.
518 public OpenRocketDocument getDocument() {
519 return handler.getDocument();
523 public ElementHandler openElement(String element, HashMap<String, String> attributes,
524 WarningSet warnings) {
526 // Check for unknown elements
527 if (!element.equals("openrocket")) {
528 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
532 // Check for first call
533 if (handler != null) {
534 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
539 // Check version number
540 String version = null;
541 String creator = attributes.remove("creator");
542 String docVersion = attributes.remove("version");
543 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
544 if (v.equals(docVersion)) {
549 if (version == null) {
550 String str = "Unsupported document version";
551 if (docVersion != null)
552 str += " " + docVersion;
553 if (creator != null && !creator.trim().equals(""))
554 str += " (written using '" + creator.trim() + "')";
555 str += ", attempting to read file anyway.";
559 handler = new OpenRocketContentHandler();
564 public void closeElement(String element, HashMap<String, String> attributes,
565 String content, WarningSet warnings) throws SAXException {
566 attributes.remove("version");
567 attributes.remove("creator");
568 super.closeElement(element, attributes, content, warnings);
576 * Handles the content of the <openrocket> tag.
578 class OpenRocketContentHandler extends ElementHandler {
579 private final OpenRocketDocument doc;
580 private final Rocket rocket;
582 private boolean rocketDefined = false;
583 private boolean simulationsDefined = false;
585 public OpenRocketContentHandler() {
586 this.rocket = new Rocket();
587 this.doc = new OpenRocketDocument(rocket);
591 public OpenRocketDocument getDocument() {
598 public ElementHandler openElement(String element, HashMap<String, String> attributes,
599 WarningSet warnings) {
601 if (element.equals("rocket")) {
604 .fromString("Multiple rocket designs within one document, "
605 + "ignoring later ones."));
608 rocketDefined = true;
609 return new ComponentParameterHandler(rocket);
612 if (element.equals("simulations")) {
613 if (simulationsDefined) {
615 .fromString("Multiple simulation definitions within one document, "
616 + "ignoring later ones."));
619 simulationsDefined = true;
620 return new SimulationsHandler(doc);
623 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
633 * A handler that creates components from the corresponding elements. The control of the
634 * contents is passed on to ComponentParameterHandler.
636 class ComponentHandler extends ElementHandler {
637 private final RocketComponent parent;
639 public ComponentHandler(RocketComponent parent) {
640 this.parent = parent;
644 public ElementHandler openElement(String element, HashMap<String, String> attributes,
645 WarningSet warnings) {
647 // Attempt to construct new component
648 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
650 if (constructor == null) {
651 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
657 c = constructor.newInstance();
658 } catch (InstantiationException e) {
659 throw new RuntimeException("Error constructing component.", e);
660 } catch (IllegalAccessException e) {
661 throw new RuntimeException("Error constructing component.", e);
662 } catch (InvocationTargetException e) {
663 throw new RuntimeException("Error constructing component.", e);
668 return new ComponentParameterHandler(c);
674 * A handler that populates the parameters of a previously constructed rocket component.
675 * This uses the setters, or delegates the handling to another handler for specific
678 class ComponentParameterHandler extends ElementHandler {
679 private final RocketComponent component;
681 public ComponentParameterHandler(RocketComponent c) {
686 public ElementHandler openElement(String element, HashMap<String, String> attributes,
687 WarningSet warnings) {
689 // Check for specific elements that contain other elements
690 if (element.equals("subcomponents")) {
691 return new ComponentHandler(component);
693 if (element.equals("motormount")) {
694 if (!(component instanceof MotorMount)) {
695 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
698 return new MotorMountHandler((MotorMount)component);
700 if (element.equals("finpoints")) {
701 if (!(component instanceof FreeformFinSet)) {
702 warnings.add(Warning.fromString("Illegal component defined for fin points."));
705 return new FinSetPointHandler((FreeformFinSet)component);
707 if (element.equals("motorconfiguration")) {
708 if (!(component instanceof Rocket)) {
709 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
712 return new MotorConfigurationHandler((Rocket)component);
716 return PlainTextHandler.INSTANCE;
720 public void closeElement(String element, HashMap<String, String> attributes,
721 String content, WarningSet warnings) {
723 if (element.equals("subcomponents") || element.equals("motormount") ||
724 element.equals("finpoints") || element.equals("motorconfiguration")) {
728 // Search for the correct setter class
731 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
732 String setterKey = c.getSimpleName() + ":" + element;
733 Setter s = DocumentConfig.setters.get(setterKey);
736 System.out.println("Calling with key "+setterKey);
737 s.set(component, content, attributes, warnings);
740 if (DocumentConfig.setters.containsKey(setterKey)) {
741 // Key exists but is null -> invalid parameter
747 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
748 + component.getComponentName() + ", ignoring."));
755 * A handler that reads the <point> specifications within the freeformfinset's
756 * <finpoints> elements.
758 class FinSetPointHandler extends ElementHandler {
759 private final FreeformFinSet finset;
760 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
762 public FinSetPointHandler(FreeformFinSet finset) {
763 this.finset = finset;
767 public ElementHandler openElement(String element, HashMap<String, String> attributes,
768 WarningSet warnings) {
769 return PlainTextHandler.INSTANCE;
774 public void closeElement(String element, HashMap<String, String> attributes,
775 String content, WarningSet warnings) throws SAXException {
777 String strx = attributes.remove("x");
778 String stry = attributes.remove("y");
779 if (strx == null || stry == null) {
780 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
784 double x = Double.parseDouble(strx);
785 double y = Double.parseDouble(stry);
786 coordinates.add(new Coordinate(x,y));
787 } catch (NumberFormatException e) {
788 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
792 super.closeElement(element, attributes, content, warnings);
796 public void endHandler(String element, HashMap<String, String> attributes,
797 String content, WarningSet warnings) {
799 finset.setPoints(coordinates.toArray(new Coordinate[0]));
800 } catch (IllegalFinPointException e) {
801 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
807 class MotorMountHandler extends ElementHandler {
808 private final MotorMount mount;
809 private MotorHandler motorHandler;
811 public MotorMountHandler(MotorMount mount) {
813 mount.setMotorMount(true);
817 public ElementHandler openElement(String element, HashMap<String, String> attributes,
818 WarningSet warnings) {
820 if (element.equals("motor")) {
821 motorHandler = new MotorHandler();
825 if (element.equals("ignitionevent") ||
826 element.equals("ignitiondelay") ||
827 element.equals("overhang")) {
828 return PlainTextHandler.INSTANCE;
831 warnings.add(Warning.fromString("Unknown element '"+element+"' encountered, ignoring."));
838 public void closeElement(String element, HashMap<String, String> attributes,
839 String content, WarningSet warnings) throws SAXException {
841 if (element.equals("motor")) {
842 String id = attributes.get("configid");
843 if (id == null || id.equals("")) {
844 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
848 Motor motor = motorHandler.getMotor(warnings);
849 mount.setMotor(id, motor);
850 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
854 if (element.equals("ignitionevent")) {
855 MotorMount.IgnitionEvent event = null;
856 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
857 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
863 warnings.add(Warning.fromString("Unknown ignition event type '"+content+"', ignoring."));
866 mount.setIgnitionEvent(event);
870 if (element.equals("ignitiondelay")) {
873 d = Double.parseDouble(content);
874 } catch (NumberFormatException nfe) {
875 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
878 mount.setIgnitionDelay(d);
882 if (element.equals("overhang")) {
885 d = Double.parseDouble(content);
886 } catch (NumberFormatException nfe) {
887 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
890 mount.setMotorOverhang(d);
894 super.closeElement(element, attributes, content, warnings);
901 class MotorConfigurationHandler extends ElementHandler {
902 private final Rocket rocket;
903 private String name = null;
904 private boolean inNameElement = false;
906 public MotorConfigurationHandler(Rocket rocket) {
907 this.rocket = rocket;
911 public ElementHandler openElement(String element, HashMap<String, String> attributes,
912 WarningSet warnings) {
914 if (inNameElement || !element.equals("name")) {
915 warnings.add(Warning.FILE_INVALID_PARAMETER);
918 inNameElement = true;
920 return PlainTextHandler.INSTANCE;
924 public void closeElement(String element, HashMap<String, String> attributes,
925 String content, WarningSet warnings) {
930 public void endHandler(String element, HashMap<String, String> attributes,
931 String content, WarningSet warnings) throws SAXException {
933 String configid = attributes.remove("configid");
934 if (configid == null || configid.equals("")) {
935 warnings.add(Warning.FILE_INVALID_PARAMETER);
939 if (!rocket.addMotorConfigurationID(configid)) {
940 warnings.add("Duplicate motor configuration ID used.");
944 if (name != null && name.trim().length() > 0) {
945 rocket.setMotorConfigurationName(configid, name);
948 if ("true".equals(attributes.remove("default"))) {
949 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
952 super.closeElement(element, attributes, content, warnings);
957 class MotorHandler extends ElementHandler {
958 private Motor.Type type = null;
959 private String manufacturer = null;
960 private String designation = null;
961 private double diameter = Double.NaN;
962 private double length = Double.NaN;
963 private double delay = Double.NaN;
966 public ElementHandler openElement(String element, HashMap<String, String> attributes,
967 WarningSet warnings) {
968 return PlainTextHandler.INSTANCE;
973 * Return the motor to use, or null.
975 public Motor getMotor(WarningSet warnings) {
976 if (designation == null) {
977 warnings.add(Warning.fromString("No motor specified, ignoring."));
980 Motor[] motors = Databases.findMotors(type, manufacturer, designation, diameter, length);
981 if (motors.length == 0) {
982 String str = "No motor with designation '"+designation+"'";
983 if (manufacturer != null)
984 str += " for manufacturer '" + manufacturer + "'";
985 warnings.add(Warning.fromString(str + " found."));
988 if (motors.length > 1) {
989 String str = "Multiple motors with designation '"+designation+"'";
990 if (manufacturer != null)
991 str += " for manufacturer '" + manufacturer + "'";
992 warnings.add(Warning.fromString(str + " found, one chosen arbitrarily."));
999 * Return the delay to use for the motor.
1001 public double getDelay(WarningSet warnings) {
1002 if (Double.isNaN(delay)) {
1003 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1004 return Motor.PLUGGED;
1011 public void closeElement(String element, HashMap<String, String> attributes,
1012 String content, WarningSet warnings) throws SAXException {
1014 content = content.trim();
1016 if (element.equals("type")) {
1020 for (Motor.Type t: Motor.Type.values()) {
1021 if (t.name().toLowerCase().equals(content)) {
1027 warnings.add(Warning.fromString("Unknown motor type '"+content+"', ignoring."));
1030 } else if (element.equals("manufacturer")) {
1033 manufacturer = MotorLoader.convertManufacturer(content);
1035 } else if (element.equals("designation")) {
1038 designation = content;
1040 } else if (element.equals("diameter")) {
1043 diameter = Double.NaN;
1045 diameter = Double.parseDouble(content);
1046 } catch (NumberFormatException e) {
1049 if (Double.isNaN(diameter)) {
1050 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1053 } else if (element.equals("length")) {
1056 length = Double.NaN;
1058 length = Double.parseDouble(content);
1059 } catch (NumberFormatException ignore) { }
1061 if (Double.isNaN(length)) {
1062 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1065 } else if (element.equals("delay")) {
1069 if (content.equals("none")) {
1070 delay = Motor.PLUGGED;
1073 delay = Double.parseDouble(content);
1074 } catch (NumberFormatException ignore) { }
1076 if (Double.isNaN(delay)) {
1077 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1083 super.closeElement(element, attributes, content, warnings);
1091 class SimulationsHandler extends ElementHandler {
1092 private final OpenRocketDocument doc;
1093 private SingleSimulationHandler handler;
1095 public SimulationsHandler(OpenRocketDocument doc) {
1100 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1101 WarningSet warnings) {
1103 if (!element.equals("simulation")) {
1104 warnings.add("Unknown element '"+element+"', ignoring.");
1108 handler = new SingleSimulationHandler(doc);
1113 public void closeElement(String element, HashMap<String, String> attributes,
1114 String content, WarningSet warnings) throws SAXException {
1115 attributes.remove("status");
1116 super.closeElement(element, attributes, content, warnings);
1122 class SingleSimulationHandler extends ElementHandler {
1124 private final OpenRocketDocument doc;
1126 private String name;
1128 private SimulationConditionsHandler conditionHandler;
1129 private FlightDataHandler dataHandler;
1131 private final List<String> listeners = new ArrayList<String>();
1133 public SingleSimulationHandler(OpenRocketDocument doc) {
1140 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1141 WarningSet warnings) {
1143 if (element.equals("name") || element.equals("simulator") ||
1144 element.equals("calculator") || element.equals("listener")) {
1145 return PlainTextHandler.INSTANCE;
1146 } else if (element.equals("conditions")) {
1147 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1148 return conditionHandler;
1149 } else if (element.equals("flightdata")) {
1150 dataHandler = new FlightDataHandler();
1153 warnings.add("Unknown element '"+element+"', ignoring.");
1159 public void closeElement(String element, HashMap<String, String> attributes,
1160 String content, WarningSet warnings) {
1162 if (element.equals("name")) {
1164 } else if (element.equals("simulator")) {
1165 if (!content.trim().equals("RK4Simulator")) {
1166 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1168 } else if (element.equals("calculator")) {
1169 if (!content.trim().equals("BarrowmanCalculator")) {
1170 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1172 } else if (element.equals("listener") && content.trim().length() > 0) {
1173 listeners.add(content.trim());
1179 public void endHandler(String element, HashMap<String, String> attributes,
1180 String content, WarningSet warnings) {
1182 String s = attributes.get("status");
1183 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1184 if (status == null) {
1185 warnings.add("Simulation status unknown, assuming outdated.");
1186 status = Simulation.Status.OUTDATED;
1189 SimulationConditions conditions;
1190 if (conditionHandler != null) {
1191 conditions = conditionHandler.getConditions();
1193 warnings.add("Simulation conditions not defined, using defaults.");
1194 conditions = new SimulationConditions(doc.getRocket());
1198 name = "Simulation";
1201 if (dataHandler == null)
1204 data = dataHandler.getFlightData();
1206 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1207 conditions, listeners, data);
1209 doc.addSimulation(simulation);
1215 class SimulationConditionsHandler extends ElementHandler {
1216 private SimulationConditions conditions;
1217 private AtmosphereHandler atmosphereHandler;
1219 public SimulationConditionsHandler(Rocket rocket) {
1220 conditions = new SimulationConditions(rocket);
1223 public SimulationConditions getConditions() {
1228 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1229 WarningSet warnings) {
1230 if (element.equals("atmosphere")) {
1231 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1232 return atmosphereHandler;
1234 return PlainTextHandler.INSTANCE;
1238 public void closeElement(String element, HashMap<String, String> attributes,
1239 String content, WarningSet warnings) {
1241 double d = Double.NaN;
1243 d = Double.parseDouble(content);
1244 } catch (NumberFormatException ignore) { }
1247 if (element.equals("configid")) {
1248 if (content.equals("")) {
1249 conditions.setMotorConfigurationID(null);
1251 conditions.setMotorConfigurationID(content);
1253 } else if (element.equals("launchrodlength")) {
1254 if (Double.isNaN(d)) {
1255 warnings.add("Illegal launch rod length defined, ignoring.");
1257 conditions.setLaunchRodLength(d);
1259 } else if (element.equals("launchrodangle")) {
1260 if (Double.isNaN(d)) {
1261 warnings.add("Illegal launch rod angle defined, ignoring.");
1263 conditions.setLaunchRodAngle(d*Math.PI/180);
1265 } else if (element.equals("launchroddirection")) {
1266 if (Double.isNaN(d)) {
1267 warnings.add("Illegal launch rod direction defined, ignoring.");
1269 conditions.setLaunchRodDirection(d*Math.PI/180);
1271 } else if (element.equals("windaverage")) {
1272 if (Double.isNaN(d)) {
1273 warnings.add("Illegal average windspeed defined, ignoring.");
1275 conditions.setWindSpeedAverage(d);
1277 } else if (element.equals("windturbulence")) {
1278 if (Double.isNaN(d)) {
1279 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1281 conditions.setWindTurbulenceIntensity(d);
1283 } else if (element.equals("launchaltitude")) {
1284 if (Double.isNaN(d)) {
1285 warnings.add("Illegal launch altitude defined, ignoring.");
1287 conditions.setLaunchAltitude(d);
1289 } else if (element.equals("launchlatitude")) {
1290 if (Double.isNaN(d)) {
1291 warnings.add("Illegal launch latitude defined, ignoring.");
1293 conditions.setLaunchLatitude(d);
1295 } else if (element.equals("atmosphere")) {
1296 atmosphereHandler.storeSettings(conditions, warnings);
1297 } else if (element.equals("timestep")) {
1298 if (Double.isNaN(d)) {
1299 warnings.add("Illegal time step defined, ignoring.");
1301 conditions.setTimeStep(d);
1308 class AtmosphereHandler extends ElementHandler {
1309 private final String model;
1310 private double temperature = Double.NaN;
1311 private double pressure = Double.NaN;
1313 public AtmosphereHandler(String model) {
1318 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1319 WarningSet warnings) {
1320 return PlainTextHandler.INSTANCE;
1324 public void closeElement(String element, HashMap<String, String> attributes,
1325 String content, WarningSet warnings) throws SAXException {
1327 double d = Double.NaN;
1329 d = Double.parseDouble(content);
1330 } catch (NumberFormatException ignore) { }
1332 if (element.equals("basetemperature")) {
1333 if (Double.isNaN(d)) {
1334 warnings.add("Illegal base temperature specified, ignoring.");
1337 } else if (element.equals("basepressure")) {
1338 if (Double.isNaN(d)) {
1339 warnings.add("Illegal base pressure specified, ignoring.");
1343 super.closeElement(element, attributes, content, warnings);
1348 public void storeSettings(SimulationConditions cond, WarningSet warnings) {
1349 if (!Double.isNaN(pressure)) {
1350 cond.setLaunchPressure(pressure);
1352 if (!Double.isNaN(temperature)) {
1353 cond.setLaunchTemperature(temperature);
1356 if ("isa".equals(model)) {
1357 cond.setISAAtmosphere(true);
1358 } else if ("extendedisa".equals(model)){
1359 cond.setISAAtmosphere(false);
1361 cond.setISAAtmosphere(true);
1362 warnings.add("Unknown atmospheric model, using ISA.");
1369 class FlightDataHandler extends ElementHandler {
1371 private FlightDataBranchHandler dataHandler;
1372 private WarningSet warningSet = new WarningSet();
1373 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1375 private FlightData data;
1377 public FlightData getFlightData() {
1382 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1383 WarningSet warnings) {
1385 if (element.equals("warning")) {
1386 return PlainTextHandler.INSTANCE;
1388 if (element.equals("databranch")) {
1389 if (attributes.get("name") == null || attributes.get("types")==null) {
1390 warnings.add("Illegal flight data definition, ignoring.");
1393 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1394 attributes.get("types"));
1398 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1404 public void closeElement(String element, HashMap<String, String> attributes,
1405 String content, WarningSet warnings) {
1407 if (element.equals("databranch")) {
1408 FlightDataBranch branch = dataHandler.getBranch();
1409 if (branch.getLength() > 0) {
1410 branches.add(branch);
1412 } else if (element.equals("warning")) {
1413 warningSet.add(Warning.fromString(content));
1419 public void endHandler(String element, HashMap<String, String> attributes,
1420 String content, WarningSet warnings) {
1422 if (branches.size() > 0) {
1423 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1425 double maxAltitude = Double.NaN;
1426 double maxVelocity = Double.NaN;
1427 double maxAcceleration = Double.NaN;
1428 double maxMach = Double.NaN;
1429 double timeToApogee = Double.NaN;
1430 double flightTime = Double.NaN;
1431 double groundHitVelocity = Double.NaN;
1434 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1435 } catch (NumberFormatException ignore) { }
1437 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1438 } catch (NumberFormatException ignore) { }
1440 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1441 } catch (NumberFormatException ignore) { }
1443 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1444 } catch (NumberFormatException ignore) { }
1446 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1447 } catch (NumberFormatException ignore) { }
1449 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1450 } catch (NumberFormatException ignore) { }
1453 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1454 } catch (NumberFormatException ignore) { }
1456 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1457 timeToApogee, flightTime, groundHitVelocity);
1460 data.getWarningSet().addAll(warningSet);
1467 class FlightDataBranchHandler extends ElementHandler {
1468 private final FlightDataBranch.Type[] types;
1469 private final FlightDataBranch branch;
1471 public FlightDataBranchHandler(String name, String typeList) {
1472 String[] split = typeList.split(",");
1473 types = new FlightDataBranch.Type[split.length];
1474 for (int i=0; i < split.length; i++) {
1475 types[i] = FlightDataBranch.getType(split[i], UnitGroup.UNITS_NONE);
1478 // TODO: LOW: May throw an IllegalArgumentException
1479 branch = new FlightDataBranch(name, types);
1482 public FlightDataBranch getBranch() {
1488 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1489 WarningSet warnings) {
1491 if (element.equals("datapoint"))
1492 return PlainTextHandler.INSTANCE;
1493 if (element.equals("event"))
1494 return PlainTextHandler.INSTANCE;
1496 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1502 public void closeElement(String element, HashMap<String, String> attributes,
1503 String content, WarningSet warnings) {
1505 if (element.equals("event")) {
1507 FlightEvent.Type type;
1510 time = DocumentConfig.stringToDouble(attributes.get("time"));
1511 } catch (NumberFormatException e) {
1512 warnings.add("Illegal event specification, ignoring.");
1516 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1518 warnings.add("Illegal event specification, ignoring.");
1522 branch.addEvent(time, new FlightEvent(type, time));
1526 if (!element.equals("datapoint")) {
1527 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1531 // element == "datapoint"
1534 // Check line format
1535 String[] split = content.split(",");
1536 if (split.length != types.length) {
1537 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1541 // Parse the doubles
1542 double[] values = new double[split.length];
1543 for (int i=0; i < values.length; i++) {
1545 values[i] = DocumentConfig.stringToDouble(split[i]);
1546 } catch (NumberFormatException e) {
1547 warnings.add("Data point format error, ignoring point.");
1552 // Add point to branch
1554 for (int i=0; i < types.length; i++) {
1555 branch.setValue(types[i], values[i]);
1565 ///////////////// Setters implementation
1571 * Set the specified value to the given component.
1573 * @param component the component to which to set.
1574 * @param value the value within the element.
1575 * @param attributes attributes for the element.
1576 * @param warnings the warning set to use.
1578 public void set(RocketComponent component, String value,
1579 HashMap<String, String> attributes, WarningSet warnings);
1583 //// StringSetter - sets the value to the contained String
1584 class StringSetter implements Setter {
1585 private final Reflection.Method setMethod;
1587 public StringSetter(Reflection.Method set) {
1591 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1592 WarningSet warnings) {
1593 setMethod.invoke(c, s);
1597 //// IntSetter - set an integer value
1598 class IntSetter implements Setter {
1599 private final Reflection.Method setMethod;
1601 public IntSetter(Reflection.Method set) {
1605 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1606 WarningSet warnings) {
1608 int n = Integer.parseInt(s);
1609 setMethod.invoke(c, n);
1610 } catch (NumberFormatException e) {
1611 warnings.add(Warning.FILE_INVALID_PARAMETER);
1617 //// BooleanSetter - set a boolean value
1618 class BooleanSetter implements Setter {
1619 private final Reflection.Method setMethod;
1621 public BooleanSetter(Reflection.Method set) {
1625 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1626 WarningSet warnings) {
1629 if (s.equalsIgnoreCase("true")) {
1630 setMethod.invoke(c, true);
1631 } else if (s.equalsIgnoreCase("false")) {
1632 setMethod.invoke(c, false);
1634 warnings.add(Warning.FILE_INVALID_PARAMETER);
1641 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1642 //// calls a setXXX(boolean) method.
1643 class DoubleSetter implements Setter {
1644 private final Reflection.Method setMethod;
1645 private final String specialString;
1646 private final Reflection.Method specialMethod;
1647 private final double multiplier;
1650 * Set only the double value.
1651 * @param set set method for the double value.
1653 public DoubleSetter(Reflection.Method set) {
1654 this.setMethod = set;
1655 this.specialString = null;
1656 this.specialMethod = null;
1657 this.multiplier = 1.0;
1661 * Multiply with the given multiplier and set the double value.
1662 * @param set set method for the double value.
1663 * @param mul multiplier.
1665 public DoubleSetter(Reflection.Method set, double mul) {
1666 this.setMethod = set;
1667 this.specialString = null;
1668 this.specialMethod = null;
1669 this.multiplier = mul;
1673 * Set the double value, or if the value equals the special string, use the
1674 * special setter and set it to true.
1676 * @param set double setter.
1677 * @param special special string
1678 * @param specialMethod boolean setter.
1680 public DoubleSetter(Reflection.Method set, String special,
1681 Reflection.Method specialMethod) {
1682 this.setMethod = set;
1683 this.specialString = special;
1684 this.specialMethod = specialMethod;
1685 this.multiplier = 1.0;
1689 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1690 WarningSet warnings) {
1694 // Check for special case
1695 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1696 specialMethod.invoke(c, true);
1702 double d = Double.parseDouble(s);
1703 setMethod.invoke(c, d * multiplier);
1704 } catch (NumberFormatException e) {
1705 warnings.add(Warning.FILE_INVALID_PARAMETER);
1711 class OverrideSetter implements Setter {
1712 private final Reflection.Method setMethod;
1713 private final Reflection.Method enabledMethod;
1715 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1716 this.setMethod = set;
1717 this.enabledMethod = enabledMethod;
1720 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1721 WarningSet warnings) {
1724 double d = Double.parseDouble(s);
1725 setMethod.invoke(c, d);
1726 enabledMethod.invoke(c, true);
1727 } catch (NumberFormatException e) {
1728 warnings.add(Warning.FILE_INVALID_PARAMETER);
1733 //// EnumSetter - sets a generic enum type
1734 class EnumSetter<T extends Enum<T>> implements Setter {
1735 private final Reflection.Method setter;
1736 private final Class<T> enumClass;
1738 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1740 this.enumClass = enumClass;
1744 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1745 WarningSet warnings) {
1747 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1748 if (setEnum == null) {
1749 warnings.add(Warning.FILE_INVALID_PARAMETER);
1753 setter.invoke(c, setEnum);
1758 //// ColorSetter - sets a Color value
1759 class ColorSetter implements Setter {
1760 private final Reflection.Method setMethod;
1762 public ColorSetter(Reflection.Method set) {
1766 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1767 WarningSet warnings) {
1769 String red = attributes.get("red");
1770 String green = attributes.get("green");
1771 String blue = attributes.get("blue");
1773 if (red == null || green == null || blue == null) {
1774 warnings.add(Warning.FILE_INVALID_PARAMETER);
1780 r = Integer.parseInt(red);
1781 g = Integer.parseInt(green);
1782 b = Integer.parseInt(blue);
1783 } catch (NumberFormatException e) {
1784 warnings.add(Warning.FILE_INVALID_PARAMETER);
1788 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1789 warnings.add(Warning.FILE_INVALID_PARAMETER);
1793 Color color = new Color(r, g, b);
1794 setMethod.invoke(c, color);
1796 if (!s.trim().equals("")) {
1797 warnings.add(Warning.FILE_INVALID_PARAMETER);
1804 class MaterialSetter implements Setter {
1805 private final Reflection.Method setMethod;
1806 private final Material.Type type;
1808 public MaterialSetter(Reflection.Method set, Material.Type type) {
1809 this.setMethod = set;
1813 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1814 WarningSet warnings) {
1820 if (name.equals("")) {
1821 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1828 str = attributes.remove("density");
1830 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1834 density = Double.parseDouble(str);
1835 } catch (NumberFormatException e) {
1836 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1841 // double thickness = 0;
1842 // str = attributes.remove("thickness");
1845 // thickness = Double.parseDouble(str);
1846 // } catch (NumberFormatException e){
1847 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1851 // Check type if specified
1852 str = attributes.remove("type");
1853 if (str != null && !type.name().toLowerCase().equals(str)) {
1854 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1858 mat = Material.newMaterial(type, name, density);
1860 setMethod.invoke(c, mat);
1867 class PositionSetter implements Setter {
1869 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1870 WarningSet warnings) {
1872 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1873 RocketComponent.Position.class);
1875 warnings.add(Warning.FILE_INVALID_PARAMETER);
1881 pos = Double.parseDouble(value);
1882 } catch (NumberFormatException e) {
1883 warnings.add(Warning.FILE_INVALID_PARAMETER);
1887 if (c instanceof FinSet) {
1888 ((FinSet)c).setRelativePosition(type);
1889 c.setPositionValue(pos);
1890 } else if (c instanceof LaunchLug) {
1891 ((LaunchLug)c).setRelativePosition(type);
1892 c.setPositionValue(pos);
1893 } else if (c instanceof InternalComponent) {
1894 ((InternalComponent)c).setRelativePosition(type);
1895 c.setPositionValue(pos);
1897 warnings.add(Warning.FILE_INVALID_PARAMETER);
1905 class ClusterConfigurationSetter implements Setter {
1907 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
1908 WarningSet warnings) {
1910 if (!(component instanceof Clusterable)) {
1911 warnings.add("Illegal component defined as cluster.");
1915 ClusterConfiguration config = null;
1916 for (ClusterConfiguration c: ClusterConfiguration.CONFIGURATIONS) {
1917 if (c.getXMLName().equals(value)) {
1923 if (config == null) {
1924 warnings.add("Illegal cluster configuration specified.");
1928 ((Clusterable)component).setClusterConfiguration(config);