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.logging.LogHelper;
25 import net.sf.openrocket.material.Material;
26 import net.sf.openrocket.motor.Motor;
27 import net.sf.openrocket.motor.MotorDigest;
28 import net.sf.openrocket.motor.ThrustCurveMotor;
29 import net.sf.openrocket.rocketcomponent.BodyComponent;
30 import net.sf.openrocket.rocketcomponent.BodyTube;
31 import net.sf.openrocket.rocketcomponent.Bulkhead;
32 import net.sf.openrocket.rocketcomponent.CenteringRing;
33 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
34 import net.sf.openrocket.rocketcomponent.Clusterable;
35 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
36 import net.sf.openrocket.rocketcomponent.EngineBlock;
37 import net.sf.openrocket.rocketcomponent.ExternalComponent;
38 import net.sf.openrocket.rocketcomponent.FinSet;
39 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
40 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
41 import net.sf.openrocket.rocketcomponent.InnerTube;
42 import net.sf.openrocket.rocketcomponent.InternalComponent;
43 import net.sf.openrocket.rocketcomponent.LaunchLug;
44 import net.sf.openrocket.rocketcomponent.MassComponent;
45 import net.sf.openrocket.rocketcomponent.MassObject;
46 import net.sf.openrocket.rocketcomponent.MotorMount;
47 import net.sf.openrocket.rocketcomponent.NoseCone;
48 import net.sf.openrocket.rocketcomponent.Parachute;
49 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
50 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
51 import net.sf.openrocket.rocketcomponent.ReferenceType;
52 import net.sf.openrocket.rocketcomponent.RingComponent;
53 import net.sf.openrocket.rocketcomponent.Rocket;
54 import net.sf.openrocket.rocketcomponent.RocketComponent;
55 import net.sf.openrocket.rocketcomponent.ShockCord;
56 import net.sf.openrocket.rocketcomponent.Stage;
57 import net.sf.openrocket.rocketcomponent.Streamer;
58 import net.sf.openrocket.rocketcomponent.StructuralComponent;
59 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
60 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
61 import net.sf.openrocket.rocketcomponent.Transition;
62 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
63 import net.sf.openrocket.rocketcomponent.TubeCoupler;
64 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
65 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
66 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
67 import net.sf.openrocket.simulation.FlightData;
68 import net.sf.openrocket.simulation.FlightDataBranch;
69 import net.sf.openrocket.simulation.FlightDataType;
70 import net.sf.openrocket.simulation.FlightEvent;
71 import net.sf.openrocket.simulation.GUISimulationConditions;
72 import net.sf.openrocket.simulation.FlightEvent.Type;
73 import net.sf.openrocket.startup.Application;
74 import net.sf.openrocket.unit.UnitGroup;
75 import net.sf.openrocket.util.BugException;
76 import net.sf.openrocket.util.Coordinate;
77 import net.sf.openrocket.util.LineStyle;
78 import net.sf.openrocket.util.Reflection;
80 import org.xml.sax.InputSource;
81 import org.xml.sax.SAXException;
85 * Class that loads a rocket definition from an OpenRocket rocket file.
87 * This class uses SAX to read the XML file format. The
88 * {@link #loadFromStream(InputStream)} method simply sets the system up and
89 * starts the parsing, while the actual logic is in the private inner class
90 * <code>OpenRocketHandler</code>.
92 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
94 public class OpenRocketLoader extends RocketLoader {
95 private static final LogHelper log = Application.getLogger();
99 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
101 log.info("Loading .ork file");
103 InputSource xmlSource = new InputSource(source);
104 OpenRocketHandler handler = new OpenRocketHandler();
108 SimpleSAX.readXML(xmlSource, handler, warnings);
109 } catch (SAXException e) {
110 log.warn("Malformed XML in input");
111 throw new RocketLoadException("Malformed XML in input.", e);
115 OpenRocketDocument doc = handler.getDocument();
116 doc.getDefaultConfiguration().setAllStages();
118 // Deduce suitable time skip
119 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
120 for (Simulation s : doc.getSimulations()) {
121 if (s.getStatus() == Simulation.Status.EXTERNAL ||
122 s.getStatus() == Simulation.Status.NOT_SIMULATED)
124 if (s.getSimulatedData() == null)
126 if (s.getSimulatedData().getBranchCount() == 0)
128 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
131 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
135 double previousTime = Double.NaN;
136 for (double time : list) {
137 if (time - previousTime < timeSkip)
138 timeSkip = time - previousTime;
143 timeSkip = Math.rint(timeSkip * 100) / 100;
145 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
146 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
147 doc.getDefaultStorageOptions().setExplicitlySet(false);
150 log.info("Loading done");
158 class DocumentConfig {
160 /* Remember to update OpenRocketSaver as well! */
161 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0", "1.1", "1.2" };
164 //////// Component constructors
165 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
168 // External components
169 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
170 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
171 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
172 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
173 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
174 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
175 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
177 // Internal components
178 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
179 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
180 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
181 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
182 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
184 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
185 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
186 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
187 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
190 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
192 } catch (NoSuchMethodException e) {
193 throw new BugException(
194 "Error in constructing the 'constructors' HashMap.");
199 //////// Parameter setters
201 * The keys are of the form Class:param, where Class is the class name and param
202 * the element name. Setters are searched for in descending class order.
203 * A setter of null means setting the parameter is not allowed.
205 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
208 setters.put("RocketComponent:name", new StringSetter(
209 Reflection.findMethodStatic(RocketComponent.class, "setName", String.class)));
210 setters.put("RocketComponent:color", new ColorSetter(
211 Reflection.findMethodStatic(RocketComponent.class, "setColor", Color.class)));
212 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
213 Reflection.findMethodStatic(RocketComponent.class, "setLineStyle", LineStyle.class),
215 setters.put("RocketComponent:position", new PositionSetter());
216 setters.put("RocketComponent:overridemass", new OverrideSetter(
217 Reflection.findMethodStatic(RocketComponent.class, "setOverrideMass", double.class),
218 Reflection.findMethodStatic(RocketComponent.class, "setMassOverridden", boolean.class)));
219 setters.put("RocketComponent:overridecg", new OverrideSetter(
220 Reflection.findMethodStatic(RocketComponent.class, "setOverrideCGX", double.class),
221 Reflection.findMethodStatic(RocketComponent.class, "setCGOverridden", boolean.class)));
222 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
223 Reflection.findMethodStatic(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
224 setters.put("RocketComponent:comment", new StringSetter(
225 Reflection.findMethodStatic(RocketComponent.class, "setComment", String.class)));
228 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
229 Reflection.findMethodStatic(ExternalComponent.class, "setFinish", Finish.class),
231 setters.put("ExternalComponent:material", new MaterialSetter(
232 Reflection.findMethodStatic(ExternalComponent.class, "setMaterial", Material.class),
233 Material.Type.BULK));
236 setters.put("BodyComponent:length", new DoubleSetter(
237 Reflection.findMethodStatic(BodyComponent.class, "setLength", double.class)));
239 // SymmetricComponent
240 setters.put("SymmetricComponent:thickness", new DoubleSetter(
241 Reflection.findMethodStatic(SymmetricComponent.class, "setThickness", double.class),
243 Reflection.findMethodStatic(SymmetricComponent.class, "setFilled", boolean.class)));
246 setters.put("BodyTube:radius", new DoubleSetter(
247 Reflection.findMethodStatic(BodyTube.class, "setRadius", double.class),
249 Reflection.findMethodStatic(BodyTube.class, "setRadiusAutomatic", boolean.class)));
252 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
253 Reflection.findMethodStatic(Transition.class, "setType", Transition.Shape.class),
254 Transition.Shape.class));
255 setters.put("Transition:shapeclipped", new BooleanSetter(
256 Reflection.findMethodStatic(Transition.class, "setClipped", boolean.class)));
257 setters.put("Transition:shapeparameter", new DoubleSetter(
258 Reflection.findMethodStatic(Transition.class, "setShapeParameter", double.class)));
260 setters.put("Transition:foreradius", new DoubleSetter(
261 Reflection.findMethodStatic(Transition.class, "setForeRadius", double.class),
263 Reflection.findMethodStatic(Transition.class, "setForeRadiusAutomatic", boolean.class)));
264 setters.put("Transition:aftradius", new DoubleSetter(
265 Reflection.findMethodStatic(Transition.class, "setAftRadius", double.class),
267 Reflection.findMethodStatic(Transition.class, "setAftRadiusAutomatic", boolean.class)));
269 setters.put("Transition:foreshoulderradius", new DoubleSetter(
270 Reflection.findMethodStatic(Transition.class, "setForeShoulderRadius", double.class)));
271 setters.put("Transition:foreshoulderlength", new DoubleSetter(
272 Reflection.findMethodStatic(Transition.class, "setForeShoulderLength", double.class)));
273 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
274 Reflection.findMethodStatic(Transition.class, "setForeShoulderThickness", double.class)));
275 setters.put("Transition:foreshouldercapped", new BooleanSetter(
276 Reflection.findMethodStatic(Transition.class, "setForeShoulderCapped", boolean.class)));
278 setters.put("Transition:aftshoulderradius", new DoubleSetter(
279 Reflection.findMethodStatic(Transition.class, "setAftShoulderRadius", double.class)));
280 setters.put("Transition:aftshoulderlength", new DoubleSetter(
281 Reflection.findMethodStatic(Transition.class, "setAftShoulderLength", double.class)));
282 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
283 Reflection.findMethodStatic(Transition.class, "setAftShoulderThickness", double.class)));
284 setters.put("Transition:aftshouldercapped", new BooleanSetter(
285 Reflection.findMethodStatic(Transition.class, "setAftShoulderCapped", boolean.class)));
287 // NoseCone - disable disallowed elements
288 setters.put("NoseCone:foreradius", null);
289 setters.put("NoseCone:foreshoulderradius", null);
290 setters.put("NoseCone:foreshoulderlength", null);
291 setters.put("NoseCone:foreshoulderthickness", null);
292 setters.put("NoseCone:foreshouldercapped", null);
295 setters.put("FinSet:fincount", new IntSetter(
296 Reflection.findMethodStatic(FinSet.class, "setFinCount", int.class)));
297 setters.put("FinSet:rotation", new DoubleSetter(
298 Reflection.findMethodStatic(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
299 setters.put("FinSet:thickness", new DoubleSetter(
300 Reflection.findMethodStatic(FinSet.class, "setThickness", double.class)));
301 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
302 Reflection.findMethodStatic(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
303 FinSet.CrossSection.class));
304 setters.put("FinSet:cant", new DoubleSetter(
305 Reflection.findMethodStatic(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
306 setters.put("FinSet:tabheight", new DoubleSetter(
307 Reflection.findMethodStatic(FinSet.class, "setTabHeight", double.class)));
308 setters.put("FinSet:tablength", new DoubleSetter(
309 Reflection.findMethodStatic(FinSet.class, "setTabLength", double.class)));
310 setters.put("FinSet:tabposition", new FinTabPositionSetter());
313 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
314 Reflection.findMethodStatic(TrapezoidFinSet.class, "setRootChord", double.class)));
315 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
316 Reflection.findMethodStatic(TrapezoidFinSet.class, "setTipChord", double.class)));
317 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
318 Reflection.findMethodStatic(TrapezoidFinSet.class, "setSweep", double.class)));
319 setters.put("TrapezoidFinSet:height", new DoubleSetter(
320 Reflection.findMethodStatic(TrapezoidFinSet.class, "setHeight", double.class)));
323 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
324 Reflection.findMethodStatic(EllipticalFinSet.class, "setLength", double.class)));
325 setters.put("EllipticalFinSet:height", new DoubleSetter(
326 Reflection.findMethodStatic(EllipticalFinSet.class, "setHeight", double.class)));
328 // FreeformFinSet points handled as a special handler
331 setters.put("LaunchLug:radius", new DoubleSetter(
332 Reflection.findMethodStatic(LaunchLug.class, "setRadius", double.class)));
333 setters.put("LaunchLug:length", new DoubleSetter(
334 Reflection.findMethodStatic(LaunchLug.class, "setLength", double.class)));
335 setters.put("LaunchLug:thickness", new DoubleSetter(
336 Reflection.findMethodStatic(LaunchLug.class, "setThickness", double.class)));
337 setters.put("LaunchLug:radialdirection", new DoubleSetter(
338 Reflection.findMethodStatic(LaunchLug.class, "setRadialDirection", double.class),
341 // InternalComponent - nothing
343 // StructuralComponent
344 setters.put("StructuralComponent:material", new MaterialSetter(
345 Reflection.findMethodStatic(StructuralComponent.class, "setMaterial", Material.class),
346 Material.Type.BULK));
349 setters.put("RingComponent:length", new DoubleSetter(
350 Reflection.findMethodStatic(RingComponent.class, "setLength", double.class)));
351 setters.put("RingComponent:radialposition", new DoubleSetter(
352 Reflection.findMethodStatic(RingComponent.class, "setRadialPosition", double.class)));
353 setters.put("RingComponent:radialdirection", new DoubleSetter(
354 Reflection.findMethodStatic(RingComponent.class, "setRadialDirection", double.class),
357 // ThicknessRingComponent - radius on separate components due to differing automatics
358 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
359 Reflection.findMethodStatic(ThicknessRingComponent.class, "setThickness", double.class)));
362 setters.put("EngineBlock:outerradius", new DoubleSetter(
363 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadius", double.class),
365 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
368 setters.put("TubeCoupler:outerradius", new DoubleSetter(
369 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadius", double.class),
371 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
374 setters.put("InnerTube:outerradius", new DoubleSetter(
375 Reflection.findMethodStatic(InnerTube.class, "setOuterRadius", double.class)));
376 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
377 setters.put("InnerTube:clusterscale", new DoubleSetter(
378 Reflection.findMethodStatic(InnerTube.class, "setClusterScale", double.class)));
379 setters.put("InnerTube:clusterrotation", new DoubleSetter(
380 Reflection.findMethodStatic(InnerTube.class, "setClusterRotation", double.class),
383 // RadiusRingComponent
386 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
387 Reflection.findMethodStatic(RadiusRingComponent.class, "setInnerRadius", double.class)));
388 setters.put("Bulkhead:outerradius", new DoubleSetter(
389 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadius", double.class),
391 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
394 setters.put("CenteringRing:innerradius", new DoubleSetter(
395 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadius", double.class),
397 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
398 setters.put("CenteringRing:outerradius", new DoubleSetter(
399 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadius", double.class),
401 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
405 setters.put("MassObject:packedlength", new DoubleSetter(
406 Reflection.findMethodStatic(MassObject.class, "setLength", double.class)));
407 setters.put("MassObject:packedradius", new DoubleSetter(
408 Reflection.findMethodStatic(MassObject.class, "setRadius", double.class)));
409 setters.put("MassObject:radialposition", new DoubleSetter(
410 Reflection.findMethodStatic(MassObject.class, "setRadialPosition", double.class)));
411 setters.put("MassObject:radialdirection", new DoubleSetter(
412 Reflection.findMethodStatic(MassObject.class, "setRadialDirection", double.class),
416 setters.put("MassComponent:mass", new DoubleSetter(
417 Reflection.findMethodStatic(MassComponent.class, "setComponentMass", double.class)));
420 setters.put("ShockCord:cordlength", new DoubleSetter(
421 Reflection.findMethodStatic(ShockCord.class, "setCordLength", double.class)));
422 setters.put("ShockCord:material", new MaterialSetter(
423 Reflection.findMethodStatic(ShockCord.class, "setMaterial", Material.class),
424 Material.Type.LINE));
427 setters.put("RecoveryDevice:cd", new DoubleSetter(
428 Reflection.findMethodStatic(RecoveryDevice.class, "setCD", double.class),
430 Reflection.findMethodStatic(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
431 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
432 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
433 RecoveryDevice.DeployEvent.class));
434 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
435 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployAltitude", double.class)));
436 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
437 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployDelay", double.class)));
438 setters.put("RecoveryDevice:material", new MaterialSetter(
439 Reflection.findMethodStatic(RecoveryDevice.class, "setMaterial", Material.class),
440 Material.Type.SURFACE));
443 setters.put("Parachute:diameter", new DoubleSetter(
444 Reflection.findMethodStatic(Parachute.class, "setDiameter", double.class)));
445 setters.put("Parachute:linecount", new IntSetter(
446 Reflection.findMethodStatic(Parachute.class, "setLineCount", int.class)));
447 setters.put("Parachute:linelength", new DoubleSetter(
448 Reflection.findMethodStatic(Parachute.class, "setLineLength", double.class)));
449 setters.put("Parachute:linematerial", new MaterialSetter(
450 Reflection.findMethodStatic(Parachute.class, "setLineMaterial", Material.class),
451 Material.Type.LINE));
454 setters.put("Streamer:striplength", new DoubleSetter(
455 Reflection.findMethodStatic(Streamer.class, "setStripLength", double.class)));
456 setters.put("Streamer:stripwidth", new DoubleSetter(
457 Reflection.findMethodStatic(Streamer.class, "setStripWidth", double.class)));
460 // <motorconfiguration> handled by separate handler
461 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
462 Reflection.findMethodStatic(Rocket.class, "setReferenceType", ReferenceType.class),
463 ReferenceType.class));
464 setters.put("Rocket:customreference", new DoubleSetter(
465 Reflection.findMethodStatic(Rocket.class, "setCustomReferenceLength", double.class)));
466 setters.put("Rocket:designer", new StringSetter(
467 Reflection.findMethodStatic(Rocket.class, "setDesigner", String.class)));
468 setters.put("Rocket:revision", new StringSetter(
469 Reflection.findMethodStatic(Rocket.class, "setRevision", String.class)));
474 * Search for a enum value that has the corresponding name as an XML value. The current
475 * conversion from enum name to XML value is to lowercase the name and strip out all
476 * underscore characters. This method returns a match to these criteria, or <code>null</code>
477 * if no such enum exists.
479 * @param <T> then enum type.
480 * @param name the XML value, null ok.
481 * @param enumClass the class of the enum.
482 * @return the found enum value, or <code>null</code>.
484 public static <T extends Enum<T>> Enum<T> findEnum(String name,
485 Class<? extends Enum<T>> enumClass) {
490 for (Enum<T> e : enumClass.getEnumConstants()) {
491 if (e.name().toLowerCase().replace("_", "").equals(name)) {
500 * Convert a string to a double including formatting specifications of the OpenRocket
501 * file format. This accepts all formatting that is valid for
502 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
504 * @param s the string to parse.
505 * @return the numerical value.
506 * @throws NumberFormatException the the string cannot be parsed.
508 public static double stringToDouble(String s) throws NumberFormatException {
510 throw new NumberFormatException("null string");
511 if (s.equalsIgnoreCase("NaN"))
513 if (s.equalsIgnoreCase("Inf"))
514 return Double.POSITIVE_INFINITY;
515 if (s.equalsIgnoreCase("-Inf"))
516 return Double.NEGATIVE_INFINITY;
517 return Double.parseDouble(s);
526 * The starting point of the handlers. Accepts a single <openrocket> element and hands
527 * the contents to be read by a OpenRocketContentsHandler.
529 class OpenRocketHandler extends ElementHandler {
530 private OpenRocketContentHandler handler = null;
533 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
534 * has not been read yet.
536 * @return the document read, or null.
538 public OpenRocketDocument getDocument() {
539 return handler.getDocument();
543 public ElementHandler openElement(String element, HashMap<String, String> attributes,
544 WarningSet warnings) {
546 // Check for unknown elements
547 if (!element.equals("openrocket")) {
548 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
552 // Check for first call
553 if (handler != null) {
554 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
559 // Check version number
560 String version = null;
561 String creator = attributes.remove("creator");
562 String docVersion = attributes.remove("version");
563 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
564 if (v.equals(docVersion)) {
569 if (version == null) {
570 String str = "Unsupported document version";
571 if (docVersion != null)
572 str += " " + docVersion;
573 if (creator != null && !creator.trim().equals(""))
574 str += " (written using '" + creator.trim() + "')";
575 str += ", attempting to read file anyway.";
579 handler = new OpenRocketContentHandler();
584 public void closeElement(String element, HashMap<String, String> attributes,
585 String content, WarningSet warnings) throws SAXException {
586 attributes.remove("version");
587 attributes.remove("creator");
588 super.closeElement(element, attributes, content, warnings);
596 * Handles the content of the <openrocket> tag.
598 class OpenRocketContentHandler extends ElementHandler {
599 private final OpenRocketDocument doc;
600 private final Rocket rocket;
602 private boolean rocketDefined = false;
603 private boolean simulationsDefined = false;
605 public OpenRocketContentHandler() {
606 this.rocket = new Rocket();
607 this.doc = new OpenRocketDocument(rocket);
611 public OpenRocketDocument getDocument() {
618 public ElementHandler openElement(String element, HashMap<String, String> attributes,
619 WarningSet warnings) {
621 if (element.equals("rocket")) {
624 .fromString("Multiple rocket designs within one document, "
625 + "ignoring later ones."));
628 rocketDefined = true;
629 return new ComponentParameterHandler(rocket);
632 if (element.equals("simulations")) {
633 if (simulationsDefined) {
635 .fromString("Multiple simulation definitions within one document, "
636 + "ignoring later ones."));
639 simulationsDefined = true;
640 return new SimulationsHandler(doc);
643 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
653 * A handler that creates components from the corresponding elements. The control of the
654 * contents is passed on to ComponentParameterHandler.
656 class ComponentHandler extends ElementHandler {
657 private final RocketComponent parent;
659 public ComponentHandler(RocketComponent parent) {
660 this.parent = parent;
664 public ElementHandler openElement(String element, HashMap<String, String> attributes,
665 WarningSet warnings) {
667 // Attempt to construct new component
668 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
670 if (constructor == null) {
671 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
677 c = constructor.newInstance();
678 } catch (InstantiationException e) {
679 throw new BugException("Error constructing component.", e);
680 } catch (IllegalAccessException e) {
681 throw new BugException("Error constructing component.", e);
682 } catch (InvocationTargetException e) {
683 throw Reflection.handleWrappedException(e);
688 return new ComponentParameterHandler(c);
694 * A handler that populates the parameters of a previously constructed rocket component.
695 * This uses the setters, or delegates the handling to another handler for specific
698 class ComponentParameterHandler extends ElementHandler {
699 private final RocketComponent component;
701 public ComponentParameterHandler(RocketComponent c) {
706 public ElementHandler openElement(String element, HashMap<String, String> attributes,
707 WarningSet warnings) {
709 // Check for specific elements that contain other elements
710 if (element.equals("subcomponents")) {
711 return new ComponentHandler(component);
713 if (element.equals("motormount")) {
714 if (!(component instanceof MotorMount)) {
715 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
718 return new MotorMountHandler((MotorMount) component);
720 if (element.equals("finpoints")) {
721 if (!(component instanceof FreeformFinSet)) {
722 warnings.add(Warning.fromString("Illegal component defined for fin points."));
725 return new FinSetPointHandler((FreeformFinSet) component);
727 if (element.equals("motorconfiguration")) {
728 if (!(component instanceof Rocket)) {
729 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
732 return new MotorConfigurationHandler((Rocket) component);
736 return PlainTextHandler.INSTANCE;
740 public void closeElement(String element, HashMap<String, String> attributes,
741 String content, WarningSet warnings) {
743 if (element.equals("subcomponents") || element.equals("motormount") ||
744 element.equals("finpoints") || element.equals("motorconfiguration")) {
748 // Search for the correct setter class
751 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
752 String setterKey = c.getSimpleName() + ":" + element;
753 Setter s = DocumentConfig.setters.get(setterKey);
756 System.out.println("Calling with key " + setterKey);
757 s.set(component, content, attributes, warnings);
760 if (DocumentConfig.setters.containsKey(setterKey)) {
761 // Key exists but is null -> invalid parameter
767 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
768 + component.getComponentName() + ", ignoring."));
775 * A handler that reads the <point> specifications within the freeformfinset's
776 * <finpoints> elements.
778 class FinSetPointHandler extends ElementHandler {
779 private final FreeformFinSet finset;
780 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
782 public FinSetPointHandler(FreeformFinSet finset) {
783 this.finset = finset;
787 public ElementHandler openElement(String element, HashMap<String, String> attributes,
788 WarningSet warnings) {
789 return PlainTextHandler.INSTANCE;
794 public void closeElement(String element, HashMap<String, String> attributes,
795 String content, WarningSet warnings) throws SAXException {
797 String strx = attributes.remove("x");
798 String stry = attributes.remove("y");
799 if (strx == null || stry == null) {
800 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
804 double x = Double.parseDouble(strx);
805 double y = Double.parseDouble(stry);
806 coordinates.add(new Coordinate(x, y));
807 } catch (NumberFormatException e) {
808 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
812 super.closeElement(element, attributes, content, warnings);
816 public void endHandler(String element, HashMap<String, String> attributes,
817 String content, WarningSet warnings) {
819 finset.setPoints(coordinates.toArray(new Coordinate[0]));
820 } catch (IllegalFinPointException e) {
821 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
827 class MotorMountHandler extends ElementHandler {
828 private final MotorMount mount;
829 private MotorHandler motorHandler;
831 public MotorMountHandler(MotorMount mount) {
833 mount.setMotorMount(true);
837 public ElementHandler openElement(String element, HashMap<String, String> attributes,
838 WarningSet warnings) {
840 if (element.equals("motor")) {
841 motorHandler = new MotorHandler();
845 if (element.equals("ignitionevent") ||
846 element.equals("ignitiondelay") ||
847 element.equals("overhang")) {
848 return PlainTextHandler.INSTANCE;
851 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
858 public void closeElement(String element, HashMap<String, String> attributes,
859 String content, WarningSet warnings) throws SAXException {
861 if (element.equals("motor")) {
862 String id = attributes.get("configid");
863 if (id == null || id.equals("")) {
864 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
868 Motor motor = motorHandler.getMotor(warnings);
869 mount.setMotor(id, motor);
870 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
874 if (element.equals("ignitionevent")) {
875 MotorMount.IgnitionEvent event = null;
876 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
877 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
883 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
886 mount.setIgnitionEvent(event);
890 if (element.equals("ignitiondelay")) {
893 d = Double.parseDouble(content);
894 } catch (NumberFormatException nfe) {
895 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
898 mount.setIgnitionDelay(d);
902 if (element.equals("overhang")) {
905 d = Double.parseDouble(content);
906 } catch (NumberFormatException nfe) {
907 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
910 mount.setMotorOverhang(d);
914 super.closeElement(element, attributes, content, warnings);
921 class MotorConfigurationHandler extends ElementHandler {
922 private final Rocket rocket;
923 private String name = null;
924 private boolean inNameElement = false;
926 public MotorConfigurationHandler(Rocket rocket) {
927 this.rocket = rocket;
931 public ElementHandler openElement(String element, HashMap<String, String> attributes,
932 WarningSet warnings) {
934 if (inNameElement || !element.equals("name")) {
935 warnings.add(Warning.FILE_INVALID_PARAMETER);
938 inNameElement = true;
940 return PlainTextHandler.INSTANCE;
944 public void closeElement(String element, HashMap<String, String> attributes,
945 String content, WarningSet warnings) {
950 public void endHandler(String element, HashMap<String, String> attributes,
951 String content, WarningSet warnings) throws SAXException {
953 String configid = attributes.remove("configid");
954 if (configid == null || configid.equals("")) {
955 warnings.add(Warning.FILE_INVALID_PARAMETER);
959 if (!rocket.addMotorConfigurationID(configid)) {
960 warnings.add("Duplicate motor configuration ID used.");
964 if (name != null && name.trim().length() > 0) {
965 rocket.setMotorConfigurationName(configid, name);
968 if ("true".equals(attributes.remove("default"))) {
969 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
972 super.closeElement(element, attributes, content, warnings);
977 class MotorHandler extends ElementHandler {
978 private Motor.Type type = null;
979 private String manufacturer = null;
980 private String designation = null;
981 private String digest = null;
982 private double diameter = Double.NaN;
983 private double length = Double.NaN;
984 private double delay = Double.NaN;
987 public ElementHandler openElement(String element, HashMap<String, String> attributes,
988 WarningSet warnings) {
989 return PlainTextHandler.INSTANCE;
994 * Return the motor to use, or null.
996 public Motor getMotor(WarningSet warnings) {
997 if (designation == null) {
998 warnings.add(Warning.fromString("No motor specified, ignoring."));
1002 List<ThrustCurveMotor> motors = Application.getMotorSetDatabase().findMotors(type, manufacturer,
1003 designation, diameter, length);
1006 if (motors.size() == 0) {
1007 String str = "No motor with designation '" + designation + "'";
1008 if (manufacturer != null)
1009 str += " for manufacturer '" + manufacturer + "'";
1016 if (motors.size() == 1) {
1017 ThrustCurveMotor m = motors.get(0);
1018 if (digest != null && !MotorDigest.digestMotor(m).equals(digest)) {
1019 String str = "Motor with designation '" + designation + "'";
1020 if (manufacturer != null)
1021 str += " for manufacturer '" + manufacturer + "'";
1022 str += " has differing thrust curve than the original.";
1028 // Multiple motors, check digest for which one to use
1029 if (digest != null) {
1031 // Check for motor with correct digest
1032 for (ThrustCurveMotor m : motors) {
1033 if (MotorDigest.digestMotor(m).equals(digest)) {
1037 String str = "Motor with designation '" + designation + "'";
1038 if (manufacturer != null)
1039 str += " for manufacturer '" + manufacturer + "'";
1040 str += " has differing thrust curve than the original.";
1045 // No digest, check for preferred digest (OpenRocket <= 1.1.0)
1046 // TODO: MEDIUM: This should only be done for document versions 1.1 and below
1047 for (ThrustCurveMotor m : motors) {
1048 if (PreferredMotorDigests.DIGESTS.contains(MotorDigest.digestMotor(m))) {
1053 String str = "Multiple motors with designation '" + designation + "'";
1054 if (manufacturer != null)
1055 str += " for manufacturer '" + manufacturer + "'";
1056 str += " found, one chosen arbitrarily.";
1060 return motors.get(0);
1064 * Return the delay to use for the motor.
1066 public double getDelay(WarningSet warnings) {
1067 if (Double.isNaN(delay)) {
1068 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1069 return Motor.PLUGGED;
1076 public void closeElement(String element, HashMap<String, String> attributes,
1077 String content, WarningSet warnings) throws SAXException {
1079 content = content.trim();
1081 if (element.equals("type")) {
1085 for (Motor.Type t : Motor.Type.values()) {
1086 if (t.name().toLowerCase().equals(content.trim())) {
1092 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1095 } else if (element.equals("manufacturer")) {
1098 manufacturer = content.trim();
1100 } else if (element.equals("designation")) {
1103 designation = content.trim();
1105 } else if (element.equals("digest")) {
1108 digest = content.trim();
1110 } else if (element.equals("diameter")) {
1113 diameter = Double.NaN;
1115 diameter = Double.parseDouble(content.trim());
1116 } catch (NumberFormatException e) {
1119 if (Double.isNaN(diameter)) {
1120 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1123 } else if (element.equals("length")) {
1126 length = Double.NaN;
1128 length = Double.parseDouble(content.trim());
1129 } catch (NumberFormatException ignore) {
1132 if (Double.isNaN(length)) {
1133 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1136 } else if (element.equals("delay")) {
1140 if (content.equals("none")) {
1141 delay = Motor.PLUGGED;
1144 delay = Double.parseDouble(content.trim());
1145 } catch (NumberFormatException ignore) {
1148 if (Double.isNaN(delay)) {
1149 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1155 super.closeElement(element, attributes, content, warnings);
1163 class SimulationsHandler extends ElementHandler {
1164 private final OpenRocketDocument doc;
1165 private SingleSimulationHandler handler;
1167 public SimulationsHandler(OpenRocketDocument doc) {
1172 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1173 WarningSet warnings) {
1175 if (!element.equals("simulation")) {
1176 warnings.add("Unknown element '" + element + "', ignoring.");
1180 handler = new SingleSimulationHandler(doc);
1185 public void closeElement(String element, HashMap<String, String> attributes,
1186 String content, WarningSet warnings) throws SAXException {
1187 attributes.remove("status");
1188 super.closeElement(element, attributes, content, warnings);
1194 class SingleSimulationHandler extends ElementHandler {
1196 private final OpenRocketDocument doc;
1198 private String name;
1200 private SimulationConditionsHandler conditionHandler;
1201 private FlightDataHandler dataHandler;
1203 private final List<String> listeners = new ArrayList<String>();
1205 public SingleSimulationHandler(OpenRocketDocument doc) {
1212 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1213 WarningSet warnings) {
1215 if (element.equals("name") || element.equals("simulator") ||
1216 element.equals("calculator") || element.equals("listener")) {
1217 return PlainTextHandler.INSTANCE;
1218 } else if (element.equals("conditions")) {
1219 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1220 return conditionHandler;
1221 } else if (element.equals("flightdata")) {
1222 dataHandler = new FlightDataHandler();
1225 warnings.add("Unknown element '" + element + "', ignoring.");
1231 public void closeElement(String element, HashMap<String, String> attributes,
1232 String content, WarningSet warnings) {
1234 if (element.equals("name")) {
1236 } else if (element.equals("simulator")) {
1237 if (!content.trim().equals("RK4Simulator")) {
1238 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1240 } else if (element.equals("calculator")) {
1241 if (!content.trim().equals("BarrowmanCalculator")) {
1242 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1244 } else if (element.equals("listener") && content.trim().length() > 0) {
1245 listeners.add(content.trim());
1251 public void endHandler(String element, HashMap<String, String> attributes,
1252 String content, WarningSet warnings) {
1254 String s = attributes.get("status");
1255 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1256 if (status == null) {
1257 warnings.add("Simulation status unknown, assuming outdated.");
1258 status = Simulation.Status.OUTDATED;
1261 GUISimulationConditions conditions;
1262 if (conditionHandler != null) {
1263 conditions = conditionHandler.getConditions();
1265 warnings.add("Simulation conditions not defined, using defaults.");
1266 conditions = new GUISimulationConditions(doc.getRocket());
1270 name = "Simulation";
1273 if (dataHandler == null)
1276 data = dataHandler.getFlightData();
1278 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1279 conditions, listeners, data);
1281 doc.addSimulation(simulation);
1287 class SimulationConditionsHandler extends ElementHandler {
1288 private GUISimulationConditions conditions;
1289 private AtmosphereHandler atmosphereHandler;
1291 public SimulationConditionsHandler(Rocket rocket) {
1292 conditions = new GUISimulationConditions(rocket);
1295 public GUISimulationConditions getConditions() {
1300 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1301 WarningSet warnings) {
1302 if (element.equals("atmosphere")) {
1303 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1304 return atmosphereHandler;
1306 return PlainTextHandler.INSTANCE;
1310 public void closeElement(String element, HashMap<String, String> attributes,
1311 String content, WarningSet warnings) {
1313 double d = Double.NaN;
1315 d = Double.parseDouble(content);
1316 } catch (NumberFormatException ignore) {
1320 if (element.equals("configid")) {
1321 if (content.equals("")) {
1322 conditions.setMotorConfigurationID(null);
1324 conditions.setMotorConfigurationID(content);
1326 } else if (element.equals("launchrodlength")) {
1327 if (Double.isNaN(d)) {
1328 warnings.add("Illegal launch rod length defined, ignoring.");
1330 conditions.setLaunchRodLength(d);
1332 } else if (element.equals("launchrodangle")) {
1333 if (Double.isNaN(d)) {
1334 warnings.add("Illegal launch rod angle defined, ignoring.");
1336 conditions.setLaunchRodAngle(d * Math.PI / 180);
1338 } else if (element.equals("launchroddirection")) {
1339 if (Double.isNaN(d)) {
1340 warnings.add("Illegal launch rod direction defined, ignoring.");
1342 conditions.setLaunchRodDirection(d * Math.PI / 180);
1344 } else if (element.equals("windaverage")) {
1345 if (Double.isNaN(d)) {
1346 warnings.add("Illegal average windspeed defined, ignoring.");
1348 conditions.setWindSpeedAverage(d);
1350 } else if (element.equals("windturbulence")) {
1351 if (Double.isNaN(d)) {
1352 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1354 conditions.setWindTurbulenceIntensity(d);
1356 } else if (element.equals("launchaltitude")) {
1357 if (Double.isNaN(d)) {
1358 warnings.add("Illegal launch altitude defined, ignoring.");
1360 conditions.setLaunchAltitude(d);
1362 } else if (element.equals("launchlatitude")) {
1363 if (Double.isNaN(d)) {
1364 warnings.add("Illegal launch latitude defined, ignoring.");
1366 conditions.setLaunchLatitude(d);
1368 } else if (element.equals("atmosphere")) {
1369 atmosphereHandler.storeSettings(conditions, warnings);
1370 } else if (element.equals("timestep")) {
1371 if (Double.isNaN(d)) {
1372 warnings.add("Illegal time step defined, ignoring.");
1374 conditions.setTimeStep(d);
1381 class AtmosphereHandler extends ElementHandler {
1382 private final String model;
1383 private double temperature = Double.NaN;
1384 private double pressure = Double.NaN;
1386 public AtmosphereHandler(String model) {
1391 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1392 WarningSet warnings) {
1393 return PlainTextHandler.INSTANCE;
1397 public void closeElement(String element, HashMap<String, String> attributes,
1398 String content, WarningSet warnings) throws SAXException {
1400 double d = Double.NaN;
1402 d = Double.parseDouble(content);
1403 } catch (NumberFormatException ignore) {
1406 if (element.equals("basetemperature")) {
1407 if (Double.isNaN(d)) {
1408 warnings.add("Illegal base temperature specified, ignoring.");
1411 } else if (element.equals("basepressure")) {
1412 if (Double.isNaN(d)) {
1413 warnings.add("Illegal base pressure specified, ignoring.");
1417 super.closeElement(element, attributes, content, warnings);
1422 public void storeSettings(GUISimulationConditions cond, WarningSet warnings) {
1423 if (!Double.isNaN(pressure)) {
1424 cond.setLaunchPressure(pressure);
1426 if (!Double.isNaN(temperature)) {
1427 cond.setLaunchTemperature(temperature);
1430 if ("isa".equals(model)) {
1431 cond.setISAAtmosphere(true);
1432 } else if ("extendedisa".equals(model)) {
1433 cond.setISAAtmosphere(false);
1435 cond.setISAAtmosphere(true);
1436 warnings.add("Unknown atmospheric model, using ISA.");
1443 class FlightDataHandler extends ElementHandler {
1445 private FlightDataBranchHandler dataHandler;
1446 private WarningSet warningSet = new WarningSet();
1447 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1449 private FlightData data;
1451 public FlightData getFlightData() {
1456 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1457 WarningSet warnings) {
1459 if (element.equals("warning")) {
1460 return PlainTextHandler.INSTANCE;
1462 if (element.equals("databranch")) {
1463 if (attributes.get("name") == null || attributes.get("types") == null) {
1464 warnings.add("Illegal flight data definition, ignoring.");
1467 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1468 attributes.get("types"));
1472 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1478 public void closeElement(String element, HashMap<String, String> attributes,
1479 String content, WarningSet warnings) {
1481 if (element.equals("databranch")) {
1482 FlightDataBranch branch = dataHandler.getBranch();
1483 if (branch.getLength() > 0) {
1484 branches.add(branch);
1486 } else if (element.equals("warning")) {
1487 warningSet.add(Warning.fromString(content));
1493 public void endHandler(String element, HashMap<String, String> attributes,
1494 String content, WarningSet warnings) {
1496 if (branches.size() > 0) {
1497 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1499 double maxAltitude = Double.NaN;
1500 double maxVelocity = Double.NaN;
1501 double maxAcceleration = Double.NaN;
1502 double maxMach = Double.NaN;
1503 double timeToApogee = Double.NaN;
1504 double flightTime = Double.NaN;
1505 double groundHitVelocity = Double.NaN;
1508 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1509 } catch (NumberFormatException ignore) {
1512 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1513 } catch (NumberFormatException ignore) {
1516 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1517 } catch (NumberFormatException ignore) {
1520 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1521 } catch (NumberFormatException ignore) {
1524 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1525 } catch (NumberFormatException ignore) {
1528 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1529 } catch (NumberFormatException ignore) {
1533 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1534 } catch (NumberFormatException ignore) {
1537 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1538 timeToApogee, flightTime, groundHitVelocity);
1541 data.getWarningSet().addAll(warningSet);
1549 class FlightDataBranchHandler extends ElementHandler {
1550 private final FlightDataType[] types;
1551 private final FlightDataBranch branch;
1553 public FlightDataBranchHandler(String name, String typeList) {
1554 String[] split = typeList.split(",");
1555 types = new FlightDataType[split.length];
1556 for (int i = 0; i < split.length; i++) {
1557 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1560 // TODO: LOW: May throw an IllegalArgumentException
1561 branch = new FlightDataBranch(name, types);
1564 public FlightDataBranch getBranch() {
1570 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1571 WarningSet warnings) {
1573 if (element.equals("datapoint"))
1574 return PlainTextHandler.INSTANCE;
1575 if (element.equals("event"))
1576 return PlainTextHandler.INSTANCE;
1578 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1584 public void closeElement(String element, HashMap<String, String> attributes,
1585 String content, WarningSet warnings) {
1587 if (element.equals("event")) {
1589 FlightEvent.Type type;
1592 time = DocumentConfig.stringToDouble(attributes.get("time"));
1593 } catch (NumberFormatException e) {
1594 warnings.add("Illegal event specification, ignoring.");
1598 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1600 warnings.add("Illegal event specification, ignoring.");
1604 branch.addEvent(new FlightEvent(type, time));
1608 if (!element.equals("datapoint")) {
1609 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1613 // element == "datapoint"
1616 // Check line format
1617 String[] split = content.split(",");
1618 if (split.length != types.length) {
1619 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1623 // Parse the doubles
1624 double[] values = new double[split.length];
1625 for (int i = 0; i < values.length; i++) {
1627 values[i] = DocumentConfig.stringToDouble(split[i]);
1628 } catch (NumberFormatException e) {
1629 warnings.add("Data point format error, ignoring point.");
1634 // Add point to branch
1636 for (int i = 0; i < types.length; i++) {
1637 branch.setValue(types[i], values[i]);
1646 ///////////////// Setters implementation
1652 * Set the specified value to the given component.
1654 * @param component the component to which to set.
1655 * @param value the value within the element.
1656 * @param attributes attributes for the element.
1657 * @param warnings the warning set to use.
1659 public void set(RocketComponent component, String value,
1660 HashMap<String, String> attributes, WarningSet warnings);
1664 //// StringSetter - sets the value to the contained String
1665 class StringSetter implements Setter {
1666 private final Reflection.Method setMethod;
1668 public StringSetter(Reflection.Method set) {
1672 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1673 WarningSet warnings) {
1674 setMethod.invoke(c, s);
1678 //// IntSetter - set an integer value
1679 class IntSetter implements Setter {
1680 private final Reflection.Method setMethod;
1682 public IntSetter(Reflection.Method set) {
1686 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1687 WarningSet warnings) {
1689 int n = Integer.parseInt(s);
1690 setMethod.invoke(c, n);
1691 } catch (NumberFormatException e) {
1692 warnings.add(Warning.FILE_INVALID_PARAMETER);
1698 //// BooleanSetter - set a boolean value
1699 class BooleanSetter implements Setter {
1700 private final Reflection.Method setMethod;
1702 public BooleanSetter(Reflection.Method set) {
1706 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1707 WarningSet warnings) {
1710 if (s.equalsIgnoreCase("true")) {
1711 setMethod.invoke(c, true);
1712 } else if (s.equalsIgnoreCase("false")) {
1713 setMethod.invoke(c, false);
1715 warnings.add(Warning.FILE_INVALID_PARAMETER);
1722 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1723 //// calls a setXXX(boolean) method.
1724 class DoubleSetter implements Setter {
1725 private final Reflection.Method setMethod;
1726 private final String specialString;
1727 private final Reflection.Method specialMethod;
1728 private final double multiplier;
1731 * Set only the double value.
1732 * @param set set method for the double value.
1734 public DoubleSetter(Reflection.Method set) {
1735 this.setMethod = set;
1736 this.specialString = null;
1737 this.specialMethod = null;
1738 this.multiplier = 1.0;
1742 * Multiply with the given multiplier and set the double value.
1743 * @param set set method for the double value.
1744 * @param mul multiplier.
1746 public DoubleSetter(Reflection.Method set, double mul) {
1747 this.setMethod = set;
1748 this.specialString = null;
1749 this.specialMethod = null;
1750 this.multiplier = mul;
1754 * Set the double value, or if the value equals the special string, use the
1755 * special setter and set it to true.
1757 * @param set double setter.
1758 * @param special special string
1759 * @param specialMethod boolean setter.
1761 public DoubleSetter(Reflection.Method set, String special,
1762 Reflection.Method specialMethod) {
1763 this.setMethod = set;
1764 this.specialString = special;
1765 this.specialMethod = specialMethod;
1766 this.multiplier = 1.0;
1770 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1771 WarningSet warnings) {
1775 // Check for special case
1776 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1777 specialMethod.invoke(c, true);
1783 double d = Double.parseDouble(s);
1784 setMethod.invoke(c, d * multiplier);
1785 } catch (NumberFormatException e) {
1786 warnings.add(Warning.FILE_INVALID_PARAMETER);
1792 class OverrideSetter implements Setter {
1793 private final Reflection.Method setMethod;
1794 private final Reflection.Method enabledMethod;
1796 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1797 this.setMethod = set;
1798 this.enabledMethod = enabledMethod;
1801 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1802 WarningSet warnings) {
1805 double d = Double.parseDouble(s);
1806 setMethod.invoke(c, d);
1807 enabledMethod.invoke(c, true);
1808 } catch (NumberFormatException e) {
1809 warnings.add(Warning.FILE_INVALID_PARAMETER);
1814 //// EnumSetter - sets a generic enum type
1815 class EnumSetter<T extends Enum<T>> implements Setter {
1816 private final Reflection.Method setter;
1817 private final Class<T> enumClass;
1819 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1821 this.enumClass = enumClass;
1825 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1826 WarningSet warnings) {
1828 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1829 if (setEnum == null) {
1830 warnings.add(Warning.FILE_INVALID_PARAMETER);
1834 setter.invoke(c, setEnum);
1839 //// ColorSetter - sets a Color value
1840 class ColorSetter implements Setter {
1841 private final Reflection.Method setMethod;
1843 public ColorSetter(Reflection.Method set) {
1847 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1848 WarningSet warnings) {
1850 String red = attributes.get("red");
1851 String green = attributes.get("green");
1852 String blue = attributes.get("blue");
1854 if (red == null || green == null || blue == null) {
1855 warnings.add(Warning.FILE_INVALID_PARAMETER);
1861 r = Integer.parseInt(red);
1862 g = Integer.parseInt(green);
1863 b = Integer.parseInt(blue);
1864 } catch (NumberFormatException e) {
1865 warnings.add(Warning.FILE_INVALID_PARAMETER);
1869 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1870 warnings.add(Warning.FILE_INVALID_PARAMETER);
1874 Color color = new Color(r, g, b);
1875 setMethod.invoke(c, color);
1877 if (!s.trim().equals("")) {
1878 warnings.add(Warning.FILE_INVALID_PARAMETER);
1885 class MaterialSetter implements Setter {
1886 private final Reflection.Method setMethod;
1887 private final Material.Type type;
1889 public MaterialSetter(Reflection.Method set, Material.Type type) {
1890 this.setMethod = set;
1894 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1895 WarningSet warnings) {
1901 if (name.equals("")) {
1902 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1909 str = attributes.remove("density");
1911 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1915 density = Double.parseDouble(str);
1916 } catch (NumberFormatException e) {
1917 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1922 // double thickness = 0;
1923 // str = attributes.remove("thickness");
1926 // thickness = Double.parseDouble(str);
1927 // } catch (NumberFormatException e){
1928 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1932 // Check type if specified
1933 str = attributes.remove("type");
1934 if (str != null && !type.name().toLowerCase().equals(str)) {
1935 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1939 mat = Databases.findMaterial(type, name, density, false);
1941 setMethod.invoke(c, mat);
1948 class PositionSetter implements Setter {
1950 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
1951 WarningSet warnings) {
1953 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
1954 RocketComponent.Position.class);
1956 warnings.add(Warning.FILE_INVALID_PARAMETER);
1962 pos = Double.parseDouble(value);
1963 } catch (NumberFormatException e) {
1964 warnings.add(Warning.FILE_INVALID_PARAMETER);
1968 if (c instanceof FinSet) {
1969 ((FinSet) c).setRelativePosition(type);
1970 c.setPositionValue(pos);
1971 } else if (c instanceof LaunchLug) {
1972 ((LaunchLug) c).setRelativePosition(type);
1973 c.setPositionValue(pos);
1974 } else if (c instanceof InternalComponent) {
1975 ((InternalComponent) c).setRelativePosition(type);
1976 c.setPositionValue(pos);
1978 warnings.add(Warning.FILE_INVALID_PARAMETER);
1985 class FinTabPositionSetter extends DoubleSetter {
1987 public FinTabPositionSetter() {
1988 super(Reflection.findMethodStatic(FinSet.class, "setTabShift", double.class));
1992 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1993 WarningSet warnings) {
1995 if (!(c instanceof FinSet)) {
1996 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
1999 String relative = attributes.get("relativeto");
2000 FinSet.TabRelativePosition position =
2001 (TabRelativePosition) DocumentConfig.findEnum(relative,
2002 FinSet.TabRelativePosition.class);
2004 if (position != null) {
2006 ((FinSet) c).setTabRelativePosition(position);
2009 if (relative == null) {
2010 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2012 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2016 super.set(c, s, attributes, warnings);
2023 class ClusterConfigurationSetter implements Setter {
2025 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2026 WarningSet warnings) {
2028 if (!(component instanceof Clusterable)) {
2029 warnings.add("Illegal component defined as cluster.");
2033 ClusterConfiguration config = null;
2034 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2035 if (c.getXMLName().equals(value)) {
2041 if (config == null) {
2042 warnings.add("Illegal cluster configuration specified.");
2046 ((Clusterable) component).setClusterConfiguration(config);