1 package net.sf.openrocket.file.openrocket;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.lang.reflect.Constructor;
7 import java.lang.reflect.InvocationTargetException;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.List;
12 import net.sf.openrocket.aerodynamics.Warning;
13 import net.sf.openrocket.aerodynamics.WarningSet;
14 import net.sf.openrocket.database.Databases;
15 import net.sf.openrocket.document.OpenRocketDocument;
16 import net.sf.openrocket.document.Simulation;
17 import net.sf.openrocket.document.StorageOptions;
18 import net.sf.openrocket.document.Simulation.Status;
19 import net.sf.openrocket.file.RocketLoadException;
20 import net.sf.openrocket.file.RocketLoader;
21 import net.sf.openrocket.file.simplesax.ElementHandler;
22 import net.sf.openrocket.file.simplesax.PlainTextHandler;
23 import net.sf.openrocket.file.simplesax.SimpleSAX;
24 import net.sf.openrocket.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.FinSet;
36 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
37 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
38 import net.sf.openrocket.rocketcomponent.InnerTube;
39 import net.sf.openrocket.rocketcomponent.InternalComponent;
40 import net.sf.openrocket.rocketcomponent.LaunchLug;
41 import net.sf.openrocket.rocketcomponent.MassComponent;
42 import net.sf.openrocket.rocketcomponent.MassObject;
43 import net.sf.openrocket.rocketcomponent.MotorMount;
44 import net.sf.openrocket.rocketcomponent.NoseCone;
45 import net.sf.openrocket.rocketcomponent.Parachute;
46 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
47 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
48 import net.sf.openrocket.rocketcomponent.ReferenceType;
49 import net.sf.openrocket.rocketcomponent.RingComponent;
50 import net.sf.openrocket.rocketcomponent.Rocket;
51 import net.sf.openrocket.rocketcomponent.RocketComponent;
52 import net.sf.openrocket.rocketcomponent.ShockCord;
53 import net.sf.openrocket.rocketcomponent.Stage;
54 import net.sf.openrocket.rocketcomponent.Streamer;
55 import net.sf.openrocket.rocketcomponent.StructuralComponent;
56 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
57 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
58 import net.sf.openrocket.rocketcomponent.Transition;
59 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
60 import net.sf.openrocket.rocketcomponent.TubeCoupler;
61 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
62 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
63 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
64 import net.sf.openrocket.simulation.FlightData;
65 import net.sf.openrocket.simulation.FlightDataBranch;
66 import net.sf.openrocket.simulation.FlightEvent;
67 import net.sf.openrocket.simulation.SimulationConditions;
68 import net.sf.openrocket.simulation.FlightEvent.Type;
69 import net.sf.openrocket.unit.UnitGroup;
70 import net.sf.openrocket.util.Coordinate;
71 import net.sf.openrocket.util.LineStyle;
72 import net.sf.openrocket.util.Reflection;
74 import org.xml.sax.InputSource;
75 import org.xml.sax.SAXException;
79 * Class that loads a rocket definition from an OpenRocket rocket file.
81 * This class uses SAX to read the XML file format. The
82 * {@link #loadFromStream(InputStream)} method simply sets the system up and
83 * starts the parsing, while the actual logic is in the private inner class
84 * <code>OpenRocketHandler</code>.
86 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
89 public class OpenRocketLoader extends RocketLoader {
92 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
94 InputSource xmlSource = new InputSource(source);
95 OpenRocketHandler handler = new OpenRocketHandler();
99 SimpleSAX.readXML(xmlSource, handler, warnings);
100 } catch (SAXException e) {
101 throw new RocketLoadException("Malformed XML in input.", e);
105 OpenRocketDocument doc = handler.getDocument();
106 doc.getDefaultConfiguration().setAllStages();
108 // Deduce suitable time skip
109 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
110 for (Simulation s: doc.getSimulations()) {
111 if (s.getStatus() == Simulation.Status.EXTERNAL ||
112 s.getStatus() == Simulation.Status.NOT_SIMULATED)
114 if (s.getSimulatedData() == null)
116 if (s.getSimulatedData().getBranchCount() == 0)
118 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
121 List<Double> list = branch.get(FlightDataBranch.TYPE_TIME);
125 double previousTime = Double.NaN;
126 for (double time: list) {
127 if (time - previousTime < timeSkip)
128 timeSkip = time-previousTime;
133 timeSkip = Math.rint(timeSkip*100)/100;
135 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
136 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
137 doc.getDefaultStorageOptions().setExplicitlySet(false);
147 class DocumentConfig {
149 /* Remember to update OpenRocketSaver as well! */
150 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1" };
153 //////// Component constructors
154 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
157 // External components
158 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
159 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
160 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
161 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
162 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
163 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
164 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
166 // Internal components
167 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
168 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
169 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
170 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
171 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
173 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
174 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
175 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
176 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
179 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
181 } catch (NoSuchMethodException e) {
182 throw new RuntimeException(
183 "Error in constructing the 'constructors' HashMap.");
188 //////// Parameter setters
190 * The keys are of the form Class:param, where Class is the class name and param
191 * the element name. Setters are searched for in descending class order.
192 * A setter of null means setting the parameter is not allowed.
194 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
197 setters.put("RocketComponent:name", new StringSetter(
198 Reflection.findMethodStatic(RocketComponent.class, "setName", String.class)));
199 setters.put("RocketComponent:color", new ColorSetter(
200 Reflection.findMethodStatic(RocketComponent.class, "setColor", Color.class)));
201 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
202 Reflection.findMethodStatic(RocketComponent.class, "setLineStyle", LineStyle.class),
204 setters.put("RocketComponent:position", new PositionSetter());
205 setters.put("RocketComponent:overridemass", new OverrideSetter(
206 Reflection.findMethodStatic(RocketComponent.class, "setOverrideMass", double.class),
207 Reflection.findMethodStatic(RocketComponent.class, "setMassOverridden", boolean.class)));
208 setters.put("RocketComponent:overridecg", new OverrideSetter(
209 Reflection.findMethodStatic(RocketComponent.class, "setOverrideCGX", double.class),
210 Reflection.findMethodStatic(RocketComponent.class, "setCGOverridden", boolean.class)));
211 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
212 Reflection.findMethodStatic(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
213 setters.put("RocketComponent:comment", new StringSetter(
214 Reflection.findMethodStatic(RocketComponent.class, "setComment", String.class)));
217 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
218 Reflection.findMethodStatic(ExternalComponent.class, "setFinish", Finish.class),
220 setters.put("ExternalComponent:material", new MaterialSetter(
221 Reflection.findMethodStatic(ExternalComponent.class, "setMaterial", Material.class),
222 Material.Type.BULK));
225 setters.put("BodyComponent:length", new DoubleSetter(
226 Reflection.findMethodStatic(BodyComponent.class, "setLength", double.class)));
228 // SymmetricComponent
229 setters.put("SymmetricComponent:thickness", new DoubleSetter(
230 Reflection.findMethodStatic(SymmetricComponent.class,"setThickness", double.class),
232 Reflection.findMethodStatic(SymmetricComponent.class,"setFilled", boolean.class)));
235 setters.put("BodyTube:radius", new DoubleSetter(
236 Reflection.findMethodStatic(BodyTube.class, "setRadius", double.class),
238 Reflection.findMethodStatic(BodyTube.class,"setRadiusAutomatic", boolean.class)));
241 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
242 Reflection.findMethodStatic(Transition.class, "setType", Transition.Shape.class),
243 Transition.Shape.class));
244 setters.put("Transition:shapeclipped", new BooleanSetter(
245 Reflection.findMethodStatic(Transition.class, "setClipped", boolean.class)));
246 setters.put("Transition:shapeparameter", new DoubleSetter(
247 Reflection.findMethodStatic(Transition.class, "setShapeParameter", double.class)));
249 setters.put("Transition:foreradius", new DoubleSetter(
250 Reflection.findMethodStatic(Transition.class, "setForeRadius", double.class),
252 Reflection.findMethodStatic(Transition.class, "setForeRadiusAutomatic", boolean.class)));
253 setters.put("Transition:aftradius", new DoubleSetter(
254 Reflection.findMethodStatic(Transition.class, "setAftRadius", double.class),
256 Reflection.findMethodStatic(Transition.class, "setAftRadiusAutomatic", boolean.class)));
258 setters.put("Transition:foreshoulderradius", new DoubleSetter(
259 Reflection.findMethodStatic(Transition.class, "setForeShoulderRadius", double.class)));
260 setters.put("Transition:foreshoulderlength", new DoubleSetter(
261 Reflection.findMethodStatic(Transition.class, "setForeShoulderLength", double.class)));
262 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
263 Reflection.findMethodStatic(Transition.class, "setForeShoulderThickness", double.class)));
264 setters.put("Transition:foreshouldercapped", new BooleanSetter(
265 Reflection.findMethodStatic(Transition.class, "setForeShoulderCapped", boolean.class)));
267 setters.put("Transition:aftshoulderradius", new DoubleSetter(
268 Reflection.findMethodStatic(Transition.class, "setAftShoulderRadius", double.class)));
269 setters.put("Transition:aftshoulderlength", new DoubleSetter(
270 Reflection.findMethodStatic(Transition.class, "setAftShoulderLength", double.class)));
271 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
272 Reflection.findMethodStatic(Transition.class, "setAftShoulderThickness", double.class)));
273 setters.put("Transition:aftshouldercapped", new BooleanSetter(
274 Reflection.findMethodStatic(Transition.class, "setAftShoulderCapped", boolean.class)));
276 // NoseCone - disable disallowed elements
277 setters.put("NoseCone:foreradius", null);
278 setters.put("NoseCone:foreshoulderradius", null);
279 setters.put("NoseCone:foreshoulderlength", null);
280 setters.put("NoseCone:foreshoulderthickness", null);
281 setters.put("NoseCone:foreshouldercapped", null);
284 setters.put("FinSet:fincount", new IntSetter(
285 Reflection.findMethodStatic(FinSet.class, "setFinCount", int.class)));
286 setters.put("FinSet:rotation", new DoubleSetter(
287 Reflection.findMethodStatic(FinSet.class, "setBaseRotation", double.class), Math.PI/180.0));
288 setters.put("FinSet:thickness", new DoubleSetter(
289 Reflection.findMethodStatic(FinSet.class, "setThickness", double.class)));
290 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
291 Reflection.findMethodStatic(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
292 FinSet.CrossSection.class));
293 setters.put("FinSet:cant", new DoubleSetter(
294 Reflection.findMethodStatic(FinSet.class, "setCantAngle", double.class), Math.PI/180.0));
295 setters.put("FinSet:tabheight", new DoubleSetter(
296 Reflection.findMethodStatic(FinSet.class, "setTabHeight", double.class)));
297 setters.put("FinSet:tablength", new DoubleSetter(
298 Reflection.findMethodStatic(FinSet.class, "setTabLength", double.class)));
299 setters.put("FinSet:tabposition", new FinTabPositionSetter());
302 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
303 Reflection.findMethodStatic(TrapezoidFinSet.class, "setRootChord", double.class)));
304 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
305 Reflection.findMethodStatic(TrapezoidFinSet.class, "setTipChord", double.class)));
306 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
307 Reflection.findMethodStatic(TrapezoidFinSet.class, "setSweep", double.class)));
308 setters.put("TrapezoidFinSet:height", new DoubleSetter(
309 Reflection.findMethodStatic(TrapezoidFinSet.class, "setHeight", double.class)));
312 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
313 Reflection.findMethodStatic(EllipticalFinSet.class, "setLength", double.class)));
314 setters.put("EllipticalFinSet:height", new DoubleSetter(
315 Reflection.findMethodStatic(EllipticalFinSet.class, "setHeight", double.class)));
317 // FreeformFinSet points handled as a special handler
320 setters.put("LaunchLug:radius", new DoubleSetter(
321 Reflection.findMethodStatic(LaunchLug.class, "setRadius", double.class)));
322 setters.put("LaunchLug:length", new DoubleSetter(
323 Reflection.findMethodStatic(LaunchLug.class, "setLength", double.class)));
324 setters.put("LaunchLug:thickness", new DoubleSetter(
325 Reflection.findMethodStatic(LaunchLug.class, "setThickness", double.class)));
326 setters.put("LaunchLug:radialdirection", new DoubleSetter(
327 Reflection.findMethodStatic(LaunchLug.class, "setRadialDirection", double.class),
330 // InternalComponent - nothing
332 // StructuralComponent
333 setters.put("StructuralComponent:material", new MaterialSetter(
334 Reflection.findMethodStatic(StructuralComponent.class, "setMaterial", Material.class),
335 Material.Type.BULK));
338 setters.put("RingComponent:length", new DoubleSetter(
339 Reflection.findMethodStatic(RingComponent.class, "setLength", double.class)));
340 setters.put("RingComponent:radialposition", new DoubleSetter(
341 Reflection.findMethodStatic(RingComponent.class, "setRadialPosition", double.class)));
342 setters.put("RingComponent:radialdirection", new DoubleSetter(
343 Reflection.findMethodStatic(RingComponent.class, "setRadialDirection", double.class),
346 // ThicknessRingComponent - radius on separate components due to differing automatics
347 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
348 Reflection.findMethodStatic(ThicknessRingComponent.class, "setThickness", double.class)));
351 setters.put("EngineBlock:outerradius", new DoubleSetter(
352 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadius", double.class),
354 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
357 setters.put("TubeCoupler:outerradius", new DoubleSetter(
358 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadius", double.class),
360 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
363 setters.put("InnerTube:outerradius", new DoubleSetter(
364 Reflection.findMethodStatic(InnerTube.class, "setOuterRadius", double.class)));
365 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
366 setters.put("InnerTube:clusterscale", new DoubleSetter(
367 Reflection.findMethodStatic(InnerTube.class, "setClusterScale", double.class)));
368 setters.put("InnerTube:clusterrotation", new DoubleSetter(
369 Reflection.findMethodStatic(InnerTube.class, "setClusterRotation", double.class),
372 // RadiusRingComponent
375 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
376 Reflection.findMethodStatic(RadiusRingComponent.class, "setInnerRadius", double.class)));
377 setters.put("Bulkhead:outerradius", new DoubleSetter(
378 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadius", double.class),
380 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
383 setters.put("CenteringRing:innerradius", new DoubleSetter(
384 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadius", double.class),
386 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
387 setters.put("CenteringRing:outerradius", new DoubleSetter(
388 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadius", double.class),
390 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
394 setters.put("MassObject:packedlength", new DoubleSetter(
395 Reflection.findMethodStatic(MassObject.class, "setLength", double.class)));
396 setters.put("MassObject:packedradius", new DoubleSetter(
397 Reflection.findMethodStatic(MassObject.class, "setRadius", double.class)));
398 setters.put("MassObject:radialposition", new DoubleSetter(
399 Reflection.findMethodStatic(MassObject.class, "setRadialPosition", double.class)));
400 setters.put("MassObject:radialdirection", new DoubleSetter(
401 Reflection.findMethodStatic(MassObject.class, "setRadialDirection", double.class),
405 setters.put("MassComponent:mass", new DoubleSetter(
406 Reflection.findMethodStatic(MassComponent.class, "setComponentMass", double.class)));
409 setters.put("ShockCord:cordlength", new DoubleSetter(
410 Reflection.findMethodStatic(ShockCord.class, "setCordLength", double.class)));
411 setters.put("ShockCord:material", new MaterialSetter(
412 Reflection.findMethodStatic(ShockCord.class, "setMaterial", Material.class),
413 Material.Type.LINE));
416 setters.put("RecoveryDevice:cd", new DoubleSetter(
417 Reflection.findMethodStatic(RecoveryDevice.class, "setCD", double.class),
419 Reflection.findMethodStatic(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
420 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
421 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
422 RecoveryDevice.DeployEvent.class));
423 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
424 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployAltitude", double.class)));
425 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
426 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployDelay", double.class)));
427 setters.put("RecoveryDevice:material", new MaterialSetter(
428 Reflection.findMethodStatic(RecoveryDevice.class, "setMaterial", Material.class),
429 Material.Type.SURFACE));
432 setters.put("Parachute:diameter", new DoubleSetter(
433 Reflection.findMethodStatic(Parachute.class, "setDiameter", double.class)));
434 setters.put("Parachute:linecount", new IntSetter(
435 Reflection.findMethodStatic(Parachute.class, "setLineCount", int.class)));
436 setters.put("Parachute:linelength", new DoubleSetter(
437 Reflection.findMethodStatic(Parachute.class, "setLineLength", double.class)));
438 setters.put("Parachute:linematerial", new MaterialSetter(
439 Reflection.findMethodStatic(Parachute.class, "setLineMaterial", Material.class),
440 Material.Type.LINE));
443 setters.put("Streamer:striplength", new DoubleSetter(
444 Reflection.findMethodStatic(Streamer.class, "setStripLength", double.class)));
445 setters.put("Streamer:stripwidth", new DoubleSetter(
446 Reflection.findMethodStatic(Streamer.class, "setStripWidth", double.class)));
449 // <motorconfiguration> handled by separate handler
450 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
451 Reflection.findMethodStatic(Rocket.class, "setReferenceType", ReferenceType.class),
452 ReferenceType.class));
453 setters.put("Rocket:customreference", new DoubleSetter(
454 Reflection.findMethodStatic(Rocket.class, "setCustomReferenceLength", double.class)));
455 setters.put("Rocket:designer", new StringSetter(
456 Reflection.findMethodStatic(Rocket.class, "setDesigner", String.class)));
457 setters.put("Rocket:revision", new StringSetter(
458 Reflection.findMethodStatic(Rocket.class, "setRevision", String.class)));
463 * Search for a enum value that has the corresponding name as an XML value. The current
464 * conversion from enum name to XML value is to lowercase the name and strip out all
465 * underscore characters. This method returns a match to these criteria, or <code>null</code>
466 * if no such enum exists.
468 * @param <T> then enum type.
469 * @param name the XML value, null ok.
470 * @param enumClass the class of the enum.
471 * @return the found enum value, or <code>null</code>.
473 public static <T extends Enum<T>> Enum<T> findEnum(String name,
474 Class<? extends Enum<T>> enumClass) {
479 for (Enum<T> e: enumClass.getEnumConstants()) {
480 if (e.name().toLowerCase().replace("_", "").equals(name)) {
489 * Convert a string to a double including formatting specifications of the OpenRocket
490 * file format. This accepts all formatting that is valid for
491 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
493 * @param s the string to parse.
494 * @return the numerical value.
495 * @throws NumberFormatException the the string cannot be parsed.
497 public static double stringToDouble(String s) throws NumberFormatException {
499 throw new NumberFormatException("null string");
500 if (s.equalsIgnoreCase("NaN"))
502 if (s.equalsIgnoreCase("Inf"))
503 return Double.POSITIVE_INFINITY;
504 if (s.equalsIgnoreCase("-Inf"))
505 return Double.NEGATIVE_INFINITY;
506 return Double.parseDouble(s);
515 * The starting point of the handlers. Accepts a single <openrocket> element and hands
516 * the contents to be read by a OpenRocketContentsHandler.
518 class OpenRocketHandler extends ElementHandler {
519 private OpenRocketContentHandler handler = null;
522 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
523 * has not been read yet.
525 * @return the document read, or null.
527 public OpenRocketDocument getDocument() {
528 return handler.getDocument();
532 public ElementHandler openElement(String element, HashMap<String, String> attributes,
533 WarningSet warnings) {
535 // Check for unknown elements
536 if (!element.equals("openrocket")) {
537 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
541 // Check for first call
542 if (handler != null) {
543 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
548 // Check version number
549 String version = null;
550 String creator = attributes.remove("creator");
551 String docVersion = attributes.remove("version");
552 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
553 if (v.equals(docVersion)) {
558 if (version == null) {
559 String str = "Unsupported document version";
560 if (docVersion != null)
561 str += " " + docVersion;
562 if (creator != null && !creator.trim().equals(""))
563 str += " (written using '" + creator.trim() + "')";
564 str += ", attempting to read file anyway.";
568 handler = new OpenRocketContentHandler();
573 public void closeElement(String element, HashMap<String, String> attributes,
574 String content, WarningSet warnings) throws SAXException {
575 attributes.remove("version");
576 attributes.remove("creator");
577 super.closeElement(element, attributes, content, warnings);
585 * Handles the content of the <openrocket> tag.
587 class OpenRocketContentHandler extends ElementHandler {
588 private final OpenRocketDocument doc;
589 private final Rocket rocket;
591 private boolean rocketDefined = false;
592 private boolean simulationsDefined = false;
594 public OpenRocketContentHandler() {
595 this.rocket = new Rocket();
596 this.doc = new OpenRocketDocument(rocket);
600 public OpenRocketDocument getDocument() {
607 public ElementHandler openElement(String element, HashMap<String, String> attributes,
608 WarningSet warnings) {
610 if (element.equals("rocket")) {
613 .fromString("Multiple rocket designs within one document, "
614 + "ignoring later ones."));
617 rocketDefined = true;
618 return new ComponentParameterHandler(rocket);
621 if (element.equals("simulations")) {
622 if (simulationsDefined) {
624 .fromString("Multiple simulation definitions within one document, "
625 + "ignoring later ones."));
628 simulationsDefined = true;
629 return new SimulationsHandler(doc);
632 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
642 * A handler that creates components from the corresponding elements. The control of the
643 * contents is passed on to ComponentParameterHandler.
645 class ComponentHandler extends ElementHandler {
646 private final RocketComponent parent;
648 public ComponentHandler(RocketComponent parent) {
649 this.parent = parent;
653 public ElementHandler openElement(String element, HashMap<String, String> attributes,
654 WarningSet warnings) {
656 // Attempt to construct new component
657 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
659 if (constructor == null) {
660 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
666 c = constructor.newInstance();
667 } catch (InstantiationException e) {
668 throw new RuntimeException("Error constructing component.", e);
669 } catch (IllegalAccessException e) {
670 throw new RuntimeException("Error constructing component.", e);
671 } catch (InvocationTargetException e) {
672 throw new RuntimeException("Error constructing component.", e);
677 return new ComponentParameterHandler(c);
683 * A handler that populates the parameters of a previously constructed rocket component.
684 * This uses the setters, or delegates the handling to another handler for specific
687 class ComponentParameterHandler extends ElementHandler {
688 private final RocketComponent component;
690 public ComponentParameterHandler(RocketComponent c) {
695 public ElementHandler openElement(String element, HashMap<String, String> attributes,
696 WarningSet warnings) {
698 // Check for specific elements that contain other elements
699 if (element.equals("subcomponents")) {
700 return new ComponentHandler(component);
702 if (element.equals("motormount")) {
703 if (!(component instanceof MotorMount)) {
704 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
707 return new MotorMountHandler((MotorMount)component);
709 if (element.equals("finpoints")) {
710 if (!(component instanceof FreeformFinSet)) {
711 warnings.add(Warning.fromString("Illegal component defined for fin points."));
714 return new FinSetPointHandler((FreeformFinSet)component);
716 if (element.equals("motorconfiguration")) {
717 if (!(component instanceof Rocket)) {
718 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
721 return new MotorConfigurationHandler((Rocket)component);
725 return PlainTextHandler.INSTANCE;
729 public void closeElement(String element, HashMap<String, String> attributes,
730 String content, WarningSet warnings) {
732 if (element.equals("subcomponents") || element.equals("motormount") ||
733 element.equals("finpoints") || element.equals("motorconfiguration")) {
737 // Search for the correct setter class
740 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
741 String setterKey = c.getSimpleName() + ":" + element;
742 Setter s = DocumentConfig.setters.get(setterKey);
745 System.out.println("Calling with key "+setterKey);
746 s.set(component, content, attributes, warnings);
749 if (DocumentConfig.setters.containsKey(setterKey)) {
750 // Key exists but is null -> invalid parameter
756 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
757 + component.getComponentName() + ", ignoring."));
764 * A handler that reads the <point> specifications within the freeformfinset's
765 * <finpoints> elements.
767 class FinSetPointHandler extends ElementHandler {
768 private final FreeformFinSet finset;
769 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
771 public FinSetPointHandler(FreeformFinSet finset) {
772 this.finset = finset;
776 public ElementHandler openElement(String element, HashMap<String, String> attributes,
777 WarningSet warnings) {
778 return PlainTextHandler.INSTANCE;
783 public void closeElement(String element, HashMap<String, String> attributes,
784 String content, WarningSet warnings) throws SAXException {
786 String strx = attributes.remove("x");
787 String stry = attributes.remove("y");
788 if (strx == null || stry == null) {
789 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
793 double x = Double.parseDouble(strx);
794 double y = Double.parseDouble(stry);
795 coordinates.add(new Coordinate(x,y));
796 } catch (NumberFormatException e) {
797 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
801 super.closeElement(element, attributes, content, warnings);
805 public void endHandler(String element, HashMap<String, String> attributes,
806 String content, WarningSet warnings) {
808 finset.setPoints(coordinates.toArray(new Coordinate[0]));
809 } catch (IllegalFinPointException e) {
810 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
816 class MotorMountHandler extends ElementHandler {
817 private final MotorMount mount;
818 private MotorHandler motorHandler;
820 public MotorMountHandler(MotorMount mount) {
822 mount.setMotorMount(true);
826 public ElementHandler openElement(String element, HashMap<String, String> attributes,
827 WarningSet warnings) {
829 if (element.equals("motor")) {
830 motorHandler = new MotorHandler();
834 if (element.equals("ignitionevent") ||
835 element.equals("ignitiondelay") ||
836 element.equals("overhang")) {
837 return PlainTextHandler.INSTANCE;
840 warnings.add(Warning.fromString("Unknown element '"+element+"' encountered, ignoring."));
847 public void closeElement(String element, HashMap<String, String> attributes,
848 String content, WarningSet warnings) throws SAXException {
850 if (element.equals("motor")) {
851 String id = attributes.get("configid");
852 if (id == null || id.equals("")) {
853 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
857 Motor motor = motorHandler.getMotor(warnings);
858 mount.setMotor(id, motor);
859 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
863 if (element.equals("ignitionevent")) {
864 MotorMount.IgnitionEvent event = null;
865 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
866 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
872 warnings.add(Warning.fromString("Unknown ignition event type '"+content+"', ignoring."));
875 mount.setIgnitionEvent(event);
879 if (element.equals("ignitiondelay")) {
882 d = Double.parseDouble(content);
883 } catch (NumberFormatException nfe) {
884 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
887 mount.setIgnitionDelay(d);
891 if (element.equals("overhang")) {
894 d = Double.parseDouble(content);
895 } catch (NumberFormatException nfe) {
896 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
899 mount.setMotorOverhang(d);
903 super.closeElement(element, attributes, content, warnings);
910 class MotorConfigurationHandler extends ElementHandler {
911 private final Rocket rocket;
912 private String name = null;
913 private boolean inNameElement = false;
915 public MotorConfigurationHandler(Rocket rocket) {
916 this.rocket = rocket;
920 public ElementHandler openElement(String element, HashMap<String, String> attributes,
921 WarningSet warnings) {
923 if (inNameElement || !element.equals("name")) {
924 warnings.add(Warning.FILE_INVALID_PARAMETER);
927 inNameElement = true;
929 return PlainTextHandler.INSTANCE;
933 public void closeElement(String element, HashMap<String, String> attributes,
934 String content, WarningSet warnings) {
939 public void endHandler(String element, HashMap<String, String> attributes,
940 String content, WarningSet warnings) throws SAXException {
942 String configid = attributes.remove("configid");
943 if (configid == null || configid.equals("")) {
944 warnings.add(Warning.FILE_INVALID_PARAMETER);
948 if (!rocket.addMotorConfigurationID(configid)) {
949 warnings.add("Duplicate motor configuration ID used.");
953 if (name != null && name.trim().length() > 0) {
954 rocket.setMotorConfigurationName(configid, name);
957 if ("true".equals(attributes.remove("default"))) {
958 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
961 super.closeElement(element, attributes, content, warnings);
966 class MotorHandler extends ElementHandler {
967 private Motor.Type type = null;
968 private String manufacturer = null;
969 private String designation = null;
970 private double diameter = Double.NaN;
971 private double length = Double.NaN;
972 private double delay = Double.NaN;
975 public ElementHandler openElement(String element, HashMap<String, String> attributes,
976 WarningSet warnings) {
977 return PlainTextHandler.INSTANCE;
982 * Return the motor to use, or null.
984 public Motor getMotor(WarningSet warnings) {
985 if (designation == null) {
986 warnings.add(Warning.fromString("No motor specified, ignoring."));
989 Motor[] motors = Databases.findMotors(type, manufacturer, designation, diameter, length);
990 if (motors.length == 0) {
991 String str = "No motor with designation '"+designation+"'";
992 if (manufacturer != null)
993 str += " for manufacturer '" + manufacturer + "'";
994 warnings.add(Warning.fromString(str + " found."));
997 if (motors.length > 1) {
998 String str = "Multiple motors with designation '"+designation+"'";
999 if (manufacturer != null)
1000 str += " for manufacturer '" + manufacturer + "'";
1001 warnings.add(Warning.fromString(str + " found, one chosen arbitrarily."));
1008 * Return the delay to use for the motor.
1010 public double getDelay(WarningSet warnings) {
1011 if (Double.isNaN(delay)) {
1012 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1013 return Motor.PLUGGED;
1020 public void closeElement(String element, HashMap<String, String> attributes,
1021 String content, WarningSet warnings) throws SAXException {
1023 content = content.trim();
1025 if (element.equals("type")) {
1029 for (Motor.Type t: Motor.Type.values()) {
1030 if (t.name().toLowerCase().equals(content)) {
1036 warnings.add(Warning.fromString("Unknown motor type '"+content+"', ignoring."));
1039 } else if (element.equals("manufacturer")) {
1042 manufacturer = content;
1044 } else if (element.equals("designation")) {
1047 designation = content;
1049 } else if (element.equals("diameter")) {
1052 diameter = Double.NaN;
1054 diameter = Double.parseDouble(content);
1055 } catch (NumberFormatException e) {
1058 if (Double.isNaN(diameter)) {
1059 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1062 } else if (element.equals("length")) {
1065 length = Double.NaN;
1067 length = Double.parseDouble(content);
1068 } catch (NumberFormatException ignore) { }
1070 if (Double.isNaN(length)) {
1071 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1074 } else if (element.equals("delay")) {
1078 if (content.equals("none")) {
1079 delay = Motor.PLUGGED;
1082 delay = Double.parseDouble(content);
1083 } catch (NumberFormatException ignore) { }
1085 if (Double.isNaN(delay)) {
1086 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1092 super.closeElement(element, attributes, content, warnings);
1100 class SimulationsHandler extends ElementHandler {
1101 private final OpenRocketDocument doc;
1102 private SingleSimulationHandler handler;
1104 public SimulationsHandler(OpenRocketDocument doc) {
1109 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1110 WarningSet warnings) {
1112 if (!element.equals("simulation")) {
1113 warnings.add("Unknown element '"+element+"', ignoring.");
1117 handler = new SingleSimulationHandler(doc);
1122 public void closeElement(String element, HashMap<String, String> attributes,
1123 String content, WarningSet warnings) throws SAXException {
1124 attributes.remove("status");
1125 super.closeElement(element, attributes, content, warnings);
1131 class SingleSimulationHandler extends ElementHandler {
1133 private final OpenRocketDocument doc;
1135 private String name;
1137 private SimulationConditionsHandler conditionHandler;
1138 private FlightDataHandler dataHandler;
1140 private final List<String> listeners = new ArrayList<String>();
1142 public SingleSimulationHandler(OpenRocketDocument doc) {
1149 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1150 WarningSet warnings) {
1152 if (element.equals("name") || element.equals("simulator") ||
1153 element.equals("calculator") || element.equals("listener")) {
1154 return PlainTextHandler.INSTANCE;
1155 } else if (element.equals("conditions")) {
1156 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1157 return conditionHandler;
1158 } else if (element.equals("flightdata")) {
1159 dataHandler = new FlightDataHandler();
1162 warnings.add("Unknown element '"+element+"', ignoring.");
1168 public void closeElement(String element, HashMap<String, String> attributes,
1169 String content, WarningSet warnings) {
1171 if (element.equals("name")) {
1173 } else if (element.equals("simulator")) {
1174 if (!content.trim().equals("RK4Simulator")) {
1175 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1177 } else if (element.equals("calculator")) {
1178 if (!content.trim().equals("BarrowmanCalculator")) {
1179 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1181 } else if (element.equals("listener") && content.trim().length() > 0) {
1182 listeners.add(content.trim());
1188 public void endHandler(String element, HashMap<String, String> attributes,
1189 String content, WarningSet warnings) {
1191 String s = attributes.get("status");
1192 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1193 if (status == null) {
1194 warnings.add("Simulation status unknown, assuming outdated.");
1195 status = Simulation.Status.OUTDATED;
1198 SimulationConditions conditions;
1199 if (conditionHandler != null) {
1200 conditions = conditionHandler.getConditions();
1202 warnings.add("Simulation conditions not defined, using defaults.");
1203 conditions = new SimulationConditions(doc.getRocket());
1207 name = "Simulation";
1210 if (dataHandler == null)
1213 data = dataHandler.getFlightData();
1215 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1216 conditions, listeners, data);
1218 doc.addSimulation(simulation);
1224 class SimulationConditionsHandler extends ElementHandler {
1225 private SimulationConditions conditions;
1226 private AtmosphereHandler atmosphereHandler;
1228 public SimulationConditionsHandler(Rocket rocket) {
1229 conditions = new SimulationConditions(rocket);
1232 public SimulationConditions getConditions() {
1237 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1238 WarningSet warnings) {
1239 if (element.equals("atmosphere")) {
1240 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1241 return atmosphereHandler;
1243 return PlainTextHandler.INSTANCE;
1247 public void closeElement(String element, HashMap<String, String> attributes,
1248 String content, WarningSet warnings) {
1250 double d = Double.NaN;
1252 d = Double.parseDouble(content);
1253 } catch (NumberFormatException ignore) { }
1256 if (element.equals("configid")) {
1257 if (content.equals("")) {
1258 conditions.setMotorConfigurationID(null);
1260 conditions.setMotorConfigurationID(content);
1262 } else if (element.equals("launchrodlength")) {
1263 if (Double.isNaN(d)) {
1264 warnings.add("Illegal launch rod length defined, ignoring.");
1266 conditions.setLaunchRodLength(d);
1268 } else if (element.equals("launchrodangle")) {
1269 if (Double.isNaN(d)) {
1270 warnings.add("Illegal launch rod angle defined, ignoring.");
1272 conditions.setLaunchRodAngle(d*Math.PI/180);
1274 } else if (element.equals("launchroddirection")) {
1275 if (Double.isNaN(d)) {
1276 warnings.add("Illegal launch rod direction defined, ignoring.");
1278 conditions.setLaunchRodDirection(d*Math.PI/180);
1280 } else if (element.equals("windaverage")) {
1281 if (Double.isNaN(d)) {
1282 warnings.add("Illegal average windspeed defined, ignoring.");
1284 conditions.setWindSpeedAverage(d);
1286 } else if (element.equals("windturbulence")) {
1287 if (Double.isNaN(d)) {
1288 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1290 conditions.setWindTurbulenceIntensity(d);
1292 } else if (element.equals("launchaltitude")) {
1293 if (Double.isNaN(d)) {
1294 warnings.add("Illegal launch altitude defined, ignoring.");
1296 conditions.setLaunchAltitude(d);
1298 } else if (element.equals("launchlatitude")) {
1299 if (Double.isNaN(d)) {
1300 warnings.add("Illegal launch latitude defined, ignoring.");
1302 conditions.setLaunchLatitude(d);
1304 } else if (element.equals("atmosphere")) {
1305 atmosphereHandler.storeSettings(conditions, warnings);
1306 } else if (element.equals("timestep")) {
1307 if (Double.isNaN(d)) {
1308 warnings.add("Illegal time step defined, ignoring.");
1310 conditions.setTimeStep(d);
1317 class AtmosphereHandler extends ElementHandler {
1318 private final String model;
1319 private double temperature = Double.NaN;
1320 private double pressure = Double.NaN;
1322 public AtmosphereHandler(String model) {
1327 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1328 WarningSet warnings) {
1329 return PlainTextHandler.INSTANCE;
1333 public void closeElement(String element, HashMap<String, String> attributes,
1334 String content, WarningSet warnings) throws SAXException {
1336 double d = Double.NaN;
1338 d = Double.parseDouble(content);
1339 } catch (NumberFormatException ignore) { }
1341 if (element.equals("basetemperature")) {
1342 if (Double.isNaN(d)) {
1343 warnings.add("Illegal base temperature specified, ignoring.");
1346 } else if (element.equals("basepressure")) {
1347 if (Double.isNaN(d)) {
1348 warnings.add("Illegal base pressure specified, ignoring.");
1352 super.closeElement(element, attributes, content, warnings);
1357 public void storeSettings(SimulationConditions cond, WarningSet warnings) {
1358 if (!Double.isNaN(pressure)) {
1359 cond.setLaunchPressure(pressure);
1361 if (!Double.isNaN(temperature)) {
1362 cond.setLaunchTemperature(temperature);
1365 if ("isa".equals(model)) {
1366 cond.setISAAtmosphere(true);
1367 } else if ("extendedisa".equals(model)){
1368 cond.setISAAtmosphere(false);
1370 cond.setISAAtmosphere(true);
1371 warnings.add("Unknown atmospheric model, using ISA.");
1378 class FlightDataHandler extends ElementHandler {
1380 private FlightDataBranchHandler dataHandler;
1381 private WarningSet warningSet = new WarningSet();
1382 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1384 private FlightData data;
1386 public FlightData getFlightData() {
1391 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1392 WarningSet warnings) {
1394 if (element.equals("warning")) {
1395 return PlainTextHandler.INSTANCE;
1397 if (element.equals("databranch")) {
1398 if (attributes.get("name") == null || attributes.get("types")==null) {
1399 warnings.add("Illegal flight data definition, ignoring.");
1402 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1403 attributes.get("types"));
1407 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1413 public void closeElement(String element, HashMap<String, String> attributes,
1414 String content, WarningSet warnings) {
1416 if (element.equals("databranch")) {
1417 FlightDataBranch branch = dataHandler.getBranch();
1418 if (branch.getLength() > 0) {
1419 branches.add(branch);
1421 } else if (element.equals("warning")) {
1422 warningSet.add(Warning.fromString(content));
1428 public void endHandler(String element, HashMap<String, String> attributes,
1429 String content, WarningSet warnings) {
1431 if (branches.size() > 0) {
1432 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1434 double maxAltitude = Double.NaN;
1435 double maxVelocity = Double.NaN;
1436 double maxAcceleration = Double.NaN;
1437 double maxMach = Double.NaN;
1438 double timeToApogee = Double.NaN;
1439 double flightTime = Double.NaN;
1440 double groundHitVelocity = Double.NaN;
1443 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1444 } catch (NumberFormatException ignore) { }
1446 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1447 } catch (NumberFormatException ignore) { }
1449 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1450 } catch (NumberFormatException ignore) { }
1452 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1453 } catch (NumberFormatException ignore) { }
1455 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1456 } catch (NumberFormatException ignore) { }
1458 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1459 } catch (NumberFormatException ignore) { }
1462 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1463 } catch (NumberFormatException ignore) { }
1465 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1466 timeToApogee, flightTime, groundHitVelocity);
1469 data.getWarningSet().addAll(warningSet);
1476 class FlightDataBranchHandler extends ElementHandler {
1477 private final FlightDataBranch.Type[] types;
1478 private final FlightDataBranch branch;
1480 public FlightDataBranchHandler(String name, String typeList) {
1481 String[] split = typeList.split(",");
1482 types = new FlightDataBranch.Type[split.length];
1483 for (int i=0; i < split.length; i++) {
1484 types[i] = FlightDataBranch.getType(split[i], UnitGroup.UNITS_NONE);
1487 // TODO: LOW: May throw an IllegalArgumentException
1488 branch = new FlightDataBranch(name, types);
1491 public FlightDataBranch getBranch() {
1497 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1498 WarningSet warnings) {
1500 if (element.equals("datapoint"))
1501 return PlainTextHandler.INSTANCE;
1502 if (element.equals("event"))
1503 return PlainTextHandler.INSTANCE;
1505 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1511 public void closeElement(String element, HashMap<String, String> attributes,
1512 String content, WarningSet warnings) {
1514 if (element.equals("event")) {
1516 FlightEvent.Type type;
1519 time = DocumentConfig.stringToDouble(attributes.get("time"));
1520 } catch (NumberFormatException e) {
1521 warnings.add("Illegal event specification, ignoring.");
1525 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1527 warnings.add("Illegal event specification, ignoring.");
1531 branch.addEvent(time, new FlightEvent(type, time));
1535 if (!element.equals("datapoint")) {
1536 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1540 // element == "datapoint"
1543 // Check line format
1544 String[] split = content.split(",");
1545 if (split.length != types.length) {
1546 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1550 // Parse the doubles
1551 double[] values = new double[split.length];
1552 for (int i=0; i < values.length; i++) {
1554 values[i] = DocumentConfig.stringToDouble(split[i]);
1555 } catch (NumberFormatException e) {
1556 warnings.add("Data point format error, ignoring point.");
1561 // Add point to branch
1563 for (int i=0; i < types.length; i++) {
1564 branch.setValue(types[i], values[i]);
1574 ///////////////// Setters implementation
1580 * Set the specified value to the given component.
1582 * @param component the component to which to set.
1583 * @param value the value within the element.
1584 * @param attributes attributes for the element.
1585 * @param warnings the warning set to use.
1587 public void set(RocketComponent component, String value,
1588 HashMap<String, String> attributes, WarningSet warnings);
1592 //// StringSetter - sets the value to the contained String
1593 class StringSetter implements Setter {
1594 private final Reflection.Method setMethod;
1596 public StringSetter(Reflection.Method set) {
1600 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1601 WarningSet warnings) {
1602 setMethod.invoke(c, s);
1606 //// IntSetter - set an integer value
1607 class IntSetter implements Setter {
1608 private final Reflection.Method setMethod;
1610 public IntSetter(Reflection.Method set) {
1614 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1615 WarningSet warnings) {
1617 int n = Integer.parseInt(s);
1618 setMethod.invoke(c, n);
1619 } catch (NumberFormatException e) {
1620 warnings.add(Warning.FILE_INVALID_PARAMETER);
1626 //// BooleanSetter - set a boolean value
1627 class BooleanSetter implements Setter {
1628 private final Reflection.Method setMethod;
1630 public BooleanSetter(Reflection.Method set) {
1634 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1635 WarningSet warnings) {
1638 if (s.equalsIgnoreCase("true")) {
1639 setMethod.invoke(c, true);
1640 } else if (s.equalsIgnoreCase("false")) {
1641 setMethod.invoke(c, false);
1643 warnings.add(Warning.FILE_INVALID_PARAMETER);
1650 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1651 //// calls a setXXX(boolean) method.
1652 class DoubleSetter implements Setter {
1653 private final Reflection.Method setMethod;
1654 private final String specialString;
1655 private final Reflection.Method specialMethod;
1656 private final double multiplier;
1659 * Set only the double value.
1660 * @param set set method for the double value.
1662 public DoubleSetter(Reflection.Method set) {
1663 this.setMethod = set;
1664 this.specialString = null;
1665 this.specialMethod = null;
1666 this.multiplier = 1.0;
1670 * Multiply with the given multiplier and set the double value.
1671 * @param set set method for the double value.
1672 * @param mul multiplier.
1674 public DoubleSetter(Reflection.Method set, double mul) {
1675 this.setMethod = set;
1676 this.specialString = null;
1677 this.specialMethod = null;
1678 this.multiplier = mul;
1682 * Set the double value, or if the value equals the special string, use the
1683 * special setter and set it to true.
1685 * @param set double setter.
1686 * @param special special string
1687 * @param specialMethod boolean setter.
1689 public DoubleSetter(Reflection.Method set, String special,
1690 Reflection.Method specialMethod) {
1691 this.setMethod = set;
1692 this.specialString = special;
1693 this.specialMethod = specialMethod;
1694 this.multiplier = 1.0;
1698 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1699 WarningSet warnings) {
1703 // Check for special case
1704 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1705 specialMethod.invoke(c, true);
1711 double d = Double.parseDouble(s);
1712 setMethod.invoke(c, d * multiplier);
1713 } catch (NumberFormatException e) {
1714 warnings.add(Warning.FILE_INVALID_PARAMETER);
1720 class OverrideSetter implements Setter {
1721 private final Reflection.Method setMethod;
1722 private final Reflection.Method enabledMethod;
1724 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1725 this.setMethod = set;
1726 this.enabledMethod = enabledMethod;
1729 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1730 WarningSet warnings) {
1733 double d = Double.parseDouble(s);
1734 setMethod.invoke(c, d);
1735 enabledMethod.invoke(c, true);
1736 } catch (NumberFormatException e) {
1737 warnings.add(Warning.FILE_INVALID_PARAMETER);
1742 //// EnumSetter - sets a generic enum type
1743 class EnumSetter<T extends Enum<T>> implements Setter {
1744 private final Reflection.Method setter;
1745 private final Class<T> enumClass;
1747 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1749 this.enumClass = enumClass;
1753 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1754 WarningSet warnings) {
1756 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1757 if (setEnum == null) {
1758 warnings.add(Warning.FILE_INVALID_PARAMETER);
1762 setter.invoke(c, setEnum);
1767 //// ColorSetter - sets a Color value
1768 class ColorSetter implements Setter {
1769 private final Reflection.Method setMethod;
1771 public ColorSetter(Reflection.Method set) {
1775 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1776 WarningSet warnings) {
1778 String red = attributes.get("red");
1779 String green = attributes.get("green");
1780 String blue = attributes.get("blue");
1782 if (red == null || green == null || blue == null) {
1783 warnings.add(Warning.FILE_INVALID_PARAMETER);
1789 r = Integer.parseInt(red);
1790 g = Integer.parseInt(green);
1791 b = Integer.parseInt(blue);
1792 } catch (NumberFormatException e) {
1793 warnings.add(Warning.FILE_INVALID_PARAMETER);
1797 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1798 warnings.add(Warning.FILE_INVALID_PARAMETER);
1802 Color color = new Color(r, g, b);
1803 setMethod.invoke(c, color);
1805 if (!s.trim().equals("")) {
1806 warnings.add(Warning.FILE_INVALID_PARAMETER);
1813 class MaterialSetter implements Setter {
1814 private final Reflection.Method setMethod;
1815 private final Material.Type type;
1817 public MaterialSetter(Reflection.Method set, Material.Type type) {
1818 this.setMethod = set;
1822 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1823 WarningSet warnings) {
1829 if (name.equals("")) {
1830 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1837 str = attributes.remove("density");
1839 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1843 density = Double.parseDouble(str);
1844 } catch (NumberFormatException e) {
1845 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1850 // double thickness = 0;
1851 // str = attributes.remove("thickness");
1854 // thickness = Double.parseDouble(str);
1855 // } catch (NumberFormatException e){
1856 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1860 // Check type if specified
1861 str = attributes.remove("type");
1862 if (str != null && !type.name().toLowerCase().equals(str)) {
1863 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1867 mat = Databases.findMaterial(type, name, density, false);
1869 setMethod.invoke(c, mat);
1876 class PositionSetter implements Setter {
1878 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1879 WarningSet warnings) {
1881 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1882 RocketComponent.Position.class);
1884 warnings.add(Warning.FILE_INVALID_PARAMETER);
1890 pos = Double.parseDouble(value);
1891 } catch (NumberFormatException e) {
1892 warnings.add(Warning.FILE_INVALID_PARAMETER);
1896 if (c instanceof FinSet) {
1897 ((FinSet)c).setRelativePosition(type);
1898 c.setPositionValue(pos);
1899 } else if (c instanceof LaunchLug) {
1900 ((LaunchLug)c).setRelativePosition(type);
1901 c.setPositionValue(pos);
1902 } else if (c instanceof InternalComponent) {
1903 ((InternalComponent)c).setRelativePosition(type);
1904 c.setPositionValue(pos);
1906 warnings.add(Warning.FILE_INVALID_PARAMETER);
1913 class FinTabPositionSetter extends DoubleSetter {
1915 public FinTabPositionSetter() {
1916 super(Reflection.findMethodStatic(FinSet.class, "setTabShift", double.class));
1920 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1921 WarningSet warnings) {
1923 if (!(c instanceof FinSet)) {
1924 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
1927 String relative = attributes.get("relativeto");
1928 FinSet.TabRelativePosition position =
1929 (TabRelativePosition) DocumentConfig.findEnum(relative,
1930 FinSet.TabRelativePosition.class);
1932 if (position != null) {
1934 ((FinSet)c).setTabRelativePosition(position);
1937 if (relative == null) {
1938 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
1940 warnings.add("Illegal attribute value '" + relative + "' encountered.");
1944 super.set(c, s, attributes, warnings);
1951 class ClusterConfigurationSetter implements Setter {
1953 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
1954 WarningSet warnings) {
1956 if (!(component instanceof Clusterable)) {
1957 warnings.add("Illegal component defined as cluster.");
1961 ClusterConfiguration config = null;
1962 for (ClusterConfiguration c: ClusterConfiguration.CONFIGURATIONS) {
1963 if (c.getXMLName().equals(value)) {
1969 if (config == null) {
1970 warnings.add("Illegal cluster configuration specified.");
1974 ((Clusterable)component).setClusterConfiguration(config);