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

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

HIGHLIGHTS:

  • upgrade to Java 7
    • use try-multi-catch clauses
    • use try-with-resources were appropriate
  • configure FindBugs? (use mvn site and then navigate in browser to the report)
    • remove most bugs found
  • parametrize Dispatching environment (Dispatcher, RunAt?) to enforce more control on the place of closures actual call

CHANGELOG:
Rework FavouritesXMLFactory.

FindBugs?. Thread start.

FindBugs?. Minor change.

FindBugs?. Iterate over entrySet.

FindBugs?. Various.

FindBug?.

FindBug?. Encoding.

FindBug?. Final fields.

FindBug?.

Remove synchronization bug in ClientConnection?.

Experiments with findbugs.

Finish parametrization.

Make RunAt? an abstract class.

More changes in parametrization.

More changes in parametrizing dispatching.

Several changes to parametrize tasks.

Rename Runnable to RunAt?.

Add specific framsticks Runnable.

Add JSR305 (annotations).

Add findbugs reporting.

More improvements to ParamBuilder? wording.

Make FramsClass? accept also ParamBuilder?.

Change wording of ParamBuilder?.

Change wording of Request creation.

Use Java 7 exception catch syntax.

Add ScopeEnd? class.

Upgrade to Java 7.

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