1 package net.sf.openrocket.file;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.lang.reflect.Constructor;
7 import java.lang.reflect.InvocationTargetException;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.List;
11 import java.util.Stack;
13 import net.sf.openrocket.aerodynamics.Warning;
14 import net.sf.openrocket.aerodynamics.WarningSet;
15 import net.sf.openrocket.database.Databases;
16 import net.sf.openrocket.document.OpenRocketDocument;
17 import net.sf.openrocket.document.Simulation;
18 import net.sf.openrocket.document.StorageOptions;
19 import net.sf.openrocket.document.Simulation.Status;
20 import net.sf.openrocket.material.Material;
21 import net.sf.openrocket.rocketcomponent.BodyComponent;
22 import net.sf.openrocket.rocketcomponent.BodyTube;
23 import net.sf.openrocket.rocketcomponent.Bulkhead;
24 import net.sf.openrocket.rocketcomponent.CenteringRing;
25 import net.sf.openrocket.rocketcomponent.ClusterConfiguration;
26 import net.sf.openrocket.rocketcomponent.Clusterable;
27 import net.sf.openrocket.rocketcomponent.EllipticalFinSet;
28 import net.sf.openrocket.rocketcomponent.EngineBlock;
29 import net.sf.openrocket.rocketcomponent.ExternalComponent;
30 import net.sf.openrocket.rocketcomponent.FinSet;
31 import net.sf.openrocket.rocketcomponent.FreeformFinSet;
32 import net.sf.openrocket.rocketcomponent.IllegalFinPointException;
33 import net.sf.openrocket.rocketcomponent.InnerTube;
34 import net.sf.openrocket.rocketcomponent.InternalComponent;
35 import net.sf.openrocket.rocketcomponent.LaunchLug;
36 import net.sf.openrocket.rocketcomponent.MassComponent;
37 import net.sf.openrocket.rocketcomponent.MassObject;
38 import net.sf.openrocket.rocketcomponent.Motor;
39 import net.sf.openrocket.rocketcomponent.MotorMount;
40 import net.sf.openrocket.rocketcomponent.NoseCone;
41 import net.sf.openrocket.rocketcomponent.Parachute;
42 import net.sf.openrocket.rocketcomponent.RadiusRingComponent;
43 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
44 import net.sf.openrocket.rocketcomponent.ReferenceType;
45 import net.sf.openrocket.rocketcomponent.RingComponent;
46 import net.sf.openrocket.rocketcomponent.Rocket;
47 import net.sf.openrocket.rocketcomponent.RocketComponent;
48 import net.sf.openrocket.rocketcomponent.ShockCord;
49 import net.sf.openrocket.rocketcomponent.Stage;
50 import net.sf.openrocket.rocketcomponent.Streamer;
51 import net.sf.openrocket.rocketcomponent.StructuralComponent;
52 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
53 import net.sf.openrocket.rocketcomponent.ThicknessRingComponent;
54 import net.sf.openrocket.rocketcomponent.Transition;
55 import net.sf.openrocket.rocketcomponent.TrapezoidFinSet;
56 import net.sf.openrocket.rocketcomponent.TubeCoupler;
57 import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish;
58 import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
59 import net.sf.openrocket.simulation.FlightData;
60 import net.sf.openrocket.simulation.FlightDataBranch;
61 import net.sf.openrocket.simulation.FlightEvent;
62 import net.sf.openrocket.simulation.SimulationConditions;
63 import net.sf.openrocket.simulation.FlightEvent.Type;
64 import net.sf.openrocket.unit.UnitGroup;
65 import net.sf.openrocket.util.Coordinate;
66 import net.sf.openrocket.util.LineStyle;
67 import net.sf.openrocket.util.Reflection;
69 import org.xml.sax.Attributes;
70 import org.xml.sax.InputSource;
71 import org.xml.sax.SAXException;
72 import org.xml.sax.XMLReader;
73 import org.xml.sax.helpers.DefaultHandler;
74 import org.xml.sax.helpers.XMLReaderFactory;
78 * Class that loads a rocket definition from an OpenRocket rocket file.
80 * This class uses SAX to read the XML file format. The
81 * {@link #loadFromStream(InputStream)} method simply sets the system up and
82 * starts the parsing, while the actual logic is in the private inner class
83 * <code>OpenRocketHandler</code>.
85 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
88 public class OpenRocketLoader extends RocketLoader {
91 public OpenRocketDocument loadFromStream(InputStream source) throws RocketLoadException,
93 InputSource xmlSource = new InputSource(source);
94 OpenRocketHandler handler = new OpenRocketHandler();
96 DelegatorHandler xmlhandler = new DelegatorHandler(handler, warnings);
99 XMLReader parser = XMLReaderFactory.createXMLReader();
100 parser.setContentHandler(xmlhandler);
101 parser.setErrorHandler(xmlhandler);
102 parser.parse(xmlSource);
103 } catch (SAXException e) {
104 throw new RocketLoadException("Malformed XML in input.", e);
108 OpenRocketDocument doc = handler.getDocument();
109 doc.getDefaultConfiguration().setAllStages();
111 // Deduce suitable time skip
112 double timeSkip = StorageOptions.SIMULATION_DATA_NONE;
113 for (Simulation s: doc.getSimulations()) {
114 if (s.getStatus() == Simulation.Status.EXTERNAL ||
115 s.getStatus() == Simulation.Status.NOT_SIMULATED)
117 if (s.getSimulatedData() == null)
119 if (s.getSimulatedData().getBranchCount() == 0)
121 FlightDataBranch branch = s.getSimulatedData().getBranch(0);
124 List<Double> list = branch.get(FlightDataBranch.TYPE_TIME);
128 double previousTime = Double.NaN;
129 for (double time: list) {
130 if (time - previousTime < timeSkip)
131 timeSkip = time-previousTime;
136 timeSkip = Math.rint(timeSkip*100)/100;
138 doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip);
139 doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed
140 doc.getDefaultStorageOptions().setExplicitlySet(false);
150 class DocumentConfig {
152 /* Remember to update OpenRocketSaver as well! */
153 public static final String[] SUPPORTED_VERSIONS = { "0.9", "1.0" };
156 //////// Component constructors
157 static final HashMap<String, Constructor<? extends RocketComponent>> constructors = new HashMap<String, Constructor<? extends RocketComponent>>();
160 // External components
161 constructors.put("bodytube", BodyTube.class.getConstructor(new Class<?>[0]));
162 constructors.put("transition", Transition.class.getConstructor(new Class<?>[0]));
163 constructors.put("nosecone", NoseCone.class.getConstructor(new Class<?>[0]));
164 constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class<?>[0]));
165 constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class<?>[0]));
166 constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class<?>[0]));
167 constructors.put("launchlug", LaunchLug.class.getConstructor(new Class<?>[0]));
169 // Internal components
170 constructors.put("engineblock", EngineBlock.class.getConstructor(new Class<?>[0]));
171 constructors.put("innertube", InnerTube.class.getConstructor(new Class<?>[0]));
172 constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class<?>[0]));
173 constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class<?>[0]));
174 constructors.put("centeringring", CenteringRing.class.getConstructor(new Class<?>[0]));
176 constructors.put("masscomponent", MassComponent.class.getConstructor(new Class<?>[0]));
177 constructors.put("shockcord", ShockCord.class.getConstructor(new Class<?>[0]));
178 constructors.put("parachute", Parachute.class.getConstructor(new Class<?>[0]));
179 constructors.put("streamer", Streamer.class.getConstructor(new Class<?>[0]));
182 constructors.put("stage", Stage.class.getConstructor(new Class<?>[0]));
184 } catch (NoSuchMethodException e) {
185 throw new RuntimeException(
186 "Error in constructing the 'constructors' HashMap.");
191 //////// Parameter setters
193 * The keys are of the form Class:param, where Class is the class name and param
194 * the element name. Setters are searched for in descending class order.
195 * A setter of null means setting the parameter is not allowed.
197 static final HashMap<String, Setter> setters = new HashMap<String, Setter>();
200 setters.put("RocketComponent:name", new StringSetter(
201 Reflection.findMethodStatic(RocketComponent.class, "setName", String.class)));
202 setters.put("RocketComponent:color", new ColorSetter(
203 Reflection.findMethodStatic(RocketComponent.class, "setColor", Color.class)));
204 setters.put("RocketComponent:linestyle", new EnumSetter<LineStyle>(
205 Reflection.findMethodStatic(RocketComponent.class, "setLineStyle", LineStyle.class),
207 setters.put("RocketComponent:position", new PositionSetter());
208 setters.put("RocketComponent:overridemass", new OverrideSetter(
209 Reflection.findMethodStatic(RocketComponent.class, "setOverrideMass", double.class),
210 Reflection.findMethodStatic(RocketComponent.class, "setMassOverridden", boolean.class)));
211 setters.put("RocketComponent:overridecg", new OverrideSetter(
212 Reflection.findMethodStatic(RocketComponent.class, "setOverrideCGX", double.class),
213 Reflection.findMethodStatic(RocketComponent.class, "setCGOverridden", boolean.class)));
214 setters.put("RocketComponent:overridesubcomponents", new BooleanSetter(
215 Reflection.findMethodStatic(RocketComponent.class, "setOverrideSubcomponents", boolean.class)));
216 setters.put("RocketComponent:comment", new StringSetter(
217 Reflection.findMethodStatic(RocketComponent.class, "setComment", String.class)));
220 setters.put("ExternalComponent:finish", new EnumSetter<Finish>(
221 Reflection.findMethodStatic(ExternalComponent.class, "setFinish", Finish.class),
223 setters.put("ExternalComponent:material", new MaterialSetter(
224 Reflection.findMethodStatic(ExternalComponent.class, "setMaterial", Material.class),
225 Material.Type.BULK));
228 setters.put("BodyComponent:length", new DoubleSetter(
229 Reflection.findMethodStatic(BodyComponent.class, "setLength", double.class)));
231 // SymmetricComponent
232 setters.put("SymmetricComponent:thickness", new DoubleSetter(
233 Reflection.findMethodStatic(SymmetricComponent.class,"setThickness", double.class),
235 Reflection.findMethodStatic(SymmetricComponent.class,"setFilled", boolean.class)));
238 setters.put("BodyTube:radius", new DoubleSetter(
239 Reflection.findMethodStatic(BodyTube.class, "setRadius", double.class),
241 Reflection.findMethodStatic(BodyTube.class,"setRadiusAutomatic", boolean.class)));
244 setters.put("Transition:shape", new EnumSetter<Transition.Shape>(
245 Reflection.findMethodStatic(Transition.class, "setType", Transition.Shape.class),
246 Transition.Shape.class));
247 setters.put("Transition:shapeclipped", new BooleanSetter(
248 Reflection.findMethodStatic(Transition.class, "setClipped", boolean.class)));
249 setters.put("Transition:shapeparameter", new DoubleSetter(
250 Reflection.findMethodStatic(Transition.class, "setShapeParameter", double.class)));
252 setters.put("Transition:foreradius", new DoubleSetter(
253 Reflection.findMethodStatic(Transition.class, "setForeRadius", double.class),
255 Reflection.findMethodStatic(Transition.class, "setForeRadiusAutomatic", boolean.class)));
256 setters.put("Transition:aftradius", new DoubleSetter(
257 Reflection.findMethodStatic(Transition.class, "setAftRadius", double.class),
259 Reflection.findMethodStatic(Transition.class, "setAftRadiusAutomatic", boolean.class)));
261 setters.put("Transition:foreshoulderradius", new DoubleSetter(
262 Reflection.findMethodStatic(Transition.class, "setForeShoulderRadius", double.class)));
263 setters.put("Transition:foreshoulderlength", new DoubleSetter(
264 Reflection.findMethodStatic(Transition.class, "setForeShoulderLength", double.class)));
265 setters.put("Transition:foreshoulderthickness", new DoubleSetter(
266 Reflection.findMethodStatic(Transition.class, "setForeShoulderThickness", double.class)));
267 setters.put("Transition:foreshouldercapped", new BooleanSetter(
268 Reflection.findMethodStatic(Transition.class, "setForeShoulderCapped", boolean.class)));
270 setters.put("Transition:aftshoulderradius", new DoubleSetter(
271 Reflection.findMethodStatic(Transition.class, "setAftShoulderRadius", double.class)));
272 setters.put("Transition:aftshoulderlength", new DoubleSetter(
273 Reflection.findMethodStatic(Transition.class, "setAftShoulderLength", double.class)));
274 setters.put("Transition:aftshoulderthickness", new DoubleSetter(
275 Reflection.findMethodStatic(Transition.class, "setAftShoulderThickness", double.class)));
276 setters.put("Transition:aftshouldercapped", new BooleanSetter(
277 Reflection.findMethodStatic(Transition.class, "setAftShoulderCapped", boolean.class)));
279 // NoseCone - disable disallowed elements
280 setters.put("NoseCone:foreradius", null);
281 setters.put("NoseCone:foreshoulderradius", null);
282 setters.put("NoseCone:foreshoulderlength", null);
283 setters.put("NoseCone:foreshoulderthickness", null);
284 setters.put("NoseCone:foreshouldercapped", null);
287 setters.put("FinSet:fincount", new IntSetter(
288 Reflection.findMethodStatic(FinSet.class, "setFinCount", int.class)));
289 setters.put("FinSet:rotation", new DoubleSetter(
290 Reflection.findMethodStatic(FinSet.class, "setBaseRotation", double.class), Math.PI/180.0));
291 setters.put("FinSet:thickness", new DoubleSetter(
292 Reflection.findMethodStatic(FinSet.class, "setThickness", double.class)));
293 setters.put("FinSet:crosssection", new EnumSetter<FinSet.CrossSection>(
294 Reflection.findMethodStatic(FinSet.class, "setCrossSection", FinSet.CrossSection.class),
295 FinSet.CrossSection.class));
296 setters.put("FinSet:cant", new DoubleSetter(
297 Reflection.findMethodStatic(FinSet.class, "setCantAngle", double.class), Math.PI/180.0));
300 setters.put("TrapezoidFinSet:rootchord", new DoubleSetter(
301 Reflection.findMethodStatic(TrapezoidFinSet.class, "setRootChord", double.class)));
302 setters.put("TrapezoidFinSet:tipchord", new DoubleSetter(
303 Reflection.findMethodStatic(TrapezoidFinSet.class, "setTipChord", double.class)));
304 setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter(
305 Reflection.findMethodStatic(TrapezoidFinSet.class, "setSweep", double.class)));
306 setters.put("TrapezoidFinSet:height", new DoubleSetter(
307 Reflection.findMethodStatic(TrapezoidFinSet.class, "setHeight", double.class)));
310 setters.put("EllipticalFinSet:rootchord", new DoubleSetter(
311 Reflection.findMethodStatic(EllipticalFinSet.class, "setLength", double.class)));
312 setters.put("EllipticalFinSet:height", new DoubleSetter(
313 Reflection.findMethodStatic(EllipticalFinSet.class, "setHeight", double.class)));
315 // FreeformFinSet points handled as a special handler
318 setters.put("LaunchLug:radius", new DoubleSetter(
319 Reflection.findMethodStatic(LaunchLug.class, "setRadius", double.class)));
320 setters.put("LaunchLug:length", new DoubleSetter(
321 Reflection.findMethodStatic(LaunchLug.class, "setLength", double.class)));
322 setters.put("LaunchLug:thickness", new DoubleSetter(
323 Reflection.findMethodStatic(LaunchLug.class, "setThickness", double.class)));
324 setters.put("LaunchLug:radialdirection", new DoubleSetter(
325 Reflection.findMethodStatic(LaunchLug.class, "setRadialDirection", double.class),
328 // InternalComponent - nothing
330 // StructuralComponent
331 setters.put("StructuralComponent:material", new MaterialSetter(
332 Reflection.findMethodStatic(StructuralComponent.class, "setMaterial", Material.class),
333 Material.Type.BULK));
336 setters.put("RingComponent:length", new DoubleSetter(
337 Reflection.findMethodStatic(RingComponent.class, "setLength", double.class)));
338 setters.put("RingComponent:radialposition", new DoubleSetter(
339 Reflection.findMethodStatic(RingComponent.class, "setRadialPosition", double.class)));
340 setters.put("RingComponent:radialdirection", new DoubleSetter(
341 Reflection.findMethodStatic(RingComponent.class, "setRadialDirection", double.class),
344 // ThicknessRingComponent - radius on separate components due to differing automatics
345 setters.put("ThicknessRingComponent:thickness", new DoubleSetter(
346 Reflection.findMethodStatic(ThicknessRingComponent.class, "setThickness", double.class)));
349 setters.put("EngineBlock:outerradius", new DoubleSetter(
350 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadius", double.class),
352 Reflection.findMethodStatic(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class)));
355 setters.put("TubeCoupler:outerradius", new DoubleSetter(
356 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadius", double.class),
358 Reflection.findMethodStatic(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class)));
361 setters.put("InnerTube:outerradius", new DoubleSetter(
362 Reflection.findMethodStatic(InnerTube.class, "setOuterRadius", double.class)));
363 setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter());
364 setters.put("InnerTube:clusterscale", new DoubleSetter(
365 Reflection.findMethodStatic(InnerTube.class, "setClusterScale", double.class)));
366 setters.put("InnerTube:clusterrotation", new DoubleSetter(
367 Reflection.findMethodStatic(InnerTube.class, "setClusterRotation", double.class),
370 // RadiusRingComponent
373 setters.put("RadiusRingComponent:innerradius", new DoubleSetter(
374 Reflection.findMethodStatic(RadiusRingComponent.class, "setInnerRadius", double.class)));
375 setters.put("Bulkhead:outerradius", new DoubleSetter(
376 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadius", double.class),
378 Reflection.findMethodStatic(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class)));
381 setters.put("CenteringRing:innerradius", new DoubleSetter(
382 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadius", double.class),
384 Reflection.findMethodStatic(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class)));
385 setters.put("CenteringRing:outerradius", new DoubleSetter(
386 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadius", double.class),
388 Reflection.findMethodStatic(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class)));
392 setters.put("MassObject:packedlength", new DoubleSetter(
393 Reflection.findMethodStatic(MassObject.class, "setLength", double.class)));
394 setters.put("MassObject:packedradius", new DoubleSetter(
395 Reflection.findMethodStatic(MassObject.class, "setRadius", double.class)));
396 setters.put("MassObject:radialposition", new DoubleSetter(
397 Reflection.findMethodStatic(MassObject.class, "setRadialPosition", double.class)));
398 setters.put("MassObject:radialdirection", new DoubleSetter(
399 Reflection.findMethodStatic(MassObject.class, "setRadialDirection", double.class),
403 setters.put("MassComponent:mass", new DoubleSetter(
404 Reflection.findMethodStatic(MassComponent.class, "setComponentMass", double.class)));
407 setters.put("ShockCord:cordlength", new DoubleSetter(
408 Reflection.findMethodStatic(ShockCord.class, "setCordLength", double.class)));
409 setters.put("ShockCord:material", new MaterialSetter(
410 Reflection.findMethodStatic(ShockCord.class, "setMaterial", Material.class),
411 Material.Type.LINE));
414 setters.put("RecoveryDevice:cd", new DoubleSetter(
415 Reflection.findMethodStatic(RecoveryDevice.class, "setCD", double.class),
417 Reflection.findMethodStatic(RecoveryDevice.class, "setCDAutomatic", boolean.class)));
418 setters.put("RecoveryDevice:deployevent", new EnumSetter<RecoveryDevice.DeployEvent>(
419 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class),
420 RecoveryDevice.DeployEvent.class));
421 setters.put("RecoveryDevice:deployaltitude", new DoubleSetter(
422 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployAltitude", double.class)));
423 setters.put("RecoveryDevice:deploydelay", new DoubleSetter(
424 Reflection.findMethodStatic(RecoveryDevice.class, "setDeployDelay", double.class)));
425 setters.put("RecoveryDevice:material", new MaterialSetter(
426 Reflection.findMethodStatic(RecoveryDevice.class, "setMaterial", Material.class),
427 Material.Type.SURFACE));
430 setters.put("Parachute:diameter", new DoubleSetter(
431 Reflection.findMethodStatic(Parachute.class, "setDiameter", double.class)));
432 setters.put("Parachute:linecount", new IntSetter(
433 Reflection.findMethodStatic(Parachute.class, "setLineCount", int.class)));
434 setters.put("Parachute:linelength", new DoubleSetter(
435 Reflection.findMethodStatic(Parachute.class, "setLineLength", double.class)));
436 setters.put("Parachute:linematerial", new MaterialSetter(
437 Reflection.findMethodStatic(Parachute.class, "setLineMaterial", Material.class),
438 Material.Type.LINE));
441 setters.put("Streamer:striplength", new DoubleSetter(
442 Reflection.findMethodStatic(Streamer.class, "setStripLength", double.class)));
443 setters.put("Streamer:stripwidth", new DoubleSetter(
444 Reflection.findMethodStatic(Streamer.class, "setStripWidth", double.class)));
447 // <motorconfiguration> handled by separate handler
448 setters.put("Rocket:referencetype", new EnumSetter<ReferenceType>(
449 Reflection.findMethodStatic(Rocket.class, "setReferenceType", ReferenceType.class),
450 ReferenceType.class));
451 setters.put("Rocket:customreference", new DoubleSetter(
452 Reflection.findMethodStatic(Rocket.class, "setCustomReferenceLength", double.class)));
453 setters.put("Rocket:designer", new StringSetter(
454 Reflection.findMethodStatic(Rocket.class, "setDesigner", String.class)));
455 setters.put("Rocket:revision", new StringSetter(
456 Reflection.findMethodStatic(Rocket.class, "setRevision", String.class)));
461 * Search for a enum value that has the corresponding name as an XML value. The current
462 * conversion from enum name to XML value is to lowercase the name and strip out all
463 * underscore characters. This method returns a match to these criteria, or <code>null</code>
464 * if no such enum exists.
466 * @param <T> then enum type.
467 * @param name the XML value, null ok.
468 * @param enumClass the class of the enum.
469 * @return the found enum value, or <code>null</code>.
471 public static <T extends Enum<T>> Enum<T> findEnum(String name, Class<? extends Enum<T>> enumClass) {
476 for (Enum<T> e: enumClass.getEnumConstants()) {
477 if (e.name().toLowerCase().replace("_", "").equals(name)) {
486 * Convert a string to a double including formatting specifications of the OpenRocket
487 * file format. This accepts all formatting that is valid for
488 * <code>Double.parseDouble(s)</code> and a few others as well ("Inf", "-Inf").
490 * @param s the string to parse.
491 * @return the numerical value.
492 * @throws NumberFormatException the the string cannot be parsed.
494 public static double stringToDouble(String s) throws NumberFormatException {
496 throw new NumberFormatException("null string");
497 if (s.equalsIgnoreCase("NaN"))
499 if (s.equalsIgnoreCase("Inf"))
500 return Double.POSITIVE_INFINITY;
501 if (s.equalsIgnoreCase("-Inf"))
502 return Double.NEGATIVE_INFINITY;
503 return Double.parseDouble(s);
511 * The actual handler class. Contains the necessary methods for parsing the SAX source.
513 class DelegatorHandler extends DefaultHandler {
514 private final WarningSet warnings;
516 private final Stack<ElementHandler> handlerStack = new Stack<ElementHandler>();
517 private final Stack<StringBuilder> elementData = new Stack<StringBuilder>();
518 private final Stack<HashMap<String, String>> elementAttributes = new Stack<HashMap<String, String>>();
521 // Ignore all elements as long as ignore > 0
522 private int ignore = 0;
525 public DelegatorHandler(ElementHandler initialHandler, WarningSet warnings) {
526 this.warnings = warnings;
527 handlerStack.add(initialHandler);
528 elementData.add(new StringBuilder()); // Just in case
532 ///////// SAX handlers
535 public void startElement(String uri, String localName, String name,
536 Attributes attributes) throws SAXException {
544 // Check for unknown namespace
545 if (!uri.equals("")) {
546 warnings.add(Warning.fromString("Unknown namespace element '" + uri
547 + "' encountered, ignoring."));
552 // Add layer to data stacks
553 elementData.push(new StringBuilder());
554 elementAttributes.push(copyAttributes(attributes));
557 ElementHandler h = handlerStack.peek();
558 h = h.openElement(localName, elementAttributes.peek(), warnings);
560 handlerStack.push(h);
562 // Start ignoring elements
569 * Stores encountered characters in the elementData stack.
572 public void characters(char[] chars, int start, int length) throws SAXException {
577 StringBuilder sb = elementData.peek();
578 sb.append(chars, start, length);
583 * Removes the last layer from the stack.
586 public void endElement(String uri, String localName, String name) throws SAXException {
594 // Remove data from stack
595 String data = elementData.pop().toString(); // throws on error
596 HashMap<String, String> attr = elementAttributes.pop();
598 // Remove last handler and call the next one
601 h = handlerStack.pop();
602 h.endHandler(localName, attr, data, warnings);
604 h = handlerStack.peek();
605 h.closeElement(localName, attr, data, warnings);
609 private static HashMap<String, String> copyAttributes(Attributes atts) {
610 HashMap<String, String> ret = new HashMap<String, String>();
611 for (int i = 0; i < atts.getLength(); i++) {
612 ret.put(atts.getLocalName(i), atts.getValue(i));
621 abstract class ElementHandler {
624 * Called when an opening element is encountered. Returns the handler that will handle
625 * the elements within that element, or <code>null</code> if the element and all of
626 * its contents is to be ignored.
628 * @param element the element name.
629 * @param attributes attributes of the element.
630 * @param warnings the warning set to store warnings in.
631 * @return the handler that handles elements encountered within this element,
632 * or <code>null</code> if the element is to be ignored.
634 public abstract ElementHandler openElement(String element,
635 HashMap<String, String> attributes, WarningSet warnings);
638 * Called when an element is closed. The default implementation checks whether there is
639 * any non-space text within the element and if there exists any attributes, and adds
640 * a warning of both. This can be used at the and of the method to check for
643 * @param element the element name.
644 * @param attributes attributes of the element.
645 * @param content the textual content of the element.
646 * @param warnings the warning set to store warnings in.
648 public void closeElement(String element, HashMap<String, String> attributes,
649 String content, WarningSet warnings) {
651 if (!content.trim().equals("")) {
652 warnings.add(Warning.fromString("Unknown text in element " + element
655 if (!attributes.isEmpty()) {
656 warnings.add(Warning.fromString("Unknown attributes in element " + element
663 * Called when the element block that this handler is handling ends.
664 * The default implementation is a no-op.
666 * @param warnings the warning set to store warnings in.
668 public void endHandler(String element, HashMap<String, String> attributes,
669 String content, WarningSet warnings) {
677 * The starting point of the handlers. Accepts a single <openrocket> element and hands
678 * the contents to be read by a OpenRocketContentsHandler.
680 class OpenRocketHandler extends ElementHandler {
681 private OpenRocketContentHandler handler = null;
684 * Return the OpenRocketDocument read from the file, or <code>null</code> if a document
685 * has not been read yet.
687 * @return the document read, or null.
689 public OpenRocketDocument getDocument() {
690 return handler.getDocument();
694 public ElementHandler openElement(String element, HashMap<String, String> attributes,
695 WarningSet warnings) {
697 // Check for unknown elements
698 if (!element.equals("openrocket")) {
699 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
703 // Check for first call
704 if (handler != null) {
705 warnings.add(Warning.fromString("Multiple document elements found, ignoring later "
710 // Check version number
711 String version = null;
712 String docVersion = attributes.remove("version");
713 for (String v : DocumentConfig.SUPPORTED_VERSIONS) {
714 if (v.equals(docVersion)) {
719 if (version == null) {
720 if (docVersion != null)
721 warnings.add(Warning.fromString("Unsupported document version "
722 + docVersion + ", attempting to read anyway."));
724 warnings.add(Warning.fromString("Unsupported document version, attempting to"
728 handler = new OpenRocketContentHandler();
735 * Handles the content of the <openrocket> tag.
737 class OpenRocketContentHandler extends ElementHandler {
738 private final OpenRocketDocument doc;
739 private final Rocket rocket;
741 private boolean rocketDefined = false;
742 private boolean simulationsDefined = false;
744 public OpenRocketContentHandler() {
745 this.rocket = new Rocket();
746 this.doc = new OpenRocketDocument(rocket);
750 public OpenRocketDocument getDocument() {
757 public ElementHandler openElement(String element, HashMap<String, String> attributes,
758 WarningSet warnings) {
760 if (element.equals("rocket")) {
763 .fromString("Multiple rocket designs within one document, "
764 + "ignoring later ones."));
767 rocketDefined = true;
768 return new ComponentParameterHandler(rocket);
771 if (element.equals("simulations")) {
772 if (simulationsDefined) {
774 .fromString("Multiple simulation definitions within one document, "
775 + "ignoring later ones."));
778 simulationsDefined = true;
779 return new SimulationsHandler(doc);
782 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
790 * An element handler that does not allow any sub-elements. If any are encountered
791 * a warning is generated and they are ignored.
793 class PlainTextHandler extends ElementHandler {
794 public static final PlainTextHandler INSTANCE = new PlainTextHandler();
796 private PlainTextHandler() {
800 public ElementHandler openElement(String element, HashMap<String, String> attributes,
801 WarningSet warnings) {
802 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
807 public void closeElement(String element, HashMap<String, String> attributes,
808 String content, WarningSet warnings) {
809 // Warning from openElement is sufficient.
816 * A handler that creates components from the corresponding elements. The control of the
817 * contents is passed on to ComponentParameterHandler.
819 class ComponentHandler extends ElementHandler {
820 private final RocketComponent parent;
822 public ComponentHandler(RocketComponent parent) {
823 this.parent = parent;
827 public ElementHandler openElement(String element, HashMap<String, String> attributes,
828 WarningSet warnings) {
830 // Attempt to construct new component
831 Constructor<? extends RocketComponent> constructor = DocumentConfig.constructors
833 if (constructor == null) {
834 warnings.add(Warning.fromString("Unknown element " + element + ", ignoring."));
840 c = constructor.newInstance();
841 } catch (InstantiationException e) {
842 throw new RuntimeException("Error constructing component.", e);
843 } catch (IllegalAccessException e) {
844 throw new RuntimeException("Error constructing component.", e);
845 } catch (InvocationTargetException e) {
846 throw new RuntimeException("Error constructing component.", e);
851 return new ComponentParameterHandler(c);
857 * A handler that populates the parameters of a previously constructed rocket component.
858 * This uses the setters, or delegates the handling to another handler for specific
861 class ComponentParameterHandler extends ElementHandler {
862 private final RocketComponent component;
864 public ComponentParameterHandler(RocketComponent c) {
869 public ElementHandler openElement(String element, HashMap<String, String> attributes,
870 WarningSet warnings) {
872 // Check for specific elements that contain other elements
873 if (element.equals("subcomponents")) {
874 return new ComponentHandler(component);
876 if (element.equals("motormount")) {
877 if (!(component instanceof MotorMount)) {
878 warnings.add(Warning.fromString("Illegal component defined as motor mount."));
881 return new MotorMountHandler((MotorMount)component);
883 if (element.equals("finpoints")) {
884 if (!(component instanceof FreeformFinSet)) {
885 warnings.add(Warning.fromString("Illegal component defined for fin points."));
888 return new FinSetPointHandler((FreeformFinSet)component);
890 if (element.equals("motorconfiguration")) {
891 if (!(component instanceof Rocket)) {
892 warnings.add(Warning.fromString("Illegal component defined for motor configuration."));
895 return new MotorConfigurationHandler((Rocket)component);
899 return PlainTextHandler.INSTANCE;
903 public void closeElement(String element, HashMap<String, String> attributes,
904 String content, WarningSet warnings) {
906 if (element.equals("subcomponents") || element.equals("motormount") ||
907 element.equals("finpoints") || element.equals("motorconfiguration")) {
911 // Search for the correct setter class
914 for (c = component.getClass(); c != null; c = c.getSuperclass()) {
915 String setterKey = c.getSimpleName() + ":" + element;
916 Setter s = DocumentConfig.setters.get(setterKey);
919 System.out.println("Calling with key "+setterKey);
920 s.set(component, content, attributes, warnings);
923 if (DocumentConfig.setters.containsKey(setterKey)) {
924 // Key exists but is null -> invalid parameter
930 warnings.add(Warning.fromString("Unknown parameter type " + element + " for "
931 + component.getComponentName()));
938 * A handler that reads the <point> specifications within the freeformfinset's
939 * <finpoints> elements.
941 class FinSetPointHandler extends ElementHandler {
942 private final FreeformFinSet finset;
943 private final ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>();
945 public FinSetPointHandler(FreeformFinSet finset) {
946 this.finset = finset;
950 public ElementHandler openElement(String element, HashMap<String, String> attributes,
951 WarningSet warnings) {
952 return PlainTextHandler.INSTANCE;
957 public void closeElement(String element, HashMap<String, String> attributes,
958 String content, WarningSet warnings) {
960 String strx = attributes.remove("x");
961 String stry = attributes.remove("y");
962 if (strx == null || stry == null) {
963 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
967 double x = Double.parseDouble(strx);
968 double y = Double.parseDouble(stry);
969 coordinates.add(new Coordinate(x,y));
970 } catch (NumberFormatException e) {
971 warnings.add(Warning.fromString("Illegal fin points specification, ignoring."));
975 super.closeElement(element, attributes, content, warnings);
979 public void endHandler(String element, HashMap<String, String> attributes,
980 String content, WarningSet warnings) {
982 finset.setPoints(coordinates.toArray(new Coordinate[0]));
983 } catch (IllegalFinPointException e) {
984 warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring."));
990 class MotorMountHandler extends ElementHandler {
991 private final MotorMount mount;
992 private MotorHandler motorHandler;
994 public MotorMountHandler(MotorMount mount) {
996 mount.setMotorMount(true);
1000 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1001 WarningSet warnings) {
1003 if (element.equals("motor")) {
1004 motorHandler = new MotorHandler();
1005 return motorHandler;
1008 if (element.equals("ignitionevent") ||
1009 element.equals("ignitiondelay") ||
1010 element.equals("overhang")) {
1011 return PlainTextHandler.INSTANCE;
1014 warnings.add(Warning.fromString("Unknown element '"+element+"' encountered, ignoring."));
1021 public void closeElement(String element, HashMap<String, String> attributes,
1022 String content, WarningSet warnings) {
1024 if (element.equals("motor")) {
1025 String id = attributes.get("configid");
1026 if (id == null || id.equals("")) {
1027 warnings.add(Warning.fromString("Illegal motor specification, ignoring."));
1031 Motor motor = motorHandler.getMotor(warnings);
1032 mount.setMotor(id, motor);
1033 mount.setMotorDelay(id, motorHandler.getDelay(warnings));
1037 if (element.equals("ignitionevent")) {
1038 MotorMount.IgnitionEvent event = null;
1039 for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) {
1040 if (e.name().toLowerCase().replaceAll("_", "").equals(content)) {
1045 if (event == null) {
1046 warnings.add(Warning.fromString("Unknown ignition event type '"+content+"', ignoring."));
1049 mount.setIgnitionEvent(event);
1053 if (element.equals("ignitiondelay")) {
1056 d = Double.parseDouble(content);
1057 } catch (NumberFormatException nfe) {
1058 warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring."));
1061 mount.setIgnitionDelay(d);
1065 if (element.equals("overhang")) {
1068 d = Double.parseDouble(content);
1069 } catch (NumberFormatException nfe) {
1070 warnings.add(Warning.fromString("Illegal overhang specified, ignoring."));
1073 mount.setMotorOverhang(d);
1077 super.closeElement(element, attributes, content, warnings);
1084 class MotorConfigurationHandler extends ElementHandler {
1085 private final Rocket rocket;
1086 private String name = null;
1087 private boolean inNameElement = false;
1089 public MotorConfigurationHandler(Rocket rocket) {
1090 this.rocket = rocket;
1094 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1095 WarningSet warnings) {
1097 if (inNameElement || !element.equals("name")) {
1098 warnings.add(Warning.FILE_INVALID_PARAMETER);
1101 inNameElement = true;
1103 return PlainTextHandler.INSTANCE;
1107 public void closeElement(String element, HashMap<String, String> attributes,
1108 String content, WarningSet warnings) {
1113 public void endHandler(String element, HashMap<String, String> attributes,
1114 String content, WarningSet warnings) {
1116 String configid = attributes.remove("configid");
1117 if (configid == null || configid.equals("")) {
1118 warnings.add(Warning.FILE_INVALID_PARAMETER);
1122 if (!rocket.addMotorConfigurationID(configid)) {
1123 warnings.add("Duplicate motor configuration ID used.");
1127 if (name != null && name.trim().length() > 0) {
1128 rocket.setMotorConfigurationName(configid, name);
1131 if ("true".equals(attributes.remove("default"))) {
1132 rocket.getDefaultConfiguration().setMotorConfigurationID(configid);
1135 super.closeElement(element, attributes, content, warnings);
1140 class MotorHandler extends ElementHandler {
1141 private Motor.Type type = null;
1142 private String manufacturer = null;
1143 private String designation = null;
1144 private double diameter = Double.NaN;
1145 private double length = Double.NaN;
1146 private double delay = Double.NaN;
1149 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1150 WarningSet warnings) {
1151 return PlainTextHandler.INSTANCE;
1156 * Return the motor to use, or null.
1158 public Motor getMotor(WarningSet warnings) {
1159 if (designation == null) {
1160 warnings.add(Warning.fromString("No motor specified, ignoring."));
1163 Motor[] motors = Databases.findMotors(type, manufacturer, designation, diameter, length);
1164 if (motors.length == 0) {
1165 String str = "No motor with designation '"+designation+"'";
1166 if (manufacturer != null)
1167 str += " for manufacturer '" + manufacturer + "'";
1168 warnings.add(Warning.fromString(str + " found."));
1171 if (motors.length > 1) {
1172 String str = "Multiple motors with designation '"+designation+"'";
1173 if (manufacturer != null)
1174 str += " for manufacturer '" + manufacturer + "'";
1175 warnings.add(Warning.fromString(str + " found, one chosen arbitrarily."));
1182 * Return the delay to use for the motor.
1184 public double getDelay(WarningSet warnings) {
1185 if (Double.isNaN(delay)) {
1186 warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge."));
1187 return Motor.PLUGGED;
1194 public void closeElement(String element, HashMap<String, String> attributes,
1195 String content, WarningSet warnings) {
1197 content = content.trim();
1199 if (element.equals("type")) {
1203 for (Motor.Type t: Motor.Type.values()) {
1204 if (t.name().toLowerCase().equals(content)) {
1210 warnings.add(Warning.fromString("Unknown motor type '"+content+"', ignoring."));
1213 } else if (element.equals("manufacturer")) {
1216 manufacturer = content;
1218 } else if (element.equals("designation")) {
1221 designation = content;
1223 } else if (element.equals("diameter")) {
1226 diameter = Double.NaN;
1228 diameter = Double.parseDouble(content);
1229 } catch (NumberFormatException e) {
1232 if (Double.isNaN(diameter)) {
1233 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1236 } else if (element.equals("length")) {
1239 length = Double.NaN;
1241 length = Double.parseDouble(content);
1242 } catch (NumberFormatException ignore) { }
1244 if (Double.isNaN(length)) {
1245 warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring."));
1248 } else if (element.equals("delay")) {
1252 if (content.equals("none")) {
1253 delay = Motor.PLUGGED;
1256 delay = Double.parseDouble(content);
1257 } catch (NumberFormatException ignore) { }
1259 if (Double.isNaN(delay)) {
1260 warnings.add(Warning.fromString("Illegal motor delay specified, ignoring."));
1266 super.closeElement(element, attributes, content, warnings);
1274 class SimulationsHandler extends ElementHandler {
1275 private final OpenRocketDocument doc;
1276 private SingleSimulationHandler handler;
1278 public SimulationsHandler(OpenRocketDocument doc) {
1283 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1284 WarningSet warnings) {
1286 if (!element.equals("simulation")) {
1287 warnings.add("Unknown element '"+element+"', ignoring.");
1291 handler = new SingleSimulationHandler(doc);
1296 class SingleSimulationHandler extends ElementHandler {
1298 private final OpenRocketDocument doc;
1300 private String name;
1302 private SimulationConditionsHandler conditionHandler;
1303 private FlightDataHandler dataHandler;
1305 private final List<String> listeners = new ArrayList<String>();
1307 public SingleSimulationHandler(OpenRocketDocument doc) {
1314 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1315 WarningSet warnings) {
1317 if (element.equals("name") || element.equals("simulator") ||
1318 element.equals("calculator") || element.equals("listener")) {
1319 return PlainTextHandler.INSTANCE;
1320 } else if (element.equals("conditions")) {
1321 conditionHandler = new SimulationConditionsHandler(doc.getRocket());
1322 return conditionHandler;
1323 } else if (element.equals("flightdata")) {
1324 dataHandler = new FlightDataHandler();
1327 warnings.add("Unknown element '"+element+"', ignoring.");
1333 public void closeElement(String element, HashMap<String, String> attributes,
1334 String content, WarningSet warnings) {
1336 if (element.equals("name")) {
1338 } else if (element.equals("simulator")) {
1339 if (!content.equals("RK4Simulator")) {
1340 warnings.add("Unknown simulator specified, ignoring.");
1342 } else if (element.equals("calculator")) {
1343 if (!content.equals("BarrowmanSimulator")) {
1344 warnings.add("Unknown calculator specified, ignoring.");
1346 } else if (element.equals("listener") && content.trim().length() > 0) {
1347 listeners.add(content.trim());
1353 public void endHandler(String element, HashMap<String, String> attributes,
1354 String content, WarningSet warnings) {
1356 String s = attributes.get("status");
1357 Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class);
1358 if (status == null) {
1359 warnings.add("Simulation status unknown, assuming outdated.");
1360 status = Simulation.Status.OUTDATED;
1363 SimulationConditions conditions;
1364 if (conditionHandler != null) {
1365 conditions = conditionHandler.getConditions();
1367 warnings.add("Simulation conditions not defined, using defaults.");
1368 conditions = new SimulationConditions(doc.getRocket());
1372 name = "Simulation";
1375 if (dataHandler == null)
1378 data = dataHandler.getFlightData();
1380 Simulation simulation = new Simulation(doc.getRocket(), status, name,
1381 conditions, listeners, data);
1383 doc.addSimulation(simulation);
1389 class SimulationConditionsHandler extends ElementHandler {
1390 private SimulationConditions conditions;
1391 private AtmosphereHandler atmosphereHandler;
1393 public SimulationConditionsHandler(Rocket rocket) {
1394 conditions = new SimulationConditions(rocket);
1397 public SimulationConditions getConditions() {
1402 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1403 WarningSet warnings) {
1404 if (element.equals("atmosphere")) {
1405 atmosphereHandler = new AtmosphereHandler(attributes.get("model"));
1406 return atmosphereHandler;
1408 return PlainTextHandler.INSTANCE;
1412 public void closeElement(String element, HashMap<String, String> attributes,
1413 String content, WarningSet warnings) {
1415 double d = Double.NaN;
1417 d = Double.parseDouble(content);
1418 } catch (NumberFormatException ignore) { }
1421 if (element.equals("configid")) {
1422 if (content.equals("")) {
1423 conditions.setMotorConfigurationID(null);
1425 conditions.setMotorConfigurationID(content);
1427 } else if (element.equals("launchrodlength")) {
1428 if (Double.isNaN(d)) {
1429 warnings.add("Illegal launch rod length defined, ignoring.");
1431 conditions.setLaunchRodLength(d);
1433 } else if (element.equals("launchrodangle")) {
1434 if (Double.isNaN(d)) {
1435 warnings.add("Illegal launch rod angle defined, ignoring.");
1437 conditions.setLaunchRodAngle(d*Math.PI/180);
1439 } else if (element.equals("launchroddirection")) {
1440 if (Double.isNaN(d)) {
1441 warnings.add("Illegal launch rod direction defined, ignoring.");
1443 conditions.setLaunchRodDirection(d*Math.PI/180);
1445 } else if (element.equals("windaverage")) {
1446 if (Double.isNaN(d)) {
1447 warnings.add("Illegal average windspeed defined, ignoring.");
1449 conditions.setWindSpeedAverage(d);
1451 } else if (element.equals("windturbulence")) {
1452 if (Double.isNaN(d)) {
1453 warnings.add("Illegal wind turbulence intensity defined, ignoring.");
1455 conditions.setWindTurbulenceIntensity(d);
1457 } else if (element.equals("launchaltitude")) {
1458 if (Double.isNaN(d)) {
1459 warnings.add("Illegal launch altitude defined, ignoring.");
1461 conditions.setLaunchAltitude(d);
1463 } else if (element.equals("launchlatitude")) {
1464 if (Double.isNaN(d)) {
1465 warnings.add("Illegal launch latitude defined, ignoring.");
1467 conditions.setLaunchLatitude(d);
1469 } else if (element.equals("atmosphere")) {
1470 atmosphereHandler.storeSettings(conditions, warnings);
1471 } else if (element.equals("timestep")) {
1472 if (Double.isNaN(d)) {
1473 warnings.add("Illegal time step defined, ignoring.");
1475 conditions.setTimeStep(d);
1482 class AtmosphereHandler extends ElementHandler {
1483 private final String model;
1484 private double temperature = Double.NaN;
1485 private double pressure = Double.NaN;
1487 public AtmosphereHandler(String model) {
1492 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1493 WarningSet warnings) {
1494 return PlainTextHandler.INSTANCE;
1498 public void closeElement(String element, HashMap<String, String> attributes,
1499 String content, WarningSet warnings) {
1501 double d = Double.NaN;
1503 d = Double.parseDouble(content);
1504 } catch (NumberFormatException ignore) { }
1506 if (element.equals("basetemperature")) {
1507 if (Double.isNaN(d)) {
1508 warnings.add("Illegal base temperature specified, ignoring.");
1511 } else if (element.equals("basepressure")) {
1512 if (Double.isNaN(d)) {
1513 warnings.add("Illegal base pressure specified, ignoring.");
1517 super.closeElement(element, attributes, content, warnings);
1522 public void storeSettings(SimulationConditions cond, WarningSet warnings) {
1523 if (!Double.isNaN(pressure)) {
1524 cond.setLaunchPressure(pressure);
1526 if (!Double.isNaN(temperature)) {
1527 cond.setLaunchTemperature(temperature);
1530 if ("isa".equals(model)) {
1531 cond.setISAAtmosphere(true);
1532 } else if ("extendedisa".equals(model)){
1533 cond.setISAAtmosphere(false);
1535 cond.setISAAtmosphere(true);
1536 warnings.add("Unknown atmospheric model, using ISA.");
1543 class FlightDataHandler extends ElementHandler {
1545 private FlightDataBranchHandler dataHandler;
1546 private WarningSet warningSet = new WarningSet();
1547 private List<FlightDataBranch> branches = new ArrayList<FlightDataBranch>();
1549 private FlightData data;
1551 public FlightData getFlightData() {
1556 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1557 WarningSet warnings) {
1559 if (element.equals("warning")) {
1560 return PlainTextHandler.INSTANCE;
1562 if (element.equals("databranch")) {
1563 if (attributes.get("name") == null || attributes.get("types")==null) {
1564 warnings.add("Illegal flight data definition, ignoring.");
1567 dataHandler = new FlightDataBranchHandler(attributes.get("name"),
1568 attributes.get("types"));
1572 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1578 public void closeElement(String element, HashMap<String, String> attributes,
1579 String content, WarningSet warnings) {
1581 if (element.equals("databranch")) {
1582 FlightDataBranch branch = dataHandler.getBranch();
1583 if (branch.getLength() > 0) {
1584 branches.add(branch);
1586 } else if (element.equals("warning")) {
1587 warningSet.add(Warning.fromString(content));
1593 public void endHandler(String element, HashMap<String, String> attributes,
1594 String content, WarningSet warnings) {
1596 if (branches.size() > 0) {
1597 data = new FlightData(branches.toArray(new FlightDataBranch[0]));
1599 double maxAltitude = Double.NaN;
1600 double maxVelocity = Double.NaN;
1601 double maxAcceleration = Double.NaN;
1602 double maxMach = Double.NaN;
1603 double timeToApogee = Double.NaN;
1604 double flightTime = Double.NaN;
1605 double groundHitVelocity = Double.NaN;
1608 maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude"));
1609 } catch (NumberFormatException ignore) { }
1611 maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity"));
1612 } catch (NumberFormatException ignore) { }
1614 maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration"));
1615 } catch (NumberFormatException ignore) { }
1617 maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach"));
1618 } catch (NumberFormatException ignore) { }
1620 timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee"));
1621 } catch (NumberFormatException ignore) { }
1623 flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime"));
1624 } catch (NumberFormatException ignore) { }
1627 DocumentConfig.stringToDouble(attributes.get("groundhitvelocity"));
1628 } catch (NumberFormatException ignore) { }
1630 data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach,
1631 timeToApogee, flightTime, groundHitVelocity);
1634 data.getWarningSet().addAll(warningSet);
1641 class FlightDataBranchHandler extends ElementHandler {
1642 private final FlightDataBranch.Type[] types;
1643 private final FlightDataBranch branch;
1645 public FlightDataBranchHandler(String name, String typeList) {
1646 String[] split = typeList.split(",");
1647 types = new FlightDataBranch.Type[split.length];
1648 for (int i=0; i < split.length; i++) {
1649 types[i] = FlightDataBranch.getType(split[i], UnitGroup.UNITS_NONE);
1652 // TODO: LOW: May throw an IllegalArgumentException
1653 branch = new FlightDataBranch(name, types);
1656 public FlightDataBranch getBranch() {
1662 public ElementHandler openElement(String element, HashMap<String, String> attributes,
1663 WarningSet warnings) {
1665 if (element.equals("datapoint"))
1666 return PlainTextHandler.INSTANCE;
1667 if (element.equals("event"))
1668 return PlainTextHandler.INSTANCE;
1670 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1676 public void closeElement(String element, HashMap<String, String> attributes,
1677 String content, WarningSet warnings) {
1679 if (element.equals("event")) {
1681 FlightEvent.Type type;
1684 time = DocumentConfig.stringToDouble(attributes.get("time"));
1685 } catch (NumberFormatException e) {
1686 warnings.add("Illegal event specification, ignoring.");
1690 type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class);
1692 warnings.add("Illegal event specification, ignoring.");
1696 branch.addEvent(time, new FlightEvent(type, time));
1700 if (!element.equals("datapoint")) {
1701 warnings.add("Unknown element '"+element+"' encountered, ignoring.");
1705 // element == "datapoint"
1708 // Check line format
1709 String[] split = content.split(",");
1710 if (split.length != types.length) {
1711 warnings.add("Data point did not contain correct amount of values, ignoring point.");
1715 // Parse the doubles
1716 double[] values = new double[split.length];
1717 for (int i=0; i < values.length; i++) {
1719 values[i] = DocumentConfig.stringToDouble(split[i]);
1720 } catch (NumberFormatException e) {
1721 warnings.add("Data point format error, ignoring point.");
1726 // Add point to branch
1728 for (int i=0; i < types.length; i++) {
1729 branch.setValue(types[i], values[i]);
1739 ///////////////// Setters implementation
1745 * Set the specified value to the given component.
1747 * @param component the component to which to set.
1748 * @param value the value within the element.
1749 * @param attributes attributes for the element.
1750 * @param warnings the warning set to use.
1752 public void set(RocketComponent component, String value,
1753 HashMap<String, String> attributes, WarningSet warnings);
1757 //// StringSetter - sets the value to the contained String
1758 class StringSetter implements Setter {
1759 private final Reflection.Method setMethod;
1761 public StringSetter(Reflection.Method set) {
1765 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1766 WarningSet warnings) {
1767 setMethod.invoke(c, s);
1771 //// IntSetter - set an integer value
1772 class IntSetter implements Setter {
1773 private final Reflection.Method setMethod;
1775 public IntSetter(Reflection.Method set) {
1779 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1780 WarningSet warnings) {
1782 int n = Integer.parseInt(s);
1783 setMethod.invoke(c, n);
1784 } catch (NumberFormatException e) {
1785 warnings.add(Warning.FILE_INVALID_PARAMETER);
1791 //// BooleanSetter - set a boolean value
1792 class BooleanSetter implements Setter {
1793 private final Reflection.Method setMethod;
1795 public BooleanSetter(Reflection.Method set) {
1799 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1800 WarningSet warnings) {
1803 if (s.equalsIgnoreCase("true")) {
1804 setMethod.invoke(c, true);
1805 } else if (s.equalsIgnoreCase("false")) {
1806 setMethod.invoke(c, false);
1808 warnings.add(Warning.FILE_INVALID_PARAMETER);
1815 //// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered
1816 //// calls a setXXX(boolean) method.
1817 class DoubleSetter implements Setter {
1818 private final Reflection.Method setMethod;
1819 private final String specialString;
1820 private final Reflection.Method specialMethod;
1821 private final double multiplier;
1824 * Set only the double value.
1825 * @param set set method for the double value.
1827 public DoubleSetter(Reflection.Method set) {
1828 this.setMethod = set;
1829 this.specialString = null;
1830 this.specialMethod = null;
1831 this.multiplier = 1.0;
1835 * Multiply with the given multiplier and set the double value.
1836 * @param set set method for the double value.
1837 * @param mul multiplier.
1839 public DoubleSetter(Reflection.Method set, double mul) {
1840 this.setMethod = set;
1841 this.specialString = null;
1842 this.specialMethod = null;
1843 this.multiplier = mul;
1847 * Set the double value, or if the value equals the special string, use the
1848 * special setter and set it to true.
1850 * @param set double setter.
1851 * @param special special string
1852 * @param specialMethod boolean setter.
1854 public DoubleSetter(Reflection.Method set, String special,
1855 Reflection.Method specialMethod) {
1856 this.setMethod = set;
1857 this.specialString = special;
1858 this.specialMethod = specialMethod;
1859 this.multiplier = 1.0;
1863 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1864 WarningSet warnings) {
1868 // Check for special case
1869 if (specialMethod != null && s.equalsIgnoreCase(specialString)) {
1870 specialMethod.invoke(c, true);
1876 double d = Double.parseDouble(s);
1877 setMethod.invoke(c, d * multiplier);
1878 } catch (NumberFormatException e) {
1879 warnings.add(Warning.FILE_INVALID_PARAMETER);
1885 class OverrideSetter implements Setter {
1886 private final Reflection.Method setMethod;
1887 private final Reflection.Method enabledMethod;
1889 public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) {
1890 this.setMethod = set;
1891 this.enabledMethod = enabledMethod;
1894 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1895 WarningSet warnings) {
1898 double d = Double.parseDouble(s);
1899 setMethod.invoke(c, d);
1900 enabledMethod.invoke(c, true);
1901 } catch (NumberFormatException e) {
1902 warnings.add(Warning.FILE_INVALID_PARAMETER);
1907 //// EnumSetter - sets a generic enum type
1908 class EnumSetter<T extends Enum<T>> implements Setter {
1909 private final Reflection.Method setter;
1910 private final Class<T> enumClass;
1912 public EnumSetter(Reflection.Method set, Class<T> enumClass) {
1914 this.enumClass = enumClass;
1918 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1919 WarningSet warnings) {
1921 Enum<?> setEnum = DocumentConfig.findEnum(name, enumClass);
1922 if (setEnum == null) {
1923 warnings.add(Warning.FILE_INVALID_PARAMETER);
1927 setter.invoke(c, setEnum);
1932 //// ColorSetter - sets a Color value
1933 class ColorSetter implements Setter {
1934 private final Reflection.Method setMethod;
1936 public ColorSetter(Reflection.Method set) {
1940 public void set(RocketComponent c, String s, HashMap<String, String> attributes,
1941 WarningSet warnings) {
1943 String red = attributes.get("red");
1944 String green = attributes.get("green");
1945 String blue = attributes.get("blue");
1947 if (red == null || green == null || blue == null) {
1948 warnings.add(Warning.FILE_INVALID_PARAMETER);
1954 r = Integer.parseInt(red);
1955 g = Integer.parseInt(green);
1956 b = Integer.parseInt(blue);
1957 } catch (NumberFormatException e) {
1958 warnings.add(Warning.FILE_INVALID_PARAMETER);
1962 if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) {
1963 warnings.add(Warning.FILE_INVALID_PARAMETER);
1967 Color color = new Color(r, g, b);
1968 setMethod.invoke(c, color);
1970 if (!s.trim().equals("")) {
1971 warnings.add(Warning.FILE_INVALID_PARAMETER);
1978 class MaterialSetter implements Setter {
1979 private final Reflection.Method setMethod;
1980 private final Material.Type type;
1982 public MaterialSetter(Reflection.Method set, Material.Type type) {
1983 this.setMethod = set;
1987 public void set(RocketComponent c, String name, HashMap<String, String> attributes,
1988 WarningSet warnings) {
1994 if (name.equals("")) {
1995 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2002 str = attributes.remove("density");
2004 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2008 density = Double.parseDouble(str);
2009 } catch (NumberFormatException e) {
2010 warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2015 // double thickness = 0;
2016 // str = attributes.remove("thickness");
2019 // thickness = Double.parseDouble(str);
2020 // } catch (NumberFormatException e){
2021 // warnings.add(Warning.fromString("Illegal material specification, ignoring."));
2025 // Check type if specified
2026 str = attributes.remove("type");
2027 if (str != null && !type.name().toLowerCase().equals(str)) {
2028 warnings.add(Warning.fromString("Illegal material type specified, ignoring."));
2032 mat = Material.newMaterial(type, name, density);
2034 setMethod.invoke(c, mat);
2041 class PositionSetter implements Setter {
2043 public void set(RocketComponent c, String value, HashMap<String, String> attributes,
2044 WarningSet warnings) {
2046 RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"),
2047 RocketComponent.Position.class);
2049 warnings.add(Warning.FILE_INVALID_PARAMETER);
2055 pos = Double.parseDouble(value);
2056 } catch (NumberFormatException e) {
2057 warnings.add(Warning.FILE_INVALID_PARAMETER);
2061 if (c instanceof FinSet) {
2062 ((FinSet)c).setRelativePosition(type);
2063 c.setPositionValue(pos);
2064 } else if (c instanceof LaunchLug) {
2065 ((LaunchLug)c).setRelativePosition(type);
2066 c.setPositionValue(pos);
2067 } else if (c instanceof InternalComponent) {
2068 ((InternalComponent)c).setRelativePosition(type);
2069 c.setPositionValue(pos);
2071 warnings.add(Warning.FILE_INVALID_PARAMETER);
2079 class ClusterConfigurationSetter implements Setter {
2081 public void set(RocketComponent component, String value, HashMap<String, String> attributes,
2082 WarningSet warnings) {
2084 if (!(component instanceof Clusterable)) {
2085 warnings.add("Illegal component defined as cluster.");
2089 ClusterConfiguration config = null;
2090 for (ClusterConfiguration c: ClusterConfiguration.CONFIGURATIONS) {
2091 if (c.getXMLName().equals(value)) {
2097 if (config == null) {
2098 warnings.add("Illegal cluster configuration specified.");
2102 ((Clusterable)component).setClusterConfiguration(config);