summaryrefslogtreecommitdiffstats
blob: 10f493c4503e35e926135b7b439573a61ea59cef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.jdk.core.type;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import org.eclipse.osee.framework.jdk.core.util.Strings;

public class PropertyStoreWriter {
   private static final String TAG_SECTION = "store";
   private static final String TAG_NAME = "id";
   private static final String TAG_KEY = "key";
   private static final String TAG_VALUE = "value";
   private static final String TAG_LIST = "list";
   private static final String TAG_ITEM = "item";
   private static final String TAG_INNER = "inner.store";

   public void load(PropertyStore store, Reader reader) throws Exception {
      XMLReader xmlReader = new XMLReader();
      xmlReader.load(store, reader);
   }

   public void load(PropertyStore store, InputStream inputStream) throws Exception {
      load(store, new BufferedReader(new InputStreamReader(inputStream, "utf-8")));
   }

   public void save(PropertyStore store, OutputStream stream) throws IOException {
      XMLWriter writer = new XMLWriter(stream);
      internalSave(store, writer);
      writer.close();
   }

   public void save(PropertyStore store, Writer writer) {
      XMLWriter internalWriter = new XMLWriter(writer);
      internalSave(store, internalWriter);
   }

   private void internalSave(PropertyStore store, XMLWriter out) {
      Map<String, String> attributes = new HashMap<String, String>(2);
      String name = store.getId();
      attributes.put(TAG_NAME, name == null ? "" : name);
      out.startTag(TAG_SECTION, attributes);
      attributes.clear();

      Map<String, Object> items = store.getItems();
      for (Entry<String, Object> entry : items.entrySet()) {
         String key = entry.getKey();
         attributes.put(TAG_KEY, key == null ? "" : key);
         String value = (String) entry.getValue();
         attributes.put(TAG_VALUE, value == null ? "" : value);
         out.printTag(TAG_ITEM, attributes, true);
      }

      attributes.clear();
      Map<String, Object> arrayItems = store.getArrays();
      for (Entry<String, Object> entry : arrayItems.entrySet()) {
         String key = entry.getKey();
         attributes.put(TAG_KEY, key == null ? "" : key);
         out.startTag(TAG_LIST, attributes);

         String[] value = (String[]) entry.getValue();
         attributes.clear();
         if (value != null) {
            for (int index = 0; index < value.length; index++) {
               String item = value[index];
               attributes.put(TAG_VALUE, item == null ? "" : item);
               out.printTag(TAG_ITEM, attributes, true);
            }
         }
         out.endTag(TAG_LIST);
         attributes.clear();
      }
      attributes.clear();

      processInnerStores(store, out);

      out.endTag(TAG_SECTION);
   }

   private void processInnerStores(PropertyStore store, XMLWriter out) {
      Map<String, String> attributes = new HashMap<String, String>(2);
      Map<String, Object> properties = store.getPropertyStores();
      for (Entry<String, Object> entry : properties.entrySet()) {
         String key = entry.getKey();
         attributes.put(TAG_KEY, key == null ? "" : key);
         out.startTag(TAG_INNER, attributes);
         PropertyStore innerStore = (PropertyStore) entry.getValue();
         internalSave(innerStore, out);
         out.endTag(TAG_INNER);
      }
   }

   private static class XMLReader {
      private static final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
      private List<String> valueList;
      private String tagListKey;
      private boolean isInTagList;
      private final Stack<Pair<String, PropertyStore>> innerStoreStack;
      private String name;
      private String uri;

      public XMLReader() {
         isInTagList = false;
         valueList = null;
         tagListKey = null;
         innerStoreStack = new Stack<Pair<String, PropertyStore>>();
      }

      private boolean isInNestedStore() {
         return !innerStoreStack.isEmpty();
      }

      private PropertyStore getCurrentInnerStore() {
         return innerStoreStack.peek().getSecond();
      }

      public void load(PropertyStore store, Reader input) throws Exception {
         try {
            XMLStreamReader streamReader = inputFactory.createXMLStreamReader(input);
            while (streamReader.hasNext()) {
               process(store, streamReader);
               streamReader.next();
            }
         } finally {
            if (input != null) {
               input.close();
            }
         }
      }

      private void process(PropertyStore store, XMLStreamReader reader) {

         int eventType = reader.getEventType();
         switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
               name = reader.getLocalName();
               uri = reader.getNamespaceURI();
               if (TAG_SECTION.equals(name)) {
                  if (isInNestedStore()) {
                     getCurrentInnerStore().setId(reader.getAttributeValue(uri, TAG_NAME));
                  } else {
                     store.setId(reader.getAttributeValue(uri, TAG_NAME));
                  }
               } else if (TAG_ITEM.equals(name)) {
                  if (isInNestedStore()) {
                     processTagItemSection(uri, getCurrentInnerStore(), reader);
                  } else {
                     processTagItemSection(uri, store, reader);
                  }
               } else if (TAG_LIST.equals(name)) {
                  isInTagList = true;
                  tagListKey = reader.getAttributeValue(uri, TAG_KEY);
               } else if (TAG_INNER.equals(name)) {
                  String key = reader.getAttributeValue(uri, TAG_KEY);
                  innerStoreStack.add(new Pair<String, PropertyStore>(key, new PropertyStore()));
               }
               break;
            case XMLStreamConstants.END_ELEMENT:
               name = reader.getLocalName();
               uri = reader.getNamespaceURI();
               if (TAG_LIST.equals(name)) {
                  isInTagList = false;
                  if (Strings.isValid(tagListKey) && valueList != null && !valueList.isEmpty()) {
                     String[] value = valueList.toArray(new String[valueList.size()]);
                     if (isInNestedStore()) {
                        getCurrentInnerStore().put(tagListKey, value);
                     } else {
                        store.put(tagListKey, value);
                     }
                  }
                  valueList = null;
                  tagListKey = null;
               } else if (TAG_INNER.equals(name)) {
                  Pair<String, PropertyStore> completedPair = innerStoreStack.pop();
                  String completedKey = completedPair.getFirst();
                  PropertyStore completedStore = completedPair.getSecond();
                  if (isInNestedStore()) {
                     getCurrentInnerStore().put(completedKey, completedStore);
                  } else {
                     store.put(completedKey, completedStore);
                  }
               }
               break;
            case XMLStreamConstants.ENTITY_REFERENCE:
               name = reader.getLocalName();
               uri = reader.getNamespaceURI();
               break;
            default:
               break;
         }
      }

      private void processTagItemSection(String uri, PropertyStore store, XMLStreamReader reader) {
         String value = reader.getAttributeValue(uri, TAG_VALUE);
         if (isInTagList) {
            if (valueList == null) {
               valueList = new ArrayList<String>();
            }
            valueList.add(value);
         } else {
            String key = reader.getAttributeValue(uri, TAG_KEY);
            if (Strings.isValid(key)) {
               store.put(key, value);
            }
         }
      }
   }

   private static class XMLWriter extends PrintWriter {
      private static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
      private int tab;

      public XMLWriter(Writer writer) {
         super(writer);
         tab = 0;
         println(XML_VERSION);
      }

      public XMLWriter(OutputStream output) throws UnsupportedEncodingException {
         this(new OutputStreamWriter(output, "UTF8"));
      }

      public void endTag(String name) {
         tab--;
         printTag("/" + name, null, false);
      }

      private void printTabulation() {
         for (int i = 0; i < tab; i++) {
            super.print('\t');
         }
      }

      public void printTag(String name, Map<String, String> parameters, boolean close) {
         printTag(name, parameters, false, false, close);
      }

      private void printTag(String name, Map<String, String> parameters, boolean shouldTab, boolean newLine, boolean close) {
         StringBuffer sb = new StringBuffer();
         sb.append('<');
         sb.append(name);
         if (parameters != null) {
            for (Enumeration<String> e = Collections.enumeration(parameters.keySet()); e.hasMoreElements();) {
               sb.append(" ");
               String key = e.nextElement();
               sb.append(key);
               sb.append("=\"");
               sb.append(getEscaped(String.valueOf(parameters.get(key))));
               sb.append("\"");
            }
         }
         if (close) {
            sb.append('/');
         }
         sb.append('>');
         if (shouldTab) {
            printTabulation();
         }
         if (newLine) {
            println(sb.toString());
         } else {
            print(sb.toString());
         }
      }

      public void startTag(String name, Map<String, String> parameters) {
         startTag(name, parameters, true);
         tab++;
      }

      private void startTag(String name, Map<String, String> parameters, boolean newLine) {
         printTag(name, parameters, true, newLine, false);
      }

      private static void appendEscapedChar(StringBuffer buffer, char c) {
         String replacement = getReplacement(c);
         if (replacement != null) {
            buffer.append('&');
            buffer.append(replacement);
            buffer.append(';');
         } else {
            buffer.append(c);
         }
      }

      private static String getEscaped(String s) {
         StringBuffer result = new StringBuffer(s.length() + 10);
         for (int i = 0; i < s.length(); ++i) {
            appendEscapedChar(result, s.charAt(i));
         }
         return result.toString();
      }

      private static String getReplacement(char character) {
         // Encode special XML characters into the equivalent character references.
         // The first five are defined by default for all XML documents.
         // The next three (#xD, #xA, #x9) are encoded to avoid them
         // being converted to spaces on deserialization
         switch (character) {
            case '<':
               return "lt";
            case '>':
               return "gt";
            case '"':
               return "quot";
            case '\'':
               return "apos";
            case '&':
               return "amp";
            case '\r':
               return "#x0D";
            case '\n':
               return "#x0A";
            case '\u0009':
               return "#x09";
         }
         return null;
      }
   }
}