1 package net.sf.openrocket.file.openrocket.importt;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.InvocationTargetException;
7 import java.util.ArrayList;
8 import java.util.HashMap;
10 import java.util.Locale;
11 import java.util.regex.Matcher;
12 import java.util.regex.Pattern;
14 import net.sf.openrocket.aerodynamics.Warning;
15 import net.sf.openrocket.aerodynamics.WarningSet;
16 import net.sf.openrocket.database.Databases;
17 import net.sf.openrocket.document.OpenRocketDocument;
18 import net.sf.openrocket.document.Simulation;
19 import net.sf.openrocket.document.Simulation.Status;
20 import net.sf.openrocket.document.StorageOptions;
21 import net.sf.openrocket.file.AbstractRocketLoader;
22 import net.sf.openrocket.file.MotorFinder;
23 import net.sf.openrocket.file.RocketLoadException;
24 import net.sf.openrocket.file.simplesax.AbstractElementHandler;
25 import net.sf.openrocket.file.simplesax.ElementHandler;
26 import net.sf.openrocket.file.simplesax.PlainTextHandler;
27 import net.sf.openrocket.file.simplesax.SimpleSAX;
28 import net.sf.openrocket.logging.LogHelper;
29 import net.sf.openrocket.material.Material;
30 import net.sf.openrocket.motor.Motor;
31 import net.sf.openrocket.rocketcomponent.BodyComponent;
32 import net.sf.openrocket.rocketcomponent.BodyTube;
33 import net.sf.openrocket.rocketcomponent.Bulkhead;
34 import net.sf.openrocket.rocketcomponent.CenteringRing;
35 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
36 import net.sf.openrocket.rocketcomponent.Clusterable;
37 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
38 import net.sf.openrocket.rocketcomponent.EngineBlock;
39 import net.sf.openrocket.rocketcomponent.ExternalComponent;
40 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
41 import net.sf.openrocket.rocketcomponent.FinSet;
42 import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
43 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
44 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
45 import net.sf.openrocket.rocketcomponent.InnerTube;
46 import net.sf.openrocket.rocketcomponent.InternalComponent;
47 import net.sf.openrocket.rocketcomponent.LaunchLug;
48 import net.sf.openrocket.rocketcomponent.MassComponent;
49 import net.sf.openrocket.rocketcomponent.MassObject;
50 import net.sf.openrocket.rocketcomponent.MotorMount;
51 import net.sf.openrocket.rocketcomponent.NoseCone;
52 import net.sf.openrocket.rocketcomponent.Parachute;
53 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
54 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
55 import net.sf.openrocket.rocketcomponent.ReferenceType;
56 import net.sf.openrocket.rocketcomponent.RingComponent;
57 import net.sf.openrocket.rocketcomponent.Rocket;
58 import net.sf.openrocket.rocketcomponent.RocketComponent;
59 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
60 import net.sf.openrocket.rocketcomponent.ShockCord;
61 import net.sf.openrocket.rocketcomponent.Stage;
62 import net.sf.openrocket.rocketcomponent.Streamer;
63 import net.sf.openrocket.rocketcomponent.StructuralComponent;
64 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
65 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
66 import net.sf.openrocket.rocketcomponent.Transition;
67 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
68 import net.sf.openrocket.rocketcomponent.TubeCoupler;
69 import net.sf.openrocket.simulation.FlightData;
70 import net.sf.openrocket.simulation.FlightDataBranch;
71 import net.sf.openrocket.simulation.FlightDataType;
72 import net.sf.openrocket.simulation.FlightEvent;
73 import net.sf.openrocket.simulation.FlightEvent.Type;
74 import net.sf.openrocket.simulation.SimulationOptions;
75 import net.sf.openrocket.startup.Application;
76 import net.sf.openrocket.unit.UnitGroup;
77 import net.sf.openrocket.util.BugException;
78 import net.sf.openrocket.util.Color;
79 import net.sf.openrocket.util.Coordinate;
80 import net.sf.openrocket.util.GeodeticComputationStrategy;
81 import net.sf.openrocket.util.LineStyle;
82 import net.sf.openrocket.util.Reflection;
84 import org.xml.sax.InputSource;
85 import org.xml.sax.SAXException;
89 * Class that loads a rocket definition from an OpenRocket rocket file.
91 * This class uses SAX to read the XML file format. The
92 * #loadFromStream(InputStream) method simply sets the system up and
93 * starts the parsing, while the actual logic is in the private inner class
94 * <code>OpenRocketHandler</code>.
96 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
98 public class OpenRocketLoader extends AbstractRocketLoader {
99 private static final LogHelper log = Application.getLogger();
103 public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException,
105 log.info("Loading .ork file");
106 DocumentLoadingContext context = new DocumentLoadingContext();
107 context.setMotorFinder(motorFinder);
109 InputSource xmlSource = new InputSource(source);
110 OpenRocketHandler handler = new OpenRocketHandler(context);
114 SimpleSAX.readXML(xmlSource, handler, warnings);
115 } catch (SAXException e) {
116 log.warn("Malformed XML in input");
117 throw new RocketLoadException("Malformed XML in input.", e);
121 OpenRocketDocument doc = handler.getDocument();
122 doc.getDefaultConfiguration().setAllStages();
124 // Deduce suitable time skip
125 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
126 for (Simulation s : doc.getSimulations()) {
127 if (s.getStatus() == Simulation.Status.EXTERNAL ||
128 s.getStatus() == Simulation.Status.NOT_SIMULATED)
130 if (s.getSimulatedData() == null)
132 if (s.getSimulatedData().getBranchCount() == 0)
134 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
137 List<Double> list = branch.get(FlightDataType.TYPE_TIME);
141 double previousTime = Double.NaN;
142 for (double time : list) {
143 if (time - previousTime < timeSkip)
144 timeSkip = time - previousTime;
149 timeSkip = Math.rint(timeSkip * 100) / 100;
151 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
152 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
153 doc.getDefaultStorageOptions().setExplicitlySet(false);
156 log.info("Loading done");
164 class DocumentConfig {
166 /* Remember to update OpenRocketSaver as well! */
167 public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4" };
170 * Divisor used in converting an integer version to the point-represented version.
171 * The integer version divided by this value is the major version and the remainder is
172 * the minor version. For example 101 corresponds to file version "1.1".
174 public static final int FILE_VERSION_DIVISOR = 100;
177 //////// Component constructors
178 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
181 // External components
182 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
183 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
184 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
185 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
186 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
187 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
188 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
190 // Internal components
191 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
192 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
193 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
194 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
195 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
197 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
198 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
199 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
200 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
203 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
205 } catch (NoSuchMethodException e) {
206 throw new BugException(
207 "Error in constructing the 'constructors' HashMap.");
212 //////// Parameter setters
214 * The keys are of the form Class:param, where Class is the class name and param
215 * the element name. Setters are searched for in descending class order.
216 * A setter of null means setting the parameter is not allowed.
218 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
221 setters.put("RocketComponent:name", new StringSetter(
222 Reflection.findMethod(RocketComponent.class, "setName", String.class)));
223 setters.put("RocketComponent:color", new ColorSetter(
224 Reflection.findMethod(RocketComponent.class, "setColor", Color.class)));
225 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
226 Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class),
228 setters.put("RocketComponent:position", new PositionSetter());
229 setters.put("RocketComponent:overridemass", new OverrideSetter(
230 Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class),
231 Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class)));
232 setters.put("RocketComponent:overridecg", new OverrideSetter(
233 Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class),
234 Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class)));
235 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
236 Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
237 setters.put("RocketComponent:comment", new StringSetter(
238 Reflection.findMethod(RocketComponent.class, "setComment", String.class)));
241 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
242 Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class),
244 setters.put("ExternalComponent:material", new MaterialSetter(
245 Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class),
246 Material.Type.BULK));
249 setters.put("BodyComponent:length", new DoubleSetter(
250 Reflection.findMethod(BodyComponent.class, "setLength", double.class)));
252 // SymmetricComponent
253 setters.put("SymmetricComponent:thickness", new DoubleSetter(
254 Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class),
256 Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class)));
259 setters.put("BodyTube:radius", new DoubleSetter(
260 Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class),
262 Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class)));
265 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
266 Reflection.findMethod(Transition.class, "setType", Transition.Shape.class),
267 Transition.Shape.class));
268 setters.put("Transition:shapeclipped", new BooleanSetter(
269 Reflection.findMethod(Transition.class, "setClipped", boolean.class)));
270 setters.put("Transition:shapeparameter", new DoubleSetter(
271 Reflection.findMethod(Transition.class, "setShapeParameter", double.class)));
273 setters.put("Transition:foreradius", new DoubleSetter(
274 Reflection.findMethod(Transition.class, "setForeRadius", double.class),
276 Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class)));
277 setters.put("Transition:aftradius", new DoubleSetter(
278 Reflection.findMethod(Transition.class, "setAftRadius", double.class),
280 Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class)));
282 setters.put("Transition:foreshoulderradius", new DoubleSetter(
283 Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class)));
284 setters.put("Transition:foreshoulderlength", new DoubleSetter(
285 Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class)));
286 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
287 Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class)));
288 setters.put("Transition:foreshouldercapped", new BooleanSetter(
289 Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class)));
291 setters.put("Transition:aftshoulderradius", new DoubleSetter(
292 Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class)));
293 setters.put("Transition:aftshoulderlength", new DoubleSetter(
294 Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class)));
295 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
296 Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class)));
297 setters.put("Transition:aftshouldercapped", new BooleanSetter(
298 Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class)));
300 // NoseCone - disable disallowed elements
301 setters.put("NoseCone:foreradius", null);
302 setters.put("NoseCone:foreshoulderradius", null);
303 setters.put("NoseCone:foreshoulderlength", null);
304 setters.put("NoseCone:foreshoulderthickness", null);
305 setters.put("NoseCone:foreshouldercapped", null);
308 setters.put("FinSet:fincount", new IntSetter(
309 Reflection.findMethod(FinSet.class, "setFinCount", int.class)));
310 setters.put("FinSet:rotation", new DoubleSetter(
311 Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0));
312 setters.put("FinSet:thickness", new DoubleSetter(
313 Reflection.findMethod(FinSet.class, "setThickness", double.class)));
314 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
315 Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
316 FinSet.CrossSection.class));
317 setters.put("FinSet:cant", new DoubleSetter(
318 Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0));
319 setters.put("FinSet:tabheight", new DoubleSetter(
320 Reflection.findMethod(FinSet.class, "setTabHeight", double.class)));
321 setters.put("FinSet:tablength", new DoubleSetter(
322 Reflection.findMethod(FinSet.class, "setTabLength", double.class)));
323 setters.put("FinSet:tabposition", new FinTabPositionSetter());
326 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
327 Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class)));
328 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
329 Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class)));
330 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
331 Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class)));
332 setters.put("TrapezoidFinSet:height", new DoubleSetter(
333 Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class)));
336 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
337 Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class)));
338 setters.put("EllipticalFinSet:height", new DoubleSetter(
339 Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class)));
341 // FreeformFinSet points handled as a special handler
344 setters.put("LaunchLug:radius", new DoubleSetter(
345 Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class)));
346 setters.put("LaunchLug:length", new DoubleSetter(
347 Reflection.findMethod(LaunchLug.class, "setLength", double.class)));
348 setters.put("LaunchLug:thickness", new DoubleSetter(
349 Reflection.findMethod(LaunchLug.class, "setThickness", double.class)));
350 setters.put("LaunchLug:radialdirection", new DoubleSetter(
351 Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class),
354 // InternalComponent - nothing
356 // StructuralComponent
357 setters.put("StructuralComponent:material", new MaterialSetter(
358 Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class),
359 Material.Type.BULK));
362 setters.put("RingComponent:length", new DoubleSetter(
363 Reflection.findMethod(RingComponent.class, "setLength", double.class)));
364 setters.put("RingComponent:radialposition", new DoubleSetter(
365 Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class)));
366 setters.put("RingComponent:radialdirection", new DoubleSetter(
367 Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class),
370 // ThicknessRingComponent - radius on separate components due to differing automatics
371 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
372 Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class)));
375 setters.put("EngineBlock:outerradius", new DoubleSetter(
376 Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class),
378 Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
381 setters.put("TubeCoupler:outerradius", new DoubleSetter(
382 Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class),
384 Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
387 setters.put("InnerTube:outerradius", new DoubleSetter(
388 Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class)));
389 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
390 setters.put("InnerTube:clusterscale", new DoubleSetter(
391 Reflection.findMethod(InnerTube.class, "setClusterScale", double.class)));
392 setters.put("InnerTube:clusterrotation", new DoubleSetter(
393 Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class),
396 // RadiusRingComponent
399 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
400 Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class)));
401 setters.put("Bulkhead:outerradius", new DoubleSetter(
402 Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class),
404 Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
407 setters.put("CenteringRing:innerradius", new DoubleSetter(
408 Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class),
410 Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
411 setters.put("CenteringRing:outerradius", new DoubleSetter(
412 Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class),
414 Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
418 setters.put("MassObject:packedlength", new DoubleSetter(
419 Reflection.findMethod(MassObject.class, "setLength", double.class)));
420 setters.put("MassObject:packedradius", new DoubleSetter(
421 Reflection.findMethod(MassObject.class, "setRadius", double.class)));
422 setters.put("MassObject:radialposition", new DoubleSetter(
423 Reflection.findMethod(MassObject.class, "setRadialPosition", double.class)));
424 setters.put("MassObject:radialdirection", new DoubleSetter(
425 Reflection.findMethod(MassObject.class, "setRadialDirection", double.class),
429 setters.put("MassComponent:mass", new DoubleSetter(
430 Reflection.findMethod(MassComponent.class, "setComponentMass", double.class)));
433 setters.put("ShockCord:cordlength", new DoubleSetter(
434 Reflection.findMethod(ShockCord.class, "setCordLength", double.class)));
435 setters.put("ShockCord:material", new MaterialSetter(
436 Reflection.findMethod(ShockCord.class, "setMaterial", Material.class),
437 Material.Type.LINE));
440 setters.put("RecoveryDevice:cd", new DoubleSetter(
441 Reflection.findMethod(RecoveryDevice.class, "setCD", double.class),
443 Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
444 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
445 Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
446 RecoveryDevice.DeployEvent.class));
447 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
448 Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class)));
449 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
450 Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class)));
451 setters.put("RecoveryDevice:material", new MaterialSetter(
452 Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class),
453 Material.Type.SURFACE));
456 setters.put("Parachute:diameter", new DoubleSetter(
457 Reflection.findMethod(Parachute.class, "setDiameter", double.class)));
458 setters.put("Parachute:linecount", new IntSetter(
459 Reflection.findMethod(Parachute.class, "setLineCount", int.class)));
460 setters.put("Parachute:linelength", new DoubleSetter(
461 Reflection.findMethod(Parachute.class, "setLineLength", double.class)));
462 setters.put("Parachute:linematerial", new MaterialSetter(
463 Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class),
464 Material.Type.LINE));
467 setters.put("Streamer:striplength", new DoubleSetter(
468 Reflection.findMethod(Streamer.class, "setStripLength", double.class)));
469 setters.put("Streamer:stripwidth", new DoubleSetter(
470 Reflection.findMethod(Streamer.class, "setStripWidth", double.class)));
473 // <motorconfiguration> handled by separate handler
474 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
475 Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class),
476 ReferenceType.class));
477 setters.put("Rocket:customreference", new DoubleSetter(
478 Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class)));
479 setters.put("Rocket:designer", new StringSetter(
480 Reflection.findMethod(Rocket.class, "setDesigner", String.class)));
481 setters.put("Rocket:revision", new StringSetter(
482 Reflection.findMethod(Rocket.class, "setRevision", String.class)));
485 setters.put("Stage:separationevent", new EnumSetter<Stage.SeparationEvent>(
486 Reflection.findMethod(Stage.class, "setSeparationEvent", Stage.SeparationEvent.class),
487 Stage.SeparationEvent.class));
488 setters.put("Stage:separationdelay", new DoubleSetter(
489 Reflection.findMethod(Stage.class, "setSeparationDelay", double.class)));
495 * Search for a enum value that has the corresponding name as an XML value. The current
496 * conversion from enum name to XML value is to lowercase the name and strip out all
497 * underscore characters. This method returns a match to these criteria, or <code>null</code>
498 * if no such enum exists.
500 * @param <T> then enum type.
501 * @param name the XML value, null ok.
502 * @param enumClass the class of the enum.
503 * @return the found enum value, or <code>null</code>.
505 public static <T extends Enum<T>> Enum<T> findEnum(String name,
506 Class<? extends Enum<T>> enumClass) {
511 for (Enum<T> e : enumClass.getEnumConstants()) {
512 if (e.name().toLowerCase(Locale.ENGLISH).replace("_", "").equals(name)) {
521 * Convert a string to a double including formatting specifications of the OpenRocket
522 * file format. This accepts all formatting that is valid for
523 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
525 * @param s the string to parse.
526 * @return the numerical value.
527 * @throws NumberFormatException the the string cannot be parsed.
529 public static double stringToDouble(String s) throws NumberFormatException {
531 throw new NumberFormatException("null string");
532 if (s.equalsIgnoreCase("NaN"))
534 if (s.equalsIgnoreCase("Inf"))
535 return Double.POSITIVE_INFINITY;
536 if (s.equalsIgnoreCase("-Inf"))
537 return Double.NEGATIVE_INFINITY;
538 return Double.parseDouble(s);
547 * The starting point of the handlers. Accepts a single <openrocket> element and hands
548 * the contents to be read by a OpenRocketContentsHandler.
550 class OpenRocketHandler extends AbstractElementHandler {
551 private final DocumentLoadingContext context;
552 private OpenRocketContentHandler handler = null;
554 public OpenRocketHandler(DocumentLoadingContext context) {
555 this.context = context;
559 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
560 * has not been read yet.
562 * @return the document read, or null.
564 public OpenRocketDocument getDocument() {
565 return handler.getDocument();
569 public ElementHandler openElement(String element, HashMap<String, String> attributes,
570 WarningSet warnings) {
572 // Check for unknown elements
573 if (!element.equals("openrocket")) {
574 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
578 // Check for first call
579 if (handler != null) {
580 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
585 // Check version number
586 String version = null;
587 String creator = attributes.remove("creator");
588 String docVersion = attributes.remove("version");
589 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
590 if (v.equals(docVersion)) {
595 if (version == null) {
596 String str = "Unsupported document version";
597 if (docVersion != null)
598 str += " " + docVersion;
599 if (creator != null && !creator.trim().equals(""))
600 str += " (written using '" + creator.trim() + "')";
601 str += ", attempting to read file anyway.";
605 context.setFileVersion(parseVersion(docVersion));
607 handler = new OpenRocketContentHandler(context);
612 private int parseVersion(String docVersion) {
613 if (docVersion == null)
616 Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion);
618 int major = Integer.parseInt(m.group(1));
619 int minor = Integer.parseInt(m.group(2));
620 return major * DocumentConfig.FILE_VERSION_DIVISOR + minor;
627 public void closeElement(String element, HashMap<String, String> attributes,
628 String content, WarningSet warnings) throws SAXException {
629 attributes.remove("version");
630 attributes.remove("creator");
631 super.closeElement(element, attributes, content, warnings);
639 * Handles the content of the <openrocket> tag.
641 class OpenRocketContentHandler extends AbstractElementHandler {
642 private final DocumentLoadingContext context;
643 private final OpenRocketDocument doc;
644 private final Rocket rocket;
646 private boolean rocketDefined = false;
647 private boolean simulationsDefined = false;
649 public OpenRocketContentHandler(DocumentLoadingContext context) {
650 this.context = context;
651 this.rocket = new Rocket();
652 this.doc = new OpenRocketDocument(rocket);
656 public OpenRocketDocument getDocument() {
663 public ElementHandler openElement(String element, HashMap<String, String> attributes,
664 WarningSet warnings) {
666 if (element.equals("rocket")) {
669 .fromString("Multiple rocket designs within one document, "
670 + "ignoring later ones."));
673 rocketDefined = true;
674 return new ComponentParameterHandler(rocket, context);
677 if (element.equals("simulations")) {
678 if (simulationsDefined) {
680 .fromString("Multiple simulation definitions within one document, "
681 + "ignoring later ones."));
684 simulationsDefined = true;
685 return new SimulationsHandler(doc, context);
688 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
698 * A handler that creates components from the corresponding elements. The control of the
699 * contents is passed on to ComponentParameterHandler.
701 class ComponentHandler extends AbstractElementHandler {
702 private final DocumentLoadingContext context;
703 private final RocketComponent parent;
705 public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) {
706 this.parent = parent;
707 this.context = context;
711 public ElementHandler openElement(String element, HashMap<String, String> attributes,
712 WarningSet warnings) {
714 // Attempt to construct new component
715 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
717 if (constructor == null) {
718 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
724 c = constructor.newInstance();
725 } catch (InstantiationException e) {
726 throw new BugException("Error constructing component.", e);
727 } catch (IllegalAccessException e) {
728 throw new BugException("Error constructing component.", e);
729 } catch (InvocationTargetException e) {
730 throw Reflection.handleWrappedException(e);
735 return new ComponentParameterHandler(c, context);
741 * A handler that populates the parameters of a previously constructed rocket component.
742 * This uses the setters, or delegates the handling to another handler for specific
745 class ComponentParameterHandler extends AbstractElementHandler {
746 private final DocumentLoadingContext context;
747 private final RocketComponent component;
749 public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) {
751 this.context = context;
755 public ElementHandler openElement(String element, HashMap<String, String> attributes,
756 WarningSet warnings) {
758 // Check for specific elements that contain other elements
759 if (element.equals("subcomponents")) {
760 return new ComponentHandler(component, context);
762 if (element.equals("motormount")) {
763 if (!(component instanceof MotorMount)) {
764 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
767 return new MotorMountHandler((MotorMount) component, context);
769 if (element.equals("finpoints")) {
770 if (!(component instanceof FreeformFinSet)) {
771 warnings.add(Warning.fromString("Illegal component defined for fin points."));
774 return new FinSetPointHandler((FreeformFinSet) component, context);
776 if (element.equals("motorconfiguration")) {
777 if (!(component instanceof Rocket)) {
778 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
781 return new MotorConfigurationHandler((Rocket) component, context);
785 return PlainTextHandler.INSTANCE;
789 public void closeElement(String element, HashMap<String, String> attributes,
790 String content, WarningSet warnings) {
792 if (element.equals("subcomponents") || element.equals("motormount") ||
793 element.equals("finpoints") || element.equals("motorconfiguration")) {
797 // Search for the correct setter class
800 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
801 String setterKey = c.getSimpleName() + ":" + element;
802 Setter s = DocumentConfig.setters.get(setterKey);
805 s.set(component, content, attributes, warnings);
808 if (DocumentConfig.setters.containsKey(setterKey)) {
809 // Key exists but is null -> invalid parameter
815 warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for "
816 + component.getComponentName() + ", ignoring."));
823 * A handler that reads the <point> specifications within the freeformfinset's
824 * <finpoints> elements.
826 class FinSetPointHandler extends AbstractElementHandler {
827 @SuppressWarnings("unused")
828 private final DocumentLoadingContext context;
829 private final FreeformFinSet finset;
830 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
832 public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) {
833 this.finset = finset;
834 this.context = context;
838 public ElementHandler openElement(String element, HashMap<String, String> attributes,
839 WarningSet warnings) {
840 return PlainTextHandler.INSTANCE;
845 public void closeElement(String element, HashMap<String, String> attributes,
846 String content, WarningSet warnings) throws SAXException {
848 String strx = attributes.remove("x");
849 String stry = attributes.remove("y");
850 if (strx == null || stry == null) {
851 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
855 double x = Double.parseDouble(strx);
856 double y = Double.parseDouble(stry);
857 coordinates.add(new Coordinate(x, y));
858 } catch (NumberFormatException e) {
859 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
863 super.closeElement(element, attributes, content, warnings);
867 public void endHandler(String element, HashMap<String, String> attributes,
868 String content, WarningSet warnings) {
870 finset.setPoints(coordinates.toArray(new Coordinate[0]));
871 } catch (IllegalFinPointException e) {
872 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
878 class MotorMountHandler extends AbstractElementHandler {
879 private final DocumentLoadingContext context;
880 private final MotorMount mount;
881 private MotorHandler motorHandler;
883 public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) {
885 this.context = context;
886 mount.setMotorMount(true);
890 public ElementHandler openElement(String element, HashMap<String, String> attributes,
891 WarningSet warnings) {
893 if (element.equals("motor")) {
894 motorHandler = new MotorHandler(context);
898 if (element.equals("ignitionevent") ||
899 element.equals("ignitiondelay") ||
900 element.equals("overhang")) {
901 return PlainTextHandler.INSTANCE;
904 warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring."));
911 public void closeElement(String element, HashMap<String, String> attributes,
912 String content, WarningSet warnings) throws SAXException {
914 if (element.equals("motor")) {
915 String id = attributes.get("configid");
916 if (id == null || id.equals("")) {
917 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
921 Motor motor = motorHandler.getMotor(warnings);
922 mount.setMotor(id, motor);
923 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
927 if (element.equals("ignitionevent")) {
928 MotorMount.IgnitionEvent event = null;
929 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
930 if (e.name().toLowerCase(Locale.ENGLISH).replaceAll("_", "").equals(content)) {
936 warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring."));
939 mount.setIgnitionEvent(event);
943 if (element.equals("ignitiondelay")) {
946 d = Double.parseDouble(content);
947 } catch (NumberFormatException nfe) {
948 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
951 mount.setIgnitionDelay(d);
955 if (element.equals("overhang")) {
958 d = Double.parseDouble(content);
959 } catch (NumberFormatException nfe) {
960 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
963 mount.setMotorOverhang(d);
967 super.closeElement(element, attributes, content, warnings);
974 class MotorConfigurationHandler extends AbstractElementHandler {
975 @SuppressWarnings("unused")
976 private final DocumentLoadingContext context;
977 private final Rocket rocket;
978 private String name = null;
979 private boolean inNameElement = false;
981 public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) {
982 this.rocket = rocket;
983 this.context = context;
987 public ElementHandler openElement(String element, HashMap<String, String> attributes,
988 WarningSet warnings) {
990 if (inNameElement || !element.equals("name")) {
991 warnings.add(Warning.FILE_INVALID_PARAMETER);
994 inNameElement = true;
996 return PlainTextHandler.INSTANCE;
1000 public void closeElement(String element, HashMap<String, String> attributes,
1001 String content, WarningSet warnings) {
1006 public void endHandler(String element, HashMap<String, String> attributes,
1007 String content, WarningSet warnings) throws SAXException {
1009 String configid = attributes.remove("configid");
1010 if (configid == null || configid.equals("")) {
1011 warnings.add(Warning.FILE_INVALID_PARAMETER);
1015 if (!rocket.addMotorConfigurationID(configid)) {
1016 warnings.add("Duplicate motor configuration ID used.");
1020 if (name != null && name.trim().length() > 0) {
1021 rocket.setMotorConfigurationName(configid, name);
1024 if ("true".equals(attributes.remove("default"))) {
1025 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
1028 super.closeElement(element, attributes, content, warnings);
1033 class MotorHandler extends AbstractElementHandler {
1034 /** File version where latest digest format was introduced */
1035 private static final int MOTOR_DIGEST_VERSION = 104;
1037 private final DocumentLoadingContext context;
1038 private Motor.Type type = null;
1039 private String manufacturer = null;
1040 private String designation = null;
1041 private String digest = null;
1042 private double diameter = Double.NaN;
1043 private double length = Double.NaN;
1044 private double delay = Double.NaN;
1046 public MotorHandler(DocumentLoadingContext context) {
1047 this.context = context;
1052 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1053 WarningSet warnings) {
1054 return PlainTextHandler.INSTANCE;
1059 * Return the motor to use, or null.
1061 public Motor getMotor(WarningSet warnings) {
1062 return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings);
1066 * Return the delay to use for the motor.
1068 public double getDelay(WarningSet warnings) {
1069 if (Double.isNaN(delay)) {
1070 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1071 return Motor.PLUGGED;
1078 public void closeElement(String element, HashMap<String, String> attributes,
1079 String content, WarningSet warnings) throws SAXException {
1081 content = content.trim();
1083 if (element.equals("type")) {
1087 for (Motor.Type t : Motor.Type.values()) {
1088 if (t.name().toLowerCase(Locale.ENGLISH).equals(content.trim())) {
1094 warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring."));
1097 } else if (element.equals("manufacturer")) {
1100 manufacturer = content.trim();
1102 } else if (element.equals("designation")) {
1105 designation = content.trim();
1107 } else if (element.equals("digest")) {
1109 // Digest is used only for file versions saved using the same digest algorithm
1110 if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) {
1111 digest = content.trim();
1114 } else if (element.equals("diameter")) {
1117 diameter = Double.NaN;
1119 diameter = Double.parseDouble(content.trim());
1120 } catch (NumberFormatException e) {
1123 if (Double.isNaN(diameter)) {
1124 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1127 } else if (element.equals("length")) {
1130 length = Double.NaN;
1132 length = Double.parseDouble(content.trim());
1133 } catch (NumberFormatException ignore) {
1136 if (Double.isNaN(length)) {
1137 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1140 } else if (element.equals("delay")) {
1144 if (content.equals("none")) {
1145 delay = Motor.PLUGGED;
1148 delay = Double.parseDouble(content.trim());
1149 } catch (NumberFormatException ignore) {
1152 if (Double.isNaN(delay)) {
1153 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1159 super.closeElement(element, attributes, content, warnings);
1167 class SimulationsHandler extends AbstractElementHandler {
1168 private final DocumentLoadingContext context;
1169 private final OpenRocketDocument doc;
1170 private SingleSimulationHandler handler;
1172 public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1174 this.context = context;
1178 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1179 WarningSet warnings) {
1181 if (!element.equals("simulation")) {
1182 warnings.add("Unknown element '" + element + "', ignoring.");
1186 handler = new SingleSimulationHandler(doc, context);
1191 public void closeElement(String element, HashMap<String, String> attributes,
1192 String content, WarningSet warnings) throws SAXException {
1193 attributes.remove("status");
1194 super.closeElement(element, attributes, content, warnings);
1200 class SingleSimulationHandler extends AbstractElementHandler {
1201 private final DocumentLoadingContext context;
1203 private final OpenRocketDocument doc;
1205 private String name;
1207 private SimulationConditionsHandler conditionHandler;
1208 private FlightDataHandler dataHandler;
1210 private final List<String> listeners = new ArrayList<String>();
1212 public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) {
1214 this.context = context;
1220 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1221 WarningSet warnings) {
1223 if (element.equals("name") || element.equals("simulator") ||
1224 element.equals("calculator") || element.equals("listener")) {
1225 return PlainTextHandler.INSTANCE;
1226 } else if (element.equals("conditions")) {
1227 conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context);
1228 return conditionHandler;
1229 } else if (element.equals("flightdata")) {
1230 dataHandler = new FlightDataHandler(context);
1233 warnings.add("Unknown element '" + element + "', ignoring.");
1239 public void closeElement(String element, HashMap<String, String> attributes,
1240 String content, WarningSet warnings) {
1242 if (element.equals("name")) {
1244 } else if (element.equals("simulator")) {
1245 if (!content.trim().equals("RK4Simulator")) {
1246 warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring.");
1248 } else if (element.equals("calculator")) {
1249 if (!content.trim().equals("BarrowmanCalculator")) {
1250 warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring.");
1252 } else if (element.equals("listener") && content.trim().length() > 0) {
1253 listeners.add(content.trim());
1259 public void endHandler(String element, HashMap<String, String> attributes,
1260 String content, WarningSet warnings) {
1262 String s = attributes.get("status");
1263 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1264 if (status == null) {
1265 warnings.add("Simulation status unknown, assuming outdated.");
1266 status = Simulation.Status.OUTDATED;
1269 SimulationOptions conditions;
1270 if (conditionHandler != null) {
1271 conditions = conditionHandler.getConditions();
1273 warnings.add("Simulation conditions not defined, using defaults.");
1274 conditions = new SimulationOptions(doc.getRocket());
1278 name = "Simulation";
1281 if (dataHandler == null)
1284 data = dataHandler.getFlightData();
1286 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1287 conditions, listeners, data);
1289 doc.addSimulation(simulation);
1295 class SimulationConditionsHandler extends AbstractElementHandler {
1296 private final DocumentLoadingContext context;
1297 private SimulationOptions conditions;
1298 private AtmosphereHandler atmosphereHandler;
1300 public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) {
1301 this.context = context;
1302 conditions = new SimulationOptions(rocket);
1303 // Set up default loading settings (which may differ from the new defaults)
1304 conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT);
1307 public SimulationOptions getConditions() {
1312 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1313 WarningSet warnings) {
1314 if (element.equals("atmosphere")) {
1315 atmosphereHandler = new AtmosphereHandler(attributes.get("model"), context);
1316 return atmosphereHandler;
1318 return PlainTextHandler.INSTANCE;
1322 public void closeElement(String element, HashMap<String, String> attributes,
1323 String content, WarningSet warnings) {
1325 double d = Double.NaN;
1327 d = Double.parseDouble(content);
1328 } catch (NumberFormatException ignore) {
1332 if (element.equals("configid")) {
1333 if (content.equals("")) {
1334 conditions.setMotorConfigurationID(null);
1336 conditions.setMotorConfigurationID(content);
1338 } else if (element.equals("launchrodlength")) {
1339 if (Double.isNaN(d)) {
1340 warnings.add("Illegal launch rod length defined, ignoring.");
1342 conditions.setLaunchRodLength(d);
1344 } else if (element.equals("launchrodangle")) {
1345 if (Double.isNaN(d)) {
1346 warnings.add("Illegal launch rod angle defined, ignoring.");
1348 conditions.setLaunchRodAngle(d * Math.PI / 180);
1350 } else if (element.equals("launchroddirection")) {
1351 if (Double.isNaN(d)) {
1352 warnings.add("Illegal launch rod direction defined, ignoring.");
1354 conditions.setLaunchRodDirection(d * Math.PI / 180);
1356 } else if (element.equals("windaverage")) {
1357 if (Double.isNaN(d)) {
1358 warnings.add("Illegal average windspeed defined, ignoring.");
1360 conditions.setWindSpeedAverage(d);
1362 } else if (element.equals("windturbulence")) {
1363 if (Double.isNaN(d)) {
1364 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1366 conditions.setWindTurbulenceIntensity(d);
1368 } else if (element.equals("launchaltitude")) {
1369 if (Double.isNaN(d)) {
1370 warnings.add("Illegal launch altitude defined, ignoring.");
1372 conditions.setLaunchAltitude(d);
1374 } else if (element.equals("launchlatitude")) {
1375 if (Double.isNaN(d)) {
1376 warnings.add("Illegal launch latitude defined, ignoring.");
1378 conditions.setLaunchLatitude(d);
1380 } else if (element.equals("launchlongitude")) {
1381 if (Double.isNaN(d)) {
1382 warnings.add("Illegal launch longitude.");
1384 conditions.setLaunchLongitude(d);
1386 } else if (element.equals("geodeticmethod")) {
1387 GeodeticComputationStrategy gcs =
1388 (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class);
1390 conditions.setGeodeticComputation(gcs);
1392 warnings.add("Unknown geodetic computation method '" + content + "'");
1394 } else if (element.equals("atmosphere")) {
1395 atmosphereHandler.storeSettings(conditions, warnings);
1396 } else if (element.equals("timestep")) {
1397 if (Double.isNaN(d)) {
1398 warnings.add("Illegal time step defined, ignoring.");
1400 conditions.setTimeStep(d);
1407 class AtmosphereHandler extends AbstractElementHandler {
1408 @SuppressWarnings("unused")
1409 private final DocumentLoadingContext context;
1410 private final String model;
1411 private double temperature = Double.NaN;
1412 private double pressure = Double.NaN;
1414 public AtmosphereHandler(String model, DocumentLoadingContext context) {
1416 this.context = context;
1420 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1421 WarningSet warnings) {
1422 return PlainTextHandler.INSTANCE;
1426 public void closeElement(String element, HashMap<String, String> attributes,
1427 String content, WarningSet warnings) throws SAXException {
1429 double d = Double.NaN;
1431 d = Double.parseDouble(content);
1432 } catch (NumberFormatException ignore) {
1435 if (element.equals("basetemperature")) {
1436 if (Double.isNaN(d)) {
1437 warnings.add("Illegal base temperature specified, ignoring.");
1440 } else if (element.equals("basepressure")) {
1441 if (Double.isNaN(d)) {
1442 warnings.add("Illegal base pressure specified, ignoring.");
1446 super.closeElement(element, attributes, content, warnings);
1451 public void storeSettings(SimulationOptions cond, WarningSet warnings) {
1452 if (!Double.isNaN(pressure)) {
1453 cond.setLaunchPressure(pressure);
1455 if (!Double.isNaN(temperature)) {
1456 cond.setLaunchTemperature(temperature);
1459 if ("isa".equals(model)) {
1460 cond.setISAAtmosphere(true);
1461 } else if ("extendedisa".equals(model)) {
1462 cond.setISAAtmosphere(false);
1464 cond.setISAAtmosphere(true);
1465 warnings.add("Unknown atmospheric model, using ISA.");
1472 class FlightDataHandler extends AbstractElementHandler {
1473 private final DocumentLoadingContext context;
1475 private FlightDataBranchHandler dataHandler;
1476 private WarningSet warningSet = new WarningSet();
1477 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1479 private FlightData data;
1482 public FlightDataHandler(DocumentLoadingContext context) {
1483 this.context = context;
1486 public FlightData getFlightData() {
1491 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1492 WarningSet warnings) {
1494 if (element.equals("warning")) {
1495 return PlainTextHandler.INSTANCE;
1497 if (element.equals("databranch")) {
1498 if (attributes.get("name") == null || attributes.get("types") == null) {
1499 warnings.add("Illegal flight data definition, ignoring.");
1502 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1503 attributes.get("types"), context);
1507 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1513 public void closeElement(String element, HashMap<String, String> attributes,
1514 String content, WarningSet warnings) {
1516 if (element.equals("databranch")) {
1517 FlightDataBranch branch = dataHandler.getBranch();
1518 if (branch.getLength() > 0) {
1519 branches.add(branch);
1521 } else if (element.equals("warning")) {
1522 warningSet.add(Warning.fromString(content));
1528 public void endHandler(String element, HashMap<String, String> attributes,
1529 String content, WarningSet warnings) {
1531 if (branches.size() > 0) {
1532 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1534 double maxAltitude = Double.NaN;
1535 double maxVelocity = Double.NaN;
1536 double maxAcceleration = Double.NaN;
1537 double maxMach = Double.NaN;
1538 double timeToApogee = Double.NaN;
1539 double flightTime = Double.NaN;
1540 double groundHitVelocity = Double.NaN;
1541 double launchRodVelocity = Double.NaN;
1542 double deploymentVelocity = Double.NaN;
1545 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1546 } catch (NumberFormatException ignore) {
1549 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1550 } catch (NumberFormatException ignore) {
1553 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1554 } catch (NumberFormatException ignore) {
1557 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1558 } catch (NumberFormatException ignore) {
1561 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1562 } catch (NumberFormatException ignore) {
1565 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1566 } catch (NumberFormatException ignore) {
1570 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1571 } catch (NumberFormatException ignore) {
1574 launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity"));
1575 } catch (NumberFormatException ignore) {
1578 deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity"));
1579 } catch (NumberFormatException ignore) {
1582 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1583 timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity);
1586 data.getWarningSet().addAll(warningSet);
1594 class FlightDataBranchHandler extends AbstractElementHandler {
1595 @SuppressWarnings("unused")
1596 private final DocumentLoadingContext context;
1597 private final FlightDataType[] types;
1598 private final FlightDataBranch branch;
1600 public FlightDataBranchHandler(String name, String typeList, DocumentLoadingContext context) {
1601 this.context = context;
1602 String[] split = typeList.split(",");
1603 types = new FlightDataType[split.length];
1604 for (int i = 0; i < split.length; i++) {
1605 types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE);
1608 // TODO: LOW: May throw an IllegalArgumentException
1609 branch = new FlightDataBranch(name, types);
1612 public FlightDataBranch getBranch() {
1618 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1619 WarningSet warnings) {
1621 if (element.equals("datapoint"))
1622 return PlainTextHandler.INSTANCE;
1623 if (element.equals("event"))
1624 return PlainTextHandler.INSTANCE;
1626 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1632 public void closeElement(String element, HashMap<String, String> attributes,
1633 String content, WarningSet warnings) {
1635 if (element.equals("event")) {
1637 FlightEvent.Type type;
1640 time = DocumentConfig.stringToDouble(attributes.get("time"));
1641 } catch (NumberFormatException e) {
1642 warnings.add("Illegal event specification, ignoring.");
1646 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1648 warnings.add("Illegal event specification, ignoring.");
1652 branch.addEvent(new FlightEvent(type, time));
1656 if (!element.equals("datapoint")) {
1657 warnings.add("Unknown element '" + element + "' encountered, ignoring.");
1661 // element == "datapoint"
1664 // Check line format
1665 String[] split = content.split(",");
1666 if (split.length != types.length) {
1667 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1671 // Parse the doubles
1672 double[] values = new double[split.length];
1673 for (int i = 0; i < values.length; i++) {
1675 values[i] = DocumentConfig.stringToDouble(split[i]);
1676 } catch (NumberFormatException e) {
1677 warnings.add("Data point format error, ignoring point.");
1682 // Add point to branch
1684 for (int i = 0; i < types.length; i++) {
1685 branch.setValue(types[i], values[i]);
1694 ///////////////// Setters implementation
1700 * Set the specified value to the given component.
1702 * @param component the component to which to set.
1703 * @param value the value within the element.
1704 * @param attributes attributes for the element.
1705 * @param warnings the warning set to use.
1707 public void set(RocketComponent component, String value,
1708 HashMap<String, String> attributes, WarningSet warnings);
1712 //// StringSetter - sets the value to the contained String
1713 class StringSetter implements Setter {
1714 private final Reflection.Method setMethod;
1716 public StringSetter(Reflection.Method set) {
1721 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1722 WarningSet warnings) {
1723 setMethod.invoke(c, s);
1727 //// IntSetter - set an integer value
1728 class IntSetter implements Setter {
1729 private final Reflection.Method setMethod;
1731 public IntSetter(Reflection.Method set) {
1736 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1737 WarningSet warnings) {
1739 int n = Integer.parseInt(s);
1740 setMethod.invoke(c, n);
1741 } catch (NumberFormatException e) {
1742 warnings.add(Warning.FILE_INVALID_PARAMETER);
1748 //// BooleanSetter - set a boolean value
1749 class BooleanSetter implements Setter {
1750 private final Reflection.Method setMethod;
1752 public BooleanSetter(Reflection.Method set) {
1757 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1758 WarningSet warnings) {
1761 if (s.equalsIgnoreCase("true")) {
1762 setMethod.invoke(c, true);
1763 } else if (s.equalsIgnoreCase("false")) {
1764 setMethod.invoke(c, false);
1766 warnings.add(Warning.FILE_INVALID_PARAMETER);
1773 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1774 //// calls a setXXX(boolean) method.
1775 class DoubleSetter implements Setter {
1776 private final Reflection.Method setMethod;
1777 private final String specialString;
1778 private final Reflection.Method specialMethod;
1779 private final double multiplier;
1782 * Set only the double value.
1783 * @param set set method for the double value.
1785 public DoubleSetter(Reflection.Method set) {
1786 this.setMethod = set;
1787 this.specialString = null;
1788 this.specialMethod = null;
1789 this.multiplier = 1.0;
1793 * Multiply with the given multiplier and set the double value.
1794 * @param set set method for the double value.
1795 * @param mul multiplier.
1797 public DoubleSetter(Reflection.Method set, double mul) {
1798 this.setMethod = set;
1799 this.specialString = null;
1800 this.specialMethod = null;
1801 this.multiplier = mul;
1805 * Set the double value, or if the value equals the special string, use the
1806 * special setter and set it to true.
1808 * @param set double setter.
1809 * @param special special string
1810 * @param specialMethod boolean setter.
1812 public DoubleSetter(Reflection.Method set, String special,
1813 Reflection.Method specialMethod) {
1814 this.setMethod = set;
1815 this.specialString = special;
1816 this.specialMethod = specialMethod;
1817 this.multiplier = 1.0;
1822 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1823 WarningSet warnings) {
1827 // Check for special case
1828 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1829 specialMethod.invoke(c, true);
1835 double d = Double.parseDouble(s);
1836 setMethod.invoke(c, d * multiplier);
1837 } catch (NumberFormatException e) {
1838 warnings.add(Warning.FILE_INVALID_PARAMETER);
1844 class OverrideSetter implements Setter {
1845 private final Reflection.Method setMethod;
1846 private final Reflection.Method enabledMethod;
1848 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1849 this.setMethod = set;
1850 this.enabledMethod = enabledMethod;
1854 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1855 WarningSet warnings) {
1858 double d = Double.parseDouble(s);
1859 setMethod.invoke(c, d);
1860 enabledMethod.invoke(c, true);
1861 } catch (NumberFormatException e) {
1862 warnings.add(Warning.FILE_INVALID_PARAMETER);
1867 //// EnumSetter - sets a generic enum type
1868 class EnumSetter<T extends Enum<T>> implements Setter {
1869 private final Reflection.Method setter;
1870 private final Class<T> enumClass;
1872 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1874 this.enumClass = enumClass;
1878 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1879 WarningSet warnings) {
1881 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1882 if (setEnum == null) {
1883 warnings.add(Warning.FILE_INVALID_PARAMETER);
1887 setter.invoke(c, setEnum);
1892 //// ColorSetter - sets a Color value
1893 class ColorSetter implements Setter {
1894 private final Reflection.Method setMethod;
1896 public ColorSetter(Reflection.Method set) {
1901 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1902 WarningSet warnings) {
1904 String red = attributes.get("red");
1905 String green = attributes.get("green");
1906 String blue = attributes.get("blue");
1908 if (red == null || green == null || blue == null) {
1909 warnings.add(Warning.FILE_INVALID_PARAMETER);
1915 r = Integer.parseInt(red);
1916 g = Integer.parseInt(green);
1917 b = Integer.parseInt(blue);
1918 } catch (NumberFormatException e) {
1919 warnings.add(Warning.FILE_INVALID_PARAMETER);
1923 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1924 warnings.add(Warning.FILE_INVALID_PARAMETER);
1928 Color color = new Color(r, g, b);
1929 setMethod.invoke(c, color);
1931 if (!s.trim().equals("")) {
1932 warnings.add(Warning.FILE_INVALID_PARAMETER);
1939 class MaterialSetter implements Setter {
1940 private final Reflection.Method setMethod;
1941 private final Material.Type type;
1943 public MaterialSetter(Reflection.Method set, Material.Type type) {
1944 this.setMethod = set;
1949 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1950 WarningSet warnings) {
1956 if (name.equals("")) {
1957 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1964 str = attributes.remove("density");
1966 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1970 density = Double.parseDouble(str);
1971 } catch (NumberFormatException e) {
1972 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1977 // double thickness = 0;
1978 // str = attributes.remove("thickness");
1981 // thickness = Double.parseDouble(str);
1982 // } catch (NumberFormatException e){
1983 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
1987 // Check type if specified
1988 str = attributes.remove("type");
1989 if (str != null && !type.name().toLowerCase(Locale.ENGLISH).equals(str)) {
1990 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
1994 mat = Databases.findMaterial(type, name, density, false);
1996 setMethod.invoke(c, mat);
2003 class PositionSetter implements Setter {
2006 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
2007 WarningSet warnings) {
2009 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
2010 RocketComponent.Position.class);
2012 warnings.add(Warning.FILE_INVALID_PARAMETER);
2018 pos = Double.parseDouble(value);
2019 } catch (NumberFormatException e) {
2020 warnings.add(Warning.FILE_INVALID_PARAMETER);
2024 if (c instanceof FinSet) {
2025 ((FinSet) c).setRelativePosition(type);
2026 c.setPositionValue(pos);
2027 } else if (c instanceof LaunchLug) {
2028 ((LaunchLug) c).setRelativePosition(type);
2029 c.setPositionValue(pos);
2030 } else if (c instanceof InternalComponent) {
2031 ((InternalComponent) c).setRelativePosition(type);
2032 c.setPositionValue(pos);
2034 warnings.add(Warning.FILE_INVALID_PARAMETER);
2041 class FinTabPositionSetter extends DoubleSetter {
2043 public FinTabPositionSetter() {
2044 super(Reflection.findMethod(FinSet.class, "setTabShift", double.class));
2048 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
2049 WarningSet warnings) {
2051 if (!(c instanceof FinSet)) {
2052 throw new IllegalStateException("FinTabPositionSetter called for component " + c);
2055 String relative = attributes.get("relativeto");
2056 FinSet.TabRelativePosition position =
2057 (TabRelativePosition) DocumentConfig.findEnum(relative,
2058 FinSet.TabRelativePosition.class);
2060 if (position != null) {
2062 ((FinSet) c).setTabRelativePosition(position);
2065 if (relative == null) {
2066 warnings.add("Required attribute 'relativeto' not found for fin tab position.");
2068 warnings.add("Illegal attribute value '" + relative + "' encountered.");
2072 super.set(c, s, attributes, warnings);
2079 class ClusterConfigurationSetter implements Setter {
2082 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2083 WarningSet warnings) {
2085 if (!(component instanceof Clusterable)) {
2086 warnings.add("Illegal component defined as cluster.");
2090 ClusterConfiguration config = null;
2091 for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) {
2092 if (c.getXMLName().equals(value)) {
2098 if (config == null) {
2099 warnings.add("Illegal cluster configuration specified.");
2103 ((Clusterable) component).setClusterConfiguration(config);