source: java/main/src/main/java/com/framsticks/parsers/XmlLoader.java @ 101

Last change on this file since 101 was 101, checked in by psniegowski, 11 years ago

HIGHLIGHTS:

  • improve tree side notes
  • improve GUI layout
  • add foldable list of occured events to EventControl?
  • improve automatic type conversion in proxy listeners
  • implement several Access functionalities as algorithms independent of Access type
  • introduce draft base classes for distributed experiments
  • automatically register dependant Java classes to FramsClass? registry
  • add testing prime experiment and configuration
  • simplify and improve task dispatching

CHANGELOG:
Improve task dispatching in RemoteTree?.

GUI no longer hangs on connection problems.

Make all dispatchers joinables.

Refactorize Thread dispatcher.

Remove Task and PeriodicTask?.

Use Java utilities in those situations.

Reworking tasks dispatching.

Fix bug in EventControl? listener dispatching.

Minor improvements.

Add testing configuration for ExternalProcess? in GUI.

More improvement to prime.

Support for USERREADONLY in GUI.

Add that flag to various params in Java classes.

Remove redundant register clauses from several FramsClassAnnotations?.

Automatically gather and register dependant classes.

Add configuration for prime.

Improve Simulator class.

Add prime.xml configuration.

Introduce draft Experiment and Simulator classes.

Add prime experiment tests.

Enclose typical map with listeners into SimpleUniqueList?.

Needfile works in GUI.

Improve needfile handling in Browser.

More improvement with NeedFile?.

Implementing needfile.

Update test.

Rename ChangeEvent? to TestChangeEvent?.

Automatic argument type search in RemoteTree? listeners.

MultiParamLoader? uses AccessProvider?. By default old implementation
enclosed in AccessStash? or Registry.

Minor changes.

Rename SourceInterface? to Source.

Also improve toString of File and ListSource?.

Remove unused SimpleSource? class.

Add clearing in HistoryControl?.

Show entries in table at EventControl?.

Improve EventControl?.

Add listeners registration to EventControl?.

Add foldable table to HistoryControl?.

Add control row to Procedure and Event controls.

Improve layout of controls.

Another minor change to gui layout.

Minor improvement in the SliderControl?.

Minor changes.

Move ReflectionAccess?.Backend to separate file.

It was to cluttered.

Cleanup in ReflectionAccess?.

Move setMin, setMax, setDef to AccessOperations?.

Extract loading operation into AccessOperations?.

Append Framsticks to name of UnsupportedOperationException?.

The java.lang.UnsupportedOperationException? was shadowing this class.

Rename params.Util to params.ParamsUtil?.

Several improvements.

Minor changes.

Implement revert functionality.

Improve local changes management.

Minor improvement.

Remove methods rendered superfluous after SideNoteKey? improvement.

Improve SideNoteKey?.

It is now generic type, so explicit type specification at
call site is no more needed.

Introduce SideNoteKey? interface.

Only Objects implementing that key may be used as side note keys.

Minor improvements.

Use strings instead of ValueControls? in several gui mappings.

File size: 5.1 KB
Line 
1package com.framsticks.parsers;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileNotFoundException;
6import java.io.InputStream;
7import java.util.LinkedList;
8import java.util.List;
9
10import javax.xml.parsers.DocumentBuilder;
11import javax.xml.parsers.DocumentBuilderFactory;
12
13import org.apache.logging.log4j.Logger;
14import org.apache.logging.log4j.LogManager;
15import org.w3c.dom.Document;
16import org.w3c.dom.Element;
17import org.w3c.dom.NamedNodeMap;
18import org.w3c.dom.Node;
19import org.w3c.dom.NodeList;
20
21import com.framsticks.params.Access;
22import com.framsticks.params.ParamFlags;
23import com.framsticks.params.PrimitiveParam;
24import com.framsticks.params.Registry;
25import com.framsticks.util.AutoBuilder;
26import com.framsticks.util.FramsticksException;
27import com.framsticks.util.lang.Strings;
28
29public class XmlLoader {
30        private static final Logger log = LogManager.getLogger(XmlLoader.class);
31
32        protected Registry registry = new Registry();
33
34        /**
35         *
36         */
37        public XmlLoader() {
38                registry.registerAndBuild(AutoInjector.class);
39        }
40
41        /**
42         * @return the registry
43         */
44        public Registry getRegistry() {
45                return registry;
46        }
47
48        boolean useLowerCase = false;
49
50        /**
51         * @param useLowerCase the useLowerCase to set
52         */
53        public void setUseLowerCase(boolean useLowerCase) {
54                this.useLowerCase = useLowerCase;
55        }
56
57        public String mangleName(String name) {
58                return useLowerCase ? name.toLowerCase() : name;
59        }
60
61        public String mangleAttribute(String name) {
62                return useLowerCase ? name.toLowerCase() : Strings.uncapitalize(name);
63        }
64
65        public Object processElement(Element element, Class<?> enclosingClass) {
66                final String name = mangleName(element.getNodeName());
67                if (name.equals("import")) {
68                        String className = element.getAttribute("class");
69                        try {
70                                registry.registerAndBuild(Class.forName(className));
71                                return null;
72                        } catch (ClassNotFoundException e) {
73                                throw new FramsticksException().msg("failed to import class").arg("name", name).cause(e);
74                        }
75                }
76                if (name.equals("include")) {
77                        String fileName = element.getAttribute("file");
78                        if (Strings.notEmpty(fileName)) {
79                                try {
80                                        return load(new FileInputStream(new File(fileName)), enclosingClass);
81                                } catch (FileNotFoundException e) {
82                                        throw new FramsticksException().msg("failed to include file").arg("file", fileName).cause(e);
83                                }
84                        }
85                        String resourceName = element.getAttribute("resource");
86                        if (Strings.notEmpty(resourceName)) {
87                                Class<?> javaClass = enclosingClass;
88                                String className = element.getAttribute("class");
89                                if (Strings.notEmpty(className)) {
90                                        try {
91                                                javaClass = Class.forName(className);
92                                        } catch (ClassNotFoundException e) {
93                                                throw new FramsticksException().msg("failed to find class for resource loading").arg("class name", className).cause(e);
94                                        }
95                                }
96
97                                return load(javaClass.getResourceAsStream(resourceName), enclosingClass);
98                        }
99                        throw new FramsticksException().msg("invalid <include/> node");
100                }
101
102                Access access = registry.createAccess(name);
103
104                Object object = access.createAccessee();
105                assert object != null;
106                access.select(object);
107
108                NamedNodeMap attributes = element.getAttributes();
109                for (int i = 0; i < attributes.getLength(); ++i) {
110                        Node attributeNode = attributes.item(i);
111                        PrimitiveParam<?> param = access.getFramsClass().getParamEntry(mangleAttribute(attributeNode.getNodeName()), PrimitiveParam.class);
112                        if (param.hasFlag(ParamFlags.READONLY)) {
113                                throw new FramsticksException().msg("cannot configure readonly param").arg("param", param).arg("in", access);
114                        }
115                        access.set(param, attributeNode.getNodeValue());
116                }
117
118                NodeList children = element.getChildNodes();
119                log.debug("found {} children in {}", children.getLength(), object);
120                for (int i = 0; i < children.getLength(); ++i) {
121                        Node childNode = children.item(i);
122                        if (!(childNode instanceof Element)) {
123                                continue;
124                        }
125                        Object childObject = processElement((Element) childNode, object.getClass());
126                        if (childObject == null) {
127                                continue;
128                        }
129
130                        List<Object> childrenObjects = new LinkedList<>();
131
132                        if (childObject instanceof AutoBuilder) {
133                                childrenObjects.addAll(((AutoBuilder) childObject).autoFinish());
134                        } else {
135                                childrenObjects.add(childObject);
136                        }
137
138                        for (Object child : childrenObjects) {
139                                access.tryAutoAppend(child);
140                        }
141                }
142                log.debug("loaded {}", object);
143
144                return object;
145        }
146
147        protected Object load(InputStream stream, Class<?> enclosingClass) {
148                try {
149                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
150                        DocumentBuilder db = factory.newDocumentBuilder();
151
152                        Document document = db.parse(stream);
153                        document.getDocumentElement().normalize();
154                        Element element = document.getDocumentElement();
155                        assert element != null;
156
157                        return processElement(element, enclosingClass);
158
159                } catch (Exception e) {
160                        throw new FramsticksException().msg("failed to load").cause(e);
161                }
162        }
163
164        public <T> T load(Class<T> type, InputStream stream) {
165                registry.registerAndBuild(type);
166
167                Object object = load(stream, type);
168                if (type.isAssignableFrom(object.getClass())) {
169                        return type.cast(object);
170                }
171                throw new FramsticksException().msg("invalid type has been loaded");
172        }
173}
174
Note: See TracBrowser for help on using the repository browser.