source: java/main/src/main/java/com/framsticks/leftovers/FavouritesXMLFactory.java @ 88

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

HIGHLIGHTS:

  • loading f0 schema with XmlLoader?
  • use XmlLoader? to load configuration
  • introduce unified fork-join model of various entities

(Instances, Connections, GUI Frames, etc.),
all those entities clean up gracefully on
shutdown, which may be initialized by user
or by some entity

  • basing on above, simplify several organizing classes

(Observer, main class)

(to host native frams server process from Java level)

CHANGELOG:
Remove redundant Observer class.

Clean up in AbstractJoinable?.

Update ExternalProcess? class to changes in joining model.

Another sweep through code with FindBugs?.

Find bug with not joining RemoteInstance?.

Joining almost works.

Much improved joining model.

More improvement to joining model.

Add logging messages around joinable operations.

Rename methods in AbstractJoinable?.

Improve Joinable.

Rewrite of entity structure.

More simplifications with entities.

Further improve joinables.

Let Frame compose from JFrame instead of inheriting.

Add join classes.

Improvements of closing.

Add Builder interface.

Add FramsServerTest?.xml

FramsServer? may be configured through xml.

Make Framsticks main class an Observer of Entities.

Make Observer a generic type.

Remove variables regarding to removed endpoint.

Simplify observer (remove endpoints).

More changes to Observer and Endpoint.

Minor improvements.

Add OutputListener? to ExternalProcess?.

Improve testing of ExternalProcess?.

Add ExternalProcess? runner.

Rename the Program class to Framsticks.

Migrate Program to use XmlLoader? configuration.

First steps with configuration using XmlLoader?.

Fix several bugs.

Move all f0 classes to apriopriate package.

XmlLoader? is able to load Schema.

XmlLoader? is loading classes and props.

Add GroupBuilder?.

File size: 7.4 KB
Line 
1package com.framsticks.leftovers;
2
3import java.io.BufferedWriter;
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.FileNotFoundException;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.OutputStreamWriter;
11import java.nio.file.Files;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.LinkedHashMap;
16import java.util.Map;
17
18import javax.xml.parsers.DocumentBuilder;
19import javax.xml.parsers.DocumentBuilderFactory;
20import javax.xml.parsers.ParserConfigurationException;
21import javax.xml.stream.XMLOutputFactory;
22import javax.xml.stream.XMLStreamException;
23import javax.xml.stream.XMLStreamWriter;
24
25import org.apache.log4j.Logger;
26import org.w3c.dom.Document;
27import org.w3c.dom.Node;
28import org.w3c.dom.NodeList;
29import org.xml.sax.SAXException;
30
31import com.framsticks.util.FramsticksException;
32import com.framsticks.util.io.Encoding;
33
34public class FavouritesXMLFactory {
35        private static final Logger log = Logger.getLogger(FavouritesXMLFactory.class);
36
37        private static final String PATH_MARK = "path";
38        private static final String NAME_MARK = "name";
39        private static final String FIELD_MARK = "field";
40        private static final String TYPE_MARK = "type";
41
42        public static Node readDocument(InputStream stream) {
43                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
44                try {
45                        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
46                        Document doc = docBuilder.parse(stream);
47                        doc.getDocumentElement().normalize();
48                        return doc.getFirstChild();
49                } catch (ParserConfigurationException | SAXException | IOException e) {
50                        throw new FramsticksException().cause(e);
51                }
52        }
53
54        public static Node readDocument(String filename) {
55                File file = new File(filename);
56                if (!file.exists()) {
57                        throw new FramsticksException().msg("file does not exist");
58                }
59                try {
60                        return readDocument(new FileInputStream(file));
61                } catch (FileNotFoundException e) {
62                        throw new FramsticksException().cause(e);
63                }
64        }
65
66        public static class XmlWriter implements AutoCloseable {
67
68                BufferedWriter writer = null;
69                XMLStreamWriter xml = null;
70
71                public XmlWriter(String filename) throws XMLStreamException,
72                                IOException {
73                        XMLOutputFactory factory = XMLOutputFactory.newInstance();
74
75                        File file = new File(filename);
76                        Files.deleteIfExists(file.toPath());
77
78                        writer = new BufferedWriter(new OutputStreamWriter(
79                                        new FileOutputStream(file),
80                                        Encoding.getDefaultCharset()));
81                        xml = factory.createXMLStreamWriter(writer);
82
83                        xml.writeStartDocument("1.0");
84                }
85
86                public void close() {
87                        try {
88                                xml.writeEndDocument();
89                                xml.flush();
90                                xml.close();
91                                writer.close();
92                        } catch (XMLStreamException | IOException e) {
93                                log.error(e);
94                        }
95                }
96
97                public void start(String name) throws XMLStreamException {
98                        xml.writeStartElement(name);
99                }
100
101                public void element(String name, Object value) throws XMLStreamException {
102                        start(name);
103                        xml.writeCharacters(value.toString());
104                        end();
105                }
106
107                public void end() throws XMLStreamException {
108                        xml.writeEndElement();
109                }
110
111                public void attribute(String name, Object value) throws XMLStreamException {
112                        xml.writeAttribute(name, value.toString());
113                }
114        }
115
116        /**
117         * Writes favourites nodes and fields list to XML file.
118         *
119         * @param path
120         *            Path of XML file.
121         * @param nodes
122         *            Collection of user favourites nodes and fields.
123         */
124        public void writeFavouritesXML(String path, Collection<UserFavourite> nodes) {
125                if (nodes.isEmpty()) {
126                        return;
127                }
128
129                try (XmlWriter xml = new XmlWriter(path)) {
130                        xml.start("framsticks");
131                        for (UserFavourite node : nodes) {
132                                xml.start("item");
133
134                                xml.element(PATH_MARK, node.getPath());
135                                xml.element(NAME_MARK, node.getName());
136
137                                /*if(node.isFavouriteNode()){
138                                        xmlWriter.writeStartElement(typeMark);
139                                        xmlWriter.writeCharacters(Integer.toString(node.getNodeType().getId()));
140                                        xmlWriter.writeEndElement();
141                                }else{ //isFavouriteField() */
142                                xml.element(FIELD_MARK, node.getField());
143                                xml.end();
144                        }
145                        xml.end();
146                } catch (XMLStreamException | IOException e) {
147                        log.error(e);
148                }
149        }
150
151        /**
152         * Reads user favourites nodes and fields from XML file.
153         *
154         * @param filePath
155         *            PAth to XML file.
156         * @return LinkedHashMap contains user favourites nodes and fields. Key is
157         *         concatenation of path and field getName.
158         */
159        public LinkedHashMap<String, UserFavourite> readFavouritesXML(
160                        String filePath) {
161
162                Node root = readDocument(filePath);
163                if (root == null) {
164                        return null;
165                }
166                LinkedHashMap<String, UserFavourite> result = new LinkedHashMap<String, UserFavourite>();
167
168                NodeList items = root.getChildNodes();
169                UserFavourite userNode;
170                String path, name, field;
171                for (int i = 0; i < items.getLength(); i++) {
172                        Node item = items.item(i);
173                        NodeList itemDetails = item.getChildNodes();
174                        if (itemDetails.getLength() == 3) {
175                                if (itemDetails.item(0).getNodeName().equals(PATH_MARK)
176                                                && itemDetails.item(1).getNodeName().equals(NAME_MARK)
177                                                && (itemDetails.item(2).getNodeName().equals(FIELD_MARK)
178                                                                || itemDetails.item(2).getNodeName().equals(TYPE_MARK))) {
179                                        path = itemDetails.item(0).getTextContent();
180                                        name = itemDetails.item(1).getTextContent();
181                                        if (itemDetails.item(2).getNodeName().equals(
182                                                        FIELD_MARK)) {
183                                                field = itemDetails.item(2).getTextContent();
184                                                userNode = new UserFavourite(path, name, field);
185                                                result.put(path+field, userNode);
186                                        }else{
187                                                try {
188                                                        // int nodeTypeId = Integer.parseInt(itemDetails.item(2).getTextContent());
189                                                        userNode = new UserFavourite(path, name, null);
190                                                        result.put(path, userNode);
191                                                } catch (Exception e) {
192                                                }
193                                        }
194                                }
195                        }
196                }
197
198                return result;
199        }
200
201        /**
202         * Writes column configuration to XML file.
203         *
204         * @param path
205         *            Path to XML file.
206         * @param groupColumns
207         *            Map with column configuration. Key - path to group node. Value -
208         *            List of columns getId.
209         */
210        public void writeColumnConfigurationXML(String path,
211                        Map<String, ArrayList<String>> groupColumns) {
212                if (groupColumns.isEmpty()) {
213                        return;
214                }
215                try (XmlWriter xml = new XmlWriter(path)) {
216                        xml.start("framsticks");
217                        for (Map.Entry<String, ArrayList<String>> i : groupColumns.entrySet()) {
218                                xml.start("item");
219                                xml.attribute(PATH_MARK, i.getKey());
220                                for (String column : i.getValue()) {
221                                        xml.element("column", column);
222                                }
223                                xml.end();
224                        }
225                        xml.end();
226                } catch (XMLStreamException | IOException e) {
227                        log.error(e);
228                }
229        }
230
231        /**
232         * Reads column configuration from XML file.
233         *
234         * @param path
235         *            Path to XML file.
236         * @return HashMap with configuration. Key - path to group node. Value -
237         *         List of columns getId.
238         */
239        public HashMap<String, ArrayList<String>> readColumnConfigurationXML(
240                        String path) {
241                Node root = readDocument(path);
242                if (root == null) {
243                        return null;
244                }
245
246                HashMap<String, ArrayList<String>> result = new LinkedHashMap<String, ArrayList<String>>();
247
248                NodeList items = root.getChildNodes();
249                String itemPath;
250                ArrayList<String> columns;
251                for (int i = 0; i < items.getLength(); i++) {
252                        Node item = items.item(i);
253                        itemPath = item.getAttributes().getNamedItem(PATH_MARK)
254                                        .getNodeValue();
255                        columns = new ArrayList<String>();
256                        NodeList itemDetails = item.getChildNodes();
257                        for (int j = 0; j < itemDetails.getLength(); j++) {
258                                columns.add(itemDetails.item(j).getTextContent());
259                        }
260                        result.put(itemPath, columns);
261                }
262                return result;
263        }
264}
Note: See TracBrowser for help on using the repository browser.