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.BugException;
71 import net.sf.openrocket.util.Coordinate;
72 import net.sf.openrocket.util.LineStyle;
73 import net.sf.openrocket.util.Reflection;
75 import org.xml.sax.InputSource;
76 import org.xml.sax.SAXException;
80 * Class that loads a rocket definition from an OpenRocket rocket file.
82 * This class uses SAX to read the XML file format. The
83 * {@link #loadFromStream(InputStream)} method simply sets the system up and
84 * starts the parsing, while the actual logic is in the private inner class
85 * <code>OpenRocketHandler</code>.
87 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
90 public class OpenRocketLoader extends RocketLoader {
93 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
95 InputSource xmlSource = new InputSource(source);
96 OpenRocketHandler handler = new OpenRocketHandler();
100 SimpleSAX.readXML(xmlSource, handler, warnings);
101 } catch (SAXException e) {
102 throw new RocketLoadException("Malformed XML in input.", e);
106 OpenRocketDocument doc = handler.getDocument();
107 doc.getDefaultConfiguration().setAllStages();
109 // Deduce suitable time skip
110 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
111 for (Simulation s: doc.getSimulations()) {
112 if (s.getStatus() == Simulation.Status.EXTERNAL ||
113 s.getStatus() == Simulation.Status.NOT_SIMULATED)
115 if (s.getSimulatedData() == null)
117 if (s.getSimulatedData().getBranchCount() == 0)
119 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
122 List<Double> list = branch.get(FlightDataBranch.TYPE_TIME);
126 double previousTime = Double.NaN;
127 for (double time: list) {
128 if (time - previousTime < timeSkip)
129 timeSkip = time-previousTime;
134 timeSkip = Math.rint(timeSkip*100)/100;
136 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
137 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
138 doc.getDefaultStorageOptions().setExplicitlySet(false);
148 class DocumentConfig {
150 /* Remember to update OpenRocketSaver as well! */
151 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1" };
154 //////// Component constructors
155 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
158 // External components
159 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
160 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
161 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
162 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
163 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
164 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
165 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
167 // Internal components
168 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
169 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
170 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
171 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
172 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
174 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
175 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
176 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
177 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
180 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
182 } catch (NoSuchMethodException e) {
183 throw new BugException(
184 "Error in constructing the 'constructors' HashMap.");
189 //////// Parameter setters
191 * The keys are of the form Class:param, where Class is the class name and param
192 * the element name. Setters are searched for in descending class order.
193 * A setter of null means setting the parameter is not allowed.
195 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
198 setters.put("RocketComponent:name", new StringSetter(
199 Reflection.findMethodStatic(RocketComponent.class, "setName", String.class)));
200 setters.put("RocketComponent:color", new ColorSetter(
201 Reflection.findMethodStatic(RocketComponent.class, "setColor", Color.class)));
202 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
203 Reflection.findMethodStatic(RocketComponent.class, "setLineStyle", LineStyle.class),
205 setters.put("RocketComponent:position", new PositionSetter());
206 setters.put("RocketComponent:overridemass", new OverrideSetter(
207 Reflection.findMethodStatic(RocketComponent.class, "setOverrideMass", double.class),
208 Reflection.findMethodStatic(RocketComponent.class, "setMassOverridden", boolean.class)));
209 setters.put("RocketComponent:overridecg", new OverrideSetter(
210 Reflection.findMethodStatic(RocketComponent.class, "setOverrideCGX", double.class),
211 Reflection.findMethodStatic(RocketComponent.class, "setCGOverridden", boolean.class)));
212 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
213 Reflection.findMethodStatic(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
214 setters.put("RocketComponent:comment", new StringSetter(
215 Reflection.findMethodStatic(RocketComponent.class, "setComment", String.class)));
218 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
219 Reflection.findMethodStatic(ExternalComponent.class, "setFinish", Finish.class),
221 setters.put("ExternalComponent:material", new MaterialSetter(
222 Reflection.findMethodStatic(ExternalComponent.class, "setMaterial", Material.class),
223 Material.Type.BULK));
226 setters.put("BodyComponent:length", new DoubleSetter(
227 Reflection.findMethodStatic(BodyComponent.class, "setLength", double.class)));
229 // SymmetricComponent
230 setters.put("SymmetricComponent:thickness", new DoubleSetter(
231 Reflection.findMethodStatic(SymmetricComponent.class,"setThickness", double.class),
233 Reflection.findMethodStatic(SymmetricComponent.class,"setFilled", boolean.class)));
236 setters.put("BodyTube:radius", new DoubleSetter(
237 Reflection.findMethodStatic(BodyTube.class, "setRadius", double.class),
239 Reflection.findMethodStatic(BodyTube.class,"setRadiusAutomatic", boolean.class)));
242 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
243 Reflection.findMethodStatic(Transition.class, "setType", Transition.Shape.class),
244 Transition.Shape.class));
245 setters.put("Transition:shapeclipped", new BooleanSetter(
246 Reflection.findMethodStatic(Transition.class, "setClipped", boolean.class)));
247 setters.put("Transition:shapeparameter", new DoubleSetter(
248 Reflection.findMethodStatic(Transition.class, "setShapeParameter", double.class)));
250 setters.put("Transition:foreradius", new DoubleSetter(
251 Reflection.findMethodStatic(Transition.class, "setForeRadius", double.class),
253 Reflection.findMethodStatic(Transition.class, "setForeRadiusAutomatic", boolean.class)));
254 setters.put("Transition:aftradius", new DoubleSetter(
255 Reflection.findMethodStatic(Transition.class, "setAftRadius", double.class),
257 Reflection.findMethodStatic(Transition.class, "setAftRadiusAutomatic", boolean.class)));
259 setters.put("Transition:foreshoulderradius", new DoubleSetter(
260 Reflection.findMethodStatic(Transition.class, "setForeShoulderRadius", double.class)));
261 setters.put("Transition:foreshoulderlength", new DoubleSetter(
262 Reflection.findMethodStatic(Transition.class, "setForeShoulderLength", double.class)));
263 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
264 Reflection.findMethodStatic(Transition.class, "setForeShoulderThickness", double.class)));
265 setters.put("Transition:foreshouldercapped", new BooleanSetter(
266 Reflection.findMethodStatic(Transition.class, "setForeShoulderCapped", boolean.class)));
268 setters.put("Transition:aftshoulderradius", new DoubleSetter(
269 Reflection.findMethodStatic(Transition.class, "setAftShoulderRadius", double.class)));
270 setters.put("Transition:aftshoulderlength", new DoubleSetter(
271 Reflection.findMethodStatic(Transition.class, "setAftShoulderLength", double.class)));
272 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
273 Reflection.findMethodStatic(Transition.class, "setAftShoulderThickness", double.class)));
274 setters.put("Transition:aftshouldercapped", new BooleanSetter(
275 Reflection.findMethodStatic(Transition.class, "setAftShoulderCapped", boolean.class)));
277 // NoseCone - disable disallowed elements
278 setters.put("NoseCone:foreradius", null);
279 setters.put("NoseCone:foreshoulderradius", null);
280 setters.put("NoseCone:foreshoulderlength", null);
281 setters.put("NoseCone:foreshoulderthickness", null);
282 setters.put("NoseCone:foreshouldercapped", null);
285 setters.put("FinSet:fincount", new IntSetter(
286 Reflection.findMethodStatic(FinSet.class, "setFinCount", int.class)));
287 setters.put("FinSet:rotation", new DoubleSetter(
288 Reflection.findMethodStatic(FinSet.class, "setBaseRotation", double.class), Math.PI/180.0));
289 setters.put("FinSet:thickness", new DoubleSetter(
290 Reflection.findMethodStatic(FinSet.class, "setThickness", double.class)));
291 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
292 Reflection.findMethodStatic(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
293 FinSet.CrossSection.class));
294 setters.put("FinSet:cant", new DoubleSetter(
295 Reflection.findMethodStatic(FinSet.class, "setCantAngle", double.class), Math.PI/180.0));
296 setters.put("FinSet:tabheight", new DoubleSetter(
297 Reflection.findMethodStatic(FinSet.class, "setTabHeight", double.class)));
298 setters.put("FinSet:tablength", new DoubleSetter(
299 Reflection.findMethodStatic(FinSet.class, "setTabLength", double.class)));
300 setters.put("FinSet:tabposition", new FinTabPositionSetter());
303 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
304 Reflection.findMethodStatic(TrapezoidFinSet.class, "setRootChord", double.class)));
305 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
306 Reflection.findMethodStatic(TrapezoidFinSet.class, "setTipChord", double.class)));
307 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
308 Reflection.findMethodStatic(TrapezoidFinSet.class, "setSweep", double.class)));
309 setters.put("TrapezoidFinSet:height", new DoubleSetter(
310 Reflection.findMethodStatic(TrapezoidFinSet.class, "setHeight", double.class)));
313 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
314 Reflection.findMethodStatic(EllipticalFinSet.class, "setLength", double.class)));
315 setters.put("EllipticalFinSet:height", new DoubleSetter(
316 Reflection.findMethodStatic(EllipticalFinSet.class, "setHeight", double.class)));
318 // FreeformFinSet points handled as a special handler
321 setters.put("LaunchLug:radius", new DoubleSetter(
322 Reflection.findMethodStatic(LaunchLug.class, "setRadius", double.class)));
323 setters.put("LaunchLug:length", new DoubleSetter(
324 Reflection.findMethodStatic(LaunchLug.class, "setLength", double.class)));
325 setters.put("LaunchLug:thickness", new DoubleSetter(
326 Reflection.findMethodStatic(LaunchLug.class, "setThickness", double.class)));
327 setters.put("LaunchLug:radialdirection", new DoubleSetter(
328 Reflection.findMethodStatic(LaunchLug.class, "setRadialDirection", double.class),
331 // InternalComponent - nothing
333 // StructuralComponent
334 setters.put("StructuralComponent:material", new MaterialSetter(
335 Reflection.findMethodStatic(StructuralComponent.class, "setMaterial", Material.class),
336 Material.Type.BULK));
339 setters.put("RingComponent:length", new DoubleSetter(
340 Reflection.findMethodStatic(RingComponent.class, "setLength", double.class)));
341 setters.put("RingComponent:radialposition", new DoubleSetter(
342 Reflection.findMethodStatic(RingComponent.class, "setRadialPosition", double.class)));
343 setters.put("RingComponent:radialdirection", new DoubleSetter(
344 Reflection.findMethodStatic(RingComponent.class, "setRadialDirection", double.class),
347 // ThicknessRingComponent - radius on separate components due to differing automatics
348 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
349 Reflection.findMethodStatic(ThicknessRingComponent.class, "setThickness", double.class)));
352 setters.put("EngineBlock:outerradius", new DoubleSetter(
353 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadius", double.class),
355 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
358 setters.put("TubeCoupler:outerradius", new DoubleSetter(
359 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadius", double.class),
361 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
364 setters.put("InnerTube:outerradius", new DoubleSetter(
365 Reflection.findMethodStatic(InnerTube.class, "setOuterRadius", double.class)));
366 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
367 setters.put("InnerTube:clusterscale", new DoubleSetter(
368 Reflection.findMethodStatic(InnerTube.class, "setClusterScale", double.class)));
369 setters.put("InnerTube:clusterrotation", new DoubleSetter(
370 Reflection.findMethodStatic(InnerTube.class, "setClusterRotation", double.class),
373 // RadiusRingComponent
376 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
377 Reflection.findMethodStatic(RadiusRingComponent.class, "setInnerRadius", double.class)));
378 setters.put("Bulkhead:outerradius", new DoubleSetter(
379 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadius", double.class),
381 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
384 setters.put("CenteringRing:innerradius", new DoubleSetter(
385 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadius", double.class),
387 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
388 setters.put("CenteringRing:outerradius", new DoubleSetter(
389 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadius", double.class),
391 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
395 setters.put("MassObject:packedlength", new DoubleSetter(
396 Reflection.findMethodStatic(MassObject.class, "setLength", double.class)));
397 setters.put("MassObject:packedradius", new DoubleSetter(
398 Reflection.findMethodStatic(MassObject.class, "setRadius", double.class)));
399 setters.put("MassObject:radialposition", new DoubleSetter(
400 Reflection.findMethodStatic(MassObject.class, "setRadialPosition", double.class)));
401 setters.put("MassObject:radialdirection", new DoubleSetter(
402 Reflection.findMethodStatic(MassObject.class, "setRadialDirection", double.class),
406 setters.put("MassComponent:mass", new DoubleSetter(
407 Reflection.findMethodStatic(MassComponent.class, "setComponentMass", double.class)));
410 setters.put("ShockCord:cordlength", new DoubleSetter(
411 Reflection.findMethodStatic(ShockCord.class, "setCordLength", double.class)));
412 setters.put("ShockCord:material", new MaterialSetter(
413 Reflection.findMethodStatic(ShockCord.class, "setMaterial", Material.class),
414 Material.Type.LINE));
417 setters.put("RecoveryDevice:cd", new DoubleSetter(
418 Reflection.findMethodStatic(RecoveryDevice.class, "setCD", double.class),
420 Reflection.findMethodStatic(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
421 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
422 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
423 RecoveryDevice.DeployEvent.class));
424 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
425 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployAltitude", double.class)));
426 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
427 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployDelay", double.class)));
428 setters.put("RecoveryDevice:material", new MaterialSetter(
429 Reflection.findMethodStatic(RecoveryDevice.class, "setMaterial", Material.class),
430 Material.Type.SURFACE));
433 setters.put("Parachute:diameter", new DoubleSetter(
434 Reflection.findMethodStatic(Parachute.class, "setDiameter", double.class)));
435 setters.put("Parachute:linecount", new IntSetter(
436 Reflection.findMethodStatic(Parachute.class, "setLineCount", int.class)));
437 setters.put("Parachute:linelength", new DoubleSetter(
438 Reflection.findMethodStatic(Parachute.class, "setLineLength", double.class)));
439 setters.put("Parachute:linematerial", new MaterialSetter(
440 Reflection.findMethodStatic(Parachute.class, "setLineMaterial", Material.class),
441 Material.Type.LINE));
444 setters.put("Streamer:striplength", new DoubleSetter(
445 Reflection.findMethodStatic(Streamer.class, "setStripLength", double.class)));
446 setters.put("Streamer:stripwidth", new DoubleSetter(
447 Reflection.findMethodStatic(Streamer.class, "setStripWidth", double.class)));
450 // <motorconfiguration> handled by separate handler
451 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
452 Reflection.findMethodStatic(Rocket.class, "setReferenceType", ReferenceType.class),
453 ReferenceType.class));
454 setters.put("Rocket:customreference", new DoubleSetter(
455 Reflection.findMethodStatic(Rocket.class, "setCustomReferenceLength", double.class)));
456 setters.put("Rocket:designer", new StringSetter(
457 Reflection.findMethodStatic(Rocket.class, "setDesigner", String.class)));
458 setters.put("Rocket:revision", new StringSetter(
459 Reflection.findMethodStatic(Rocket.class, "setRevision", String.class)));
464 * Search for a enum value that has the corresponding name as an XML value. The current
465 * conversion from enum name to XML value is to lowercase the name and strip out all
466 * underscore characters. This method returns a match to these criteria, or <code>null</code>
467 * if no such enum exists.
469 * @param <T> then enum type.
470 * @param name the XML value, null ok.
471 * @param enumClass the class of the enum.
472 * @return the found enum value, or <code>null</code>.
474 public static <T extends Enum<T>> Enum<T> findEnum(String name,
475 Class<? extends Enum<T>> enumClass) {
480 for (Enum<T> e: enumClass.getEnumConstants()) {
481 if (e.name().toLowerCase().replace("_", "").equals(name)) {
490 * Convert a string to a double including formatting specifications of the OpenRocket
491 * file format. This accepts all formatting that is valid for
492 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
494 * @param s the string to parse.
495 * @return the numerical value.
496 * @throws NumberFormatException the the string cannot be parsed.
498 public static double stringToDouble(String s) throws NumberFormatException {
500 throw new NumberFormatException("null string");
501 if (s.equalsIgnoreCase("NaN"))
503 if (s.equalsIgnoreCase("Inf"))
504 return Double.POSITIVE_INFINITY;
505 if (s.equalsIgnoreCase("-Inf"))
506 return Double.NEGATIVE_INFINITY;
507 return Double.parseDouble(s);
516 * The starting point of the handlers. Accepts a single <openrocket> element and hands
517 * the contents to be read by a OpenRocketContentsHandler.
519 class OpenRocketHandler extends ElementHandler {
520 private OpenRocketContentHandler handler = null;
523 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
524 * has not been read yet.
526 * @return the document read, or null.
528 public OpenRocketDocument getDocument() {
529 return handler.getDocument();
533 public ElementHandler openElement(String element, HashMap<String, String> attributes,
534 WarningSet warnings) {
536 // Check for unknown elements
537 if (!element.equals("openrocket")) {
538 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
542 // Check for first call
543 if (handler != null) {
544 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
549 // Check version number
550 String version = null;
551 String creator = attributes.remove("creator");
552 String docVersion = attributes.remove("version");
553 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
554 if (v.equals(docVersion)) {
559 if (version == null) {
560 String str = "Unsupported document version";
561 if (docVersion != null)
562 str += " " + docVersion;
563 if (creator != null && !creator.trim().equals(""))
564 str += " (written using '" + creator.trim() + "')";
565 str += ", attempting to read file anyway.";
569 handler = new OpenRocketContentHandler();
574 public void closeElement(String element, HashMap<String, String> attributes,
575 String content, WarningSet warnings) throws SAXException {
576 attributes.remove("version");
577 attributes.remove("creator");
578 super.closeElement(element, attributes, content, warnings);
586 * Handles the content of the <openrocket> tag.
588 class OpenRocketContentHandler extends ElementHandler {
589 private final OpenRocketDocument doc;
590 private final Rocket rocket;
592 private boolean rocketDefined = false;
593 private boolean simulationsDefined = false;
595 public OpenRocketContentHandler() {
596 this.rocket = new Rocket();
597 this.doc = new OpenRocketDocument(rocket);
601 public OpenRocketDocument getDocument() {
608 public ElementHandler openElement(String element, HashMap<String, String> attributes,
609 WarningSet warnings) {
611 if (element.equals("rocket")) {
614 .fromString("Multiple rocket designs within one document, "
615 + "ignoring later ones."));
618 rocketDefined = true;
619 return new ComponentParameterHandler(rocket);
622 if (element.equals("simulations")) {
623 if (simulationsDefined) {
625 .fromString("Multiple simulation definitions within one document, "
626 + "ignoring later ones."));
629 simulationsDefined = true;
630 return new SimulationsHandler(doc);
633 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
643 * A handler that creates components from the corresponding elements. The control of the
644 * contents is passed on to ComponentParameterHandler.
646 class ComponentHandler extends ElementHandler {
647 private final RocketComponent parent;
649 public ComponentHandler(RocketComponent parent) {
650 this.parent = parent;
654 public ElementHandler openElement(String element, HashMap<String, String> attributes,
655 WarningSet warnings) {
657 // Attempt to construct new component
658 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
660 if (constructor == null) {
661 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
667 c = constructor.newInstance();
668 } catch (InstantiationException e) {
669 throw new BugException("Error constructing component.", e);
670 } catch (IllegalAccessException e) {
671 throw new BugException("Error constructing component.", e);
672 } catch (InvocationTargetException e) {
673 throw Reflection.handleWrappedException(e);
678 return new ComponentParameterHandler(c);
684 * A handler that populates the parameters of a previously constructed rocket component.
685 * This uses the setters, or delegates the handling to another handler for specific
688 class ComponentParameterHandler extends ElementHandler {
689 private final RocketComponent component;
691 public ComponentParameterHandler(RocketComponent c) {
696 public ElementHandler openElement(String element, HashMap<String, String> attributes,
697 WarningSet warnings) {
699 // Check for specific elements that contain other elements
700 if (element.equals("subcomponents")) {
701 return new ComponentHandler(component);
703 if (element.equals("motormount")) {
704 if (!(component instanceof MotorMount)) {
705 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
708 return new MotorMountHandler((MotorMount)component);
710 if (element.equals("finpoints")) {
711 if (!(component instanceof FreeformFinSet)) {
712 warnings.add(Warning.fromString("Illegal component defined for fin points."));
715 return new FinSetPointHandler((FreeformFinSet)component);
717 if (element.equals("motorconfiguration")) {
718 if (!(component instanceof Rocket)) {
719 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
722 return new MotorConfigurationHandler((Rocket)component);
726 return PlainTextHandler.INSTANCE;
730 public void closeElement(String element, HashMap<String, String> attributes,
731 String content, WarningSet warnings) {
733 if (element.equals("subcomponents") || element.equals("motormount") ||
734 element.equals("finpoints") || element.equals("motorconfiguration")) {
738 // Search for the correct setter class
741 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
742 String setterKey = c.getSimpleName() + ":" + element;
743 Setter s = DocumentConfig.setters.get(setterKey);
746 System.out.println("Calling with key "+setterKey);
747 s.set(component, content, attributes, warnings);
750 if (DocumentConfig.setters.containsKey(setterKey)) {
751 // Key exists but is null -> invalid parameter
757 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
758 + component.getComponentName() + ", ignoring."));
765 * A handler that reads the <point> specifications within the freeformfinset's
766 * <finpoints> elements.
768 class FinSetPointHandler extends ElementHandler {
769 private final FreeformFinSet finset;
770 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
772 public FinSetPointHandler(FreeformFinSet finset) {
773 this.finset = finset;
777 public ElementHandler openElement(String element, HashMap<String, String> attributes,
778 WarningSet warnings) {
779 return PlainTextHandler.INSTANCE;
784 public void closeElement(String element, HashMap<String, String> attributes,
785 String content, WarningSet warnings) throws SAXException {
787 String strx = attributes.remove("x");
788 String stry = attributes.remove("y");
789 if (strx == null || stry == null) {
790 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
794 double x = Double.parseDouble(strx);
795 double y = Double.parseDouble(stry);
796 coordinates.add(new Coordinate(x,y));
797 } catch (NumberFormatException e) {
798 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
802 super.closeElement(element, attributes, content, warnings);
806 public void endHandler(String element, HashMap<String, String> attributes,
807 String content, WarningSet warnings) {
809 finset.setPoints(coordinates.toArray(new Coordinate[0]));
810 } catch (IllegalFinPointException e) {
811 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
817 class MotorMountHandler extends ElementHandler {
818 private final MotorMount mount;
819 private MotorHandler motorHandler;
821 public MotorMountHandler(MotorMount mount) {
823 mount.setMotorMount(true);
827 public ElementHandler openElement(String element, HashMap<String, String> attributes,
828 WarningSet warnings) {
830 if (element.equals("motor")) {
831 motorHandler = new MotorHandler();
835 if (element.equals("ignitionevent") ||
836 element.equals("ignitiondelay") ||
837 element.equals("overhang")) {
838 return PlainTextHandler.INSTANCE;
841 warnings.add(Warning.fromString("Unknown element '"+element+"' encountered, ignoring."));
848 public void closeElement(String element, HashMap<String, String> attributes,
849 String content, WarningSet warnings) throws SAXException {
851 if (element.equals("motor")) {
852 String id = attributes.get("configid");
853 if (id == null || id.equals("")) {
854 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
858 Motor motor = motorHandler.getMotor(warnings);
859 mount.setMotor(id, motor);
860 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
864 if (element.equals("ignitionevent")) {
865 MotorMount.IgnitionEvent event = null;
866 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
867 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
873 warnings.add(Warning.fromString("Unknown ignition event type '"+content+"', ignoring."));
876 mount.setIgnitionEvent(event);
880 if (element.equals("ignitiondelay")) {
883 d = Double.parseDouble(content);
884 } catch (NumberFormatException nfe) {
885 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
888 mount.setIgnitionDelay(d);
892 if (element.equals("overhang")) {
895 d = Double.parseDouble(content);
896 } catch (NumberFormatException nfe) {
897 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
900 mount.setMotorOverhang(d);
904 super.closeElement(element, attributes, content, warnings);
911 class MotorConfigurationHandler extends ElementHandler {
912 private final Rocket rocket;
913 private String name = null;
914 private boolean inNameElement = false;
916 public MotorConfigurationHandler(Rocket rocket) {
917 this.rocket = rocket;
921 public ElementHandler openElement(String element, HashMap<String, String> attributes,
922 WarningSet warnings) {
924 if (inNameElement || !element.equals("name")) {
925 warnings.add(Warning.FILE_INVALID_PARAMETER);
928 inNameElement = true;
930 return PlainTextHandler.INSTANCE;
934 public void closeElement(String element, HashMap<String, String> attributes,
935 String content, WarningSet warnings) {
940 public void endHandler(String element, HashMap<String, String> attributes,
941 String content, WarningSet warnings) throws SAXException {
943 String configid = attributes.remove("configid");
944 if (configid == null || configid.equals("")) {
945 warnings.add(Warning.FILE_INVALID_PARAMETER);
949 if (!rocket.addMotorConfigurationID(configid)) {
950 warnings.add("Duplicate motor configuration ID used.");
954 if (name != null && name.trim().length() > 0) {
955 rocket.setMotorConfigurationName(configid, name);
958 if ("true".equals(attributes.remove("default"))) {
959 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
962 super.closeElement(element, attributes, content, warnings);
967 class MotorHandler extends ElementHandler {
968 private Motor.Type type = null;
969 private String manufacturer = null;
970 private String designation = null;
971 private double diameter = Double.NaN;
972 private double length = Double.NaN;
973 private double delay = Double.NaN;
976 public ElementHandler openElement(String element, HashMap<String, String> attributes,
977 WarningSet warnings) {
978 return PlainTextHandler.INSTANCE;
983 * Return the motor to use, or null.
985 public Motor getMotor(WarningSet warnings) {
986 if (designation == null) {
987 warnings.add(Warning.fromString("No motor specified, ignoring."));
990 Motor[] motors = Databases.findMotors(type, manufacturer, designation, diameter, length);
991 if (motors.length == 0) {
992 String str = "No motor with designation '"+designation+"'";
993 if (manufacturer != null)
994 str += " for manufacturer '" + manufacturer + "'";
995 warnings.add(Warning.fromString(str + " found."));
998 if (motors.length > 1) {
999 String str = "Multiple motors with designation '"+designation+"'";
1000 if (manufacturer != null)
1001 str += " for manufacturer '" + manufacturer + "'";
1002 warnings.add(Warning.fromString(str + " found, one chosen arbitrarily."));
1009 * Return the delay to use for the motor.
1011 public double getDelay(WarningSet warnings) {
1012 if (Double.isNaN(delay)) {
1013 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1014 return Motor.PLUGGED;
1021 public void closeElement(String element, HashMap<String, String> attributes,
1022 String content, WarningSet warnings) throws SAXException {
1024 content = content.trim();
1026 if (element.equals("type")) {
1030 for (Motor.Type t: Motor.Type.values()) {
1031 if (t.name().toLowerCase().equals(content)) {
1037 warnings.add(Warning.fromString("Unknown motor type '"+content+"', ignoring."));
1040 } else if (element.equals("manufacturer")) {
1043 manufacturer = content;
1045 } else if (element.equals("designation")) {
1048 designation = content;
1050 } else if (element.equals("diameter")) {
1053 diameter = Double.NaN;
1055 diameter = Double.parseDouble(content);
1056 } catch (NumberFormatException e) {
1059 if (Double.isNaN(diameter)) {
1060 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1063 } else if (element.equals("length")) {
1066 length = Double.NaN;
1068 length = Double.parseDouble(content);
1069 } catch (NumberFormatException ignore) { }
1071 if (Double.isNaN(length)) {
1072 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1075 } else if (element.equals("delay")) {
1079 if (content.equals("none")) {
1080 delay = Motor.PLUGGED;
1083 delay = Double.parseDouble(content);
1084 } catch (NumberFormatException ignore) { }
1086 if (Double.isNaN(delay)) {
1087 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1093 super.closeElement(element, attributes, content, warnings);
1101 class SimulationsHandler extends ElementHandler {
1102 private final OpenRocketDocument doc;
1103 private SingleSimulationHandler handler;
1105 public SimulationsHandler(OpenRocketDocument doc) {
1110 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1111 WarningSet warnings) {
1113 if (!element.equals("simulation")) {
1114 warnings.add("Unknown element '"+element+"', ignoring.");
1118 handler = new SingleSimulationHandler(doc);
1123 public void closeElement(String element, HashMap<String, String> attributes,
1124 String content, WarningSet warnings) throws SAXException {
1125 attributes.remove("status");
1126 super.closeElement(element, attributes, content, warnings);
1132 class SingleSimulationHandler extends ElementHandler {
1134 private final OpenRocketDocument doc;
1136 private String name;
1138 private SimulationConditionsHandler conditionHandler;
1139 private FlightDataHandler dataHandler;
1141 private final List<String> listeners = new ArrayList<String>();
1143 public SingleSimulationHandler(OpenRocketDocument doc) {
1150 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1151 WarningSet warnings) {
1153 if (element.equals("name") || element.equals("simulator") ||
1154 element.equals("calculator") || element.equals("listener")) {
1155 return PlainTextHandler.INSTANCE;
1156 } else if (element.equals("conditions")) {
1157 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1158 return conditionHandler;
1159 } else if (element.equals("flightdata")) {
1160 dataHandler = new FlightDataHandler();
1163 warnings.add("Unknown element '"+element+"', ignoring.");
1169 public void closeElement(String element, HashMap<String, String> attributes,
1170 String content, WarningSet warnings) {
1172 if (element.equals("name")) {
1174 } else if (element.equals("simulator")) {
1175 if (!content.trim().equals("RK4Simulator")) {
1176 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1178 } else if (element.equals("calculator")) {
1179 if (!content.trim().equals("BarrowmanCalculator")) {
1180 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1182 } else if (element.equals("listener") && content.trim().length() > 0) {
1183 listeners.add(content.trim());
1189 public void endHandler(String element, HashMap<String, String> attributes,
1190 String content, WarningSet warnings) {
1192 String s = attributes.get("status");
1193 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1194 if (status == null) {
1195 warnings.add("Simulation status unknown, assuming outdated.");
1196 status = Simulation.Status.OUTDATED;
1199 SimulationConditions conditions;
1200 if (conditionHandler != null) {
1201 conditions = conditionHandler.getConditions();
1203 warnings.add("Simulation conditions not defined, using defaults.");
1204 conditions = new SimulationConditions(doc.getRocket());
1208 name = "Simulation";
1211 if (dataHandler == null)
1214 data = dataHandler.getFlightData();
1216 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1217 conditions, listeners, data);
1219 doc.addSimulation(simulation);
1225 class SimulationConditionsHandler extends ElementHandler {
1226 private SimulationConditions conditions;
1227 private AtmosphereHandler atmosphereHandler;
1229 public SimulationConditionsHandler(Rocket rocket) {
1230 conditions = new SimulationConditions(rocket);
1233 public SimulationConditions getConditions() {
1238 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1239 WarningSet warnings) {
1240 if (element.equals("atmosphere")) {
1241 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1242 return atmosphereHandler;
1244 return PlainTextHandler.INSTANCE;
1248 public void closeElement(String element, HashMap<String, String> attributes,
1249 String content, WarningSet warnings) {
1251 double d = Double.NaN;
1253 d = Double.parseDouble(content);
1254 } catch (NumberFormatException ignore) { }
1257 if (element.equals("configid")) {
1258 if (content.equals("")) {
1259 conditions.setMotorConfigurationID(null);
1261 conditions.setMotorConfigurationID(content);
1263 } else if (element.equals("launchrodlength")) {
1264 if (Double.isNaN(d)) {
1265 warnings.add("Illegal launch rod length defined, ignoring.");
1267 conditions.setLaunchRodLength(d);
1269 } else if (element.equals("launchrodangle")) {
1270 if (Double.isNaN(d)) {
1271 warnings.add("Illegal launch rod angle defined, ignoring.");
1273 conditions.setLaunchRodAngle(d*Math.PI/180);
1275 } else if (element.equals("launchroddirection")) {
1276 if (Double.isNaN(d)) {
1277 warnings.add("Illegal launch rod direction defined, ignoring.");
1279 conditions.setLaunchRodDirection(d*Math.PI/180);
1281 } else if (element.equals("windaverage")) {
1282 if (Double.isNaN(d)) {
1283 warnings.add("Illegal average windspeed defined, ignoring.");
1285 conditions.setWindSpeedAverage(d);
1287 } else if (element.equals("windturbulence")) {
1288 if (Double.isNaN(d)) {
1289 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1291 conditions.setWindTurbulenceIntensity(d);
1293 } else if (element.equals("launchaltitude")) {
1294 if (Double.isNaN(d)) {
1295 warnings.add("Illegal launch altitude defined, ignoring.");
1297 conditions.setLaunchAltitude(d);
1299 } else if (element.equals("launchlatitude")) {
1300 if (Double.isNaN(d)) {
1301 warnings.add("Illegal launch latitude defined, ignoring.");
1303 conditions.setLaunchLatitude(d);
1305 } else if (element.equals("atmosphere")) {
1306 atmosphereHandler.storeSettings(conditions, warnings);
1307 } else if (element.equals("timestep")) {
1308 if (Double.isNaN(d)) {
1309 warnings.add("Illegal time step defined, ignoring.");
1311 conditions.setTimeStep(d);
1318 class AtmosphereHandler extends ElementHandler {
1319 private final String model;
1320 private double temperature = Double.NaN;
1321 private double pressure = Double.NaN;
1323 public AtmosphereHandler(String model) {
1328 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1329 WarningSet warnings) {
1330 return PlainTextHandler.INSTANCE;
1334 public void closeElement(String element, HashMap<String, String> attributes,
1335 String content, WarningSet warnings) throws SAXException {
1337 double d = Double.NaN;
1339 d = Double.parseDouble(content);
1340 } catch (NumberFormatException ignore) { }
1342 if (element.equals("basetemperature")) {
1343 if (Double.isNaN(d)) {
1344 warnings.add("Illegal base temperature specified, ignoring.");
1347 } else if (element.equals("basepressure")) {
1348 if (Double.isNaN(d)) {
1349 warnings.add("Illegal base pressure specified, ignoring.");
1353 super.closeElement(element, attributes, content, warnings);
1358 public void storeSettings(SimulationConditions cond, WarningSet warnings) {
1359 if (!Double.isNaN(pressure)) {
1360 cond.setLaunchPressure(pressure);
1362 if (!Double.isNaN(temperature)) {
1363 cond.setLaunchTemperature(temperature);
1366 if ("isa".equals(model)) {
1367 cond.setISAAtmosphere(true);
1368 } else if ("extendedisa".equals(model)){
1369 cond.setISAAtmosphere(false);
1371 cond.setISAAtmosphere(true);
1372 warnings.add("Unknown atmospheric model, using ISA.");
1379 class FlightDataHandler extends ElementHandler {
1381 private FlightDataBranchHandler dataHandler;
1382 private WarningSet warningSet = new WarningSet();
1383 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1385 private FlightData data;
1387 public FlightData getFlightData() {
1392 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1393 WarningSet warnings) {
1395 if (element.equals("warning")) {
1396 return PlainTextHandler.INSTANCE;
1398 if (element.equals("databranch")) {
1399 if (attributes.get("name") == null || attributes.get("types")==null) {
1400 warnings.add("Illegal flight data definition, ignoring.");
1403 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1404 attributes.get("types"));
1408 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1414 public void closeElement(String element, HashMap<String, String> attributes,
1415 String content, WarningSet warnings) {
1417 if (element.equals("databranch")) {
1418 FlightDataBranch branch = dataHandler.getBranch();
1419 if (branch.getLength() > 0) {
1420 branches.add(branch);
1422 } else if (element.equals("warning")) {
1423 warningSet.add(Warning.fromString(content));
1429 public void endHandler(String element, HashMap<String, String> attributes,
1430 String content, WarningSet warnings) {
1432 if (branches.size() > 0) {
1433 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1435 double maxAltitude = Double.NaN;
1436 double maxVelocity = Double.NaN;
1437 double maxAcceleration = Double.NaN;
1438 double maxMach = Double.NaN;
1439 double timeToApogee = Double.NaN;
1440 double flightTime = Double.NaN;
1441 double groundHitVelocity = Double.NaN;
1444 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1445 } catch (NumberFormatException ignore) { }
1447 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1448 } catch (NumberFormatException ignore) { }
1450 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1451 } catch (NumberFormatException ignore) { }
1453 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1454 } catch (NumberFormatException ignore) { }
1456 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1457 } catch (NumberFormatException ignore) { }
1459 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1460 } catch (NumberFormatException ignore) { }
1463 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1464 } catch (NumberFormatException ignore) { }
1466 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1467 timeToApogee, flightTime, groundHitVelocity);
1470 data.getWarningSet().addAll(warningSet);
1477 class FlightDataBranchHandler extends ElementHandler {
1478 private final FlightDataBranch.Type[] types;
1479 private final FlightDataBranch branch;
1481 public FlightDataBranchHandler(String name, String typeList) {
1482 String[] split = typeList.split(",");
1483 types = new FlightDataBranch.Type[split.length];
1484 for (int i=0; i < split.length; i++) {
1485 types[i] = FlightDataBranch.getType(split[i], UnitGroup.UNITS_NONE);
1488 // TODO: LOW: May throw an IllegalArgumentException
1489 branch = new FlightDataBranch(name, types);
1492 public FlightDataBranch getBranch() {
1498 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1499 WarningSet warnings) {
1501 if (element.equals("datapoint"))
1502 return PlainTextHandler.INSTANCE;
1503 if (element.equals("event"))
1504 return PlainTextHandler.INSTANCE;
1506 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1512 public void closeElement(String element, HashMap<String, String> attributes,
1513 String content, WarningSet warnings) {
1515 if (element.equals("event")) {
1517 FlightEvent.Type type;
1520 time = DocumentConfig.stringToDouble(attributes.get("time"));
1521 } catch (NumberFormatException e) {
1522 warnings.add("Illegal event specification, ignoring.");
1526 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1528 warnings.add("Illegal event specification, ignoring.");
1532 branch.addEvent(time, new FlightEvent(type, time));
1536 if (!element.equals("datapoint")) {
1537 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1541 // element == "datapoint"
1544 // Check line format
1545 String[] split = content.split(",");
1546 if (split.length != types.length) {
1547 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1551 // Parse the doubles
1552 double[] values = new double[split.length];
1553 for (int i=0; i < values.length; i++) {
1555 values[i] = DocumentConfig.stringToDouble(split[i]);
1556 } catch (NumberFormatException e) {
1557 warnings.add("Data point format error, ignoring point.");
1562 // Add point to branch
1564 for (int i=0; i < types.length; i++) {
1565 branch.setValue(types[i], values[i]);
1575 ///////////////// Setters implementation
1581 * Set the specified value to the given component.
1583 * @param component the component to which to set.
1584 * @param value the value within the element.
1585 * @param attributes attributes for the element.
1586 * @param warnings the warning set to use.
1588 public void set(RocketComponent component, String value,
1589 HashMap<String, String> attributes, WarningSet warnings);
1593 //// StringSetter - sets the value to the contained String
1594 class StringSetter implements Setter {
1595 private final Reflection.Method setMethod;
1597 public StringSetter(Reflection.Method set) {
1601 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1602 WarningSet warnings) {
1603 setMethod.invoke(c, s);
1607 //// IntSetter - set an integer value
1608 class IntSetter implements Setter {
1609 private final Reflection.Method setMethod;
1611 public IntSetter(Reflection.Method set) {
1615 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1616 WarningSet warnings) {
1618 int n = Integer.parseInt(s);
1619 setMethod.invoke(c, n);
1620 } catch (NumberFormatException e) {
1621 warnings.add(Warning.FILE_INVALID_PARAMETER);
1627 //// BooleanSetter - set a boolean value
1628 class BooleanSetter implements Setter {
1629 private final Reflection.Method setMethod;
1631 public BooleanSetter(Reflection.Method set) {
1635 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1636 WarningSet warnings) {
1639 if (s.equalsIgnoreCase("true")) {
1640 setMethod.invoke(c, true);
1641 } else if (s.equalsIgnoreCase("false")) {
1642 setMethod.invoke(c, false);
1644 warnings.add(Warning.FILE_INVALID_PARAMETER);
1651 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1652 //// calls a setXXX(boolean) method.
1653 class DoubleSetter implements Setter {
1654 private final Reflection.Method setMethod;
1655 private final String specialString;
1656 private final Reflection.Method specialMethod;
1657 private final double multiplier;
1660 * Set only the double value.
1661 * @param set set method for the double value.
1663 public DoubleSetter(Reflection.Method set) {
1664 this.setMethod = set;
1665 this.specialString = null;
1666 this.specialMethod = null;
1667 this.multiplier = 1.0;
1671 * Multiply with the given multiplier and set the double value.
1672 * @param set set method for the double value.
1673 * @param mul multiplier.
1675 public DoubleSetter(Reflection.Method set, double mul) {
1676 this.setMethod = set;
1677 this.specialString = null;
1678 this.specialMethod = null;
1679 this.multiplier = mul;
1683 * Set the double value, or if the value equals the special string, use the
1684 * special setter and set it to true.
1686 * @param set double setter.
1687 * @param special special string
1688 * @param specialMethod boolean setter.
1690 public DoubleSetter(Reflection.Method set, String special,
1691 Reflection.Method specialMethod) {
1692 this.setMethod = set;
1693 this.specialString = special;
1694 this.specialMethod = specialMethod;
1695 this.multiplier = 1.0;
1699 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1700 WarningSet warnings) {
1704 // Check for special case
1705 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1706 specialMethod.invoke(c, true);
1712 double d = Double.parseDouble(s);
1713 setMethod.invoke(c, d * multiplier);
1714 } catch (NumberFormatException e) {
1715 warnings.add(Warning.FILE_INVALID_PARAMETER);
1721 class OverrideSetter implements Setter {
1722 private final Reflection.Method setMethod;
1723 private final Reflection.Method enabledMethod;
1725 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1726 this.setMethod = set;
1727 this.enabledMethod = enabledMethod;
1730 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1731 WarningSet warnings) {
1734 double d = Double.parseDouble(s);
1735 setMethod.invoke(c, d);
1736 enabledMethod.invoke(c, true);
1737 } catch (NumberFormatException e) {
1738 warnings.add(Warning.FILE_INVALID_PARAMETER);
1743 //// EnumSetter - sets a generic enum type
1744 class EnumSetter<T extends Enum<T>> implements Setter {
1745 private final Reflection.Method setter;
1746 private final Class<T> enumClass;
1748 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1750 this.enumClass = enumClass;
1754 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1755 WarningSet warnings) {
1757 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1758 if (setEnum == null) {
1759 warnings.add(Warning.FILE_INVALID_PARAMETER);
1763 setter.invoke(c, setEnum);
1768 //// ColorSetter - sets a Color value
1769 class ColorSetter implements Setter {
1770 private final Reflection.Method setMethod;
1772 public ColorSetter(Reflection.Method set) {
1776 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1777 WarningSet warnings) {
1779 String red = attributes.get("red");
1780 String green = attributes.get("green");
1781 String blue = attributes.get("blue");
1783 if (red == null || green == null || blue == null) {
1784 warnings.add(Warning.FILE_INVALID_PARAMETER);
1790 r = Integer.parseInt(red);
1791 g = Integer.parseInt(green);
1792 b = Integer.parseInt(blue);
1793 } catch (NumberFormatException e) {
1794 warnings.add(Warning.FILE_INVALID_PARAMETER);
1798 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1799 warnings.add(Warning.FILE_INVALID_PARAMETER);
1803 Color color = new Color(r, g, b);
1804 setMethod.invoke(c, color);
1806 if (!s.trim().equals("")) {
1807 warnings.add(Warning.FILE_INVALID_PARAMETER);
1814 class MaterialSetter implements Setter {
1815 private final Reflection.Method setMethod;
1816 private final Material.Type type;
1818 public MaterialSetter(Reflection.Method set, Material.Type type) {
1819 this.setMethod = set;
1823 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1824 WarningSet warnings) {
1830 if (name.equals("")) {
1831 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1838 str = attributes.remove("density");
1840 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1844 density = Double.parseDouble(str);
1845 } catch (NumberFormatException e) {
1846 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1851 // double thickness = 0;
1852 // str = attributes.remove("thickness");
1855 // thickness = Double.parseDouble(str);
1856 // } catch (NumberFormatException e){
1857 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1861 // Check type if specified
1862 str = attributes.remove("type");
1863 if (str != null && !type.name().toLowerCase().equals(str)) {
1864 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1868 mat = Databases.findMaterial(type, name, density, false);
1870 setMethod.invoke(c, mat);
1877 class PositionSetter implements Setter {
1879 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1880 WarningSet warnings) {
1882 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1883 RocketComponent.Position.class);
1885 warnings.add(Warning.FILE_INVALID_PARAMETER);
1891 pos = Double.parseDouble(value);
1892 } catch (NumberFormatException e) {
1893 warnings.add(Warning.FILE_INVALID_PARAMETER);
1897 if (c instanceof FinSet) {
1898 ((FinSet)c).setRelativePosition(type);
1899 c.setPositionValue(pos);
1900 } else if (c instanceof LaunchLug) {
1901 ((LaunchLug)c).setRelativePosition(type);
1902 c.setPositionValue(pos);
1903 } else if (c instanceof InternalComponent) {
1904 ((InternalComponent)c).setRelativePosition(type);
1905 c.setPositionValue(pos);
1907 warnings.add(Warning.FILE_INVALID_PARAMETER);
1914 class FinTabPositionSetter extends DoubleSetter {
1916 public FinTabPositionSetter() {
1917 super(Reflection.findMethodStatic(FinSet.class, "setTabShift", double.class));
1921 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1922 WarningSet warnings) {
1924 if (!(c instanceof FinSet)) {
1925 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
1928 String relative = attributes.get("relativeto");
1929 FinSet.TabRelativePosition position =
1930 (TabRelativePosition) DocumentConfig.findEnum(relative,
1931 FinSet.TabRelativePosition.class);
1933 if (position != null) {
1935 ((FinSet)c).setTabRelativePosition(position);
1938 if (relative == null) {
1939 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
1941 warnings.add("Illegal attribute value '" + relative + "' encountered.");
1945 super.set(c, s, attributes, warnings);
1952 class ClusterConfigurationSetter implements Setter {
1954 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
1955 WarningSet warnings) {
1957 if (!(component instanceof Clusterable)) {
1958 warnings.add("Illegal component defined as cluster.");
1962 ClusterConfiguration config = null;
1963 for (ClusterConfiguration c: ClusterConfiguration.CONFIGURATIONS) {
1964 if (c.getXMLName().equals(value)) {
1970 if (config == null) {
1971 warnings.add("Illegal cluster configuration specified.");
1975 ((Clusterable)component).setClusterConfiguration(config);