Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 79e96f5d250b5d0c73a5d651de4f9cf13061ebbf (plain) (blame)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*******************************************************************************
 *  Copyright (c) 2007, 2017 IBM Corporation and others.
 *
 *  This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License 2.0
 *  which accompanies this distribution, and is available at
 *  https://www.eclipse.org/legal/epl-2.0/
 *
 *  SPDX-License-Identifier: EPL-2.0
 * 
 *  Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.persistence;

import static java.util.stream.Collectors.joining;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.eclipse.equinox.p2.metadata.Version;

public class XMLWriter implements XMLConstants {

	public static class ProcessingInstruction {

		private String target;
		private String[] data;

		// The standard UTF-8 processing instruction
		public static final String XML_UTF8 = "<?xml version='1.0' encoding='UTF-8'?>"; //$NON-NLS-1$

		public ProcessingInstruction(String target, String[] attrs, String[] values) {
			// Lengths of attributes and values must be the same
			this.target = target;
			this.data = new String[attrs.length];
			for (int i = 0; i < attrs.length; i++) {
				data[i] = attributeImage(attrs[i], values[i]);
			}
		}

		public static ProcessingInstruction makeTargetVersionInstruction(String target, Version version) {
			return new ProcessingInstruction(target, new String[] {PI_VERSION_ATTRIBUTE}, new String[] {version.toString()});
		}

		@Override
		public String toString() {
			StringBuilder sb = new StringBuilder("<?"); //$NON-NLS-1$
			sb.append(this.target).append(' ');
			for (int i = 0; i < data.length; i++) {
				sb.append(this.data[i]);
				if (i < data.length - 1) {
					sb.append(' ');
				}
			}
			sb.append("?>"); //$NON-NLS-1$
			return sb.toString();
		}
	}

	private Stack<String> elements; // XML elements that have not yet been closed
	private boolean open; // Can attributes be added to the current element?
	private String indent; // used for each level of indentation

	private PrintWriter pw;

	public XMLWriter(OutputStream output, ProcessingInstruction[] piElements) {
		this.pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8)), false);
		println(ProcessingInstruction.XML_UTF8);
		this.elements = new Stack<>();
		this.open = false;
		this.indent = "  "; //$NON-NLS-1$
		if (piElements != null) {
			for (int i = 0; i < piElements.length; i++) {
				println(piElements[i].toString());
			}
		}
	}

	// start a new element
	public void start(String name) {
		if (this.open) {
			println('>');
		}
		indent();
		print('<');
		print(name);
		this.elements.push(name);
		this.open = true;
	}

	// end the most recent element with this name
	public void end(String name) {
		if (this.elements.empty()) {
			throw new EndWithoutStartError();
		}
		int index = this.elements.search(name);
		if (index == -1) {
			throw new EndWithoutStartError(name);
		}
		for (int i = 0; i < index; i += 1) {
			end();
		}
	}

	// end the current element
	public void end() {
		if (this.elements.empty()) {
			throw new EndWithoutStartError();
		}
		String name = this.elements.pop();
		if (this.open) {
			println("/>"); //$NON-NLS-1$
		} else {
			printlnIndented("</" + name + '>', false); //$NON-NLS-1$
		}
		this.open = false;
	}

	public static String escape(String txt) {
		StringBuffer buffer = null;
		for (int i = 0; i < txt.length(); ++i) {
			String replace;
			char c = txt.charAt(i);
			switch (c) {
				case '<' :
					replace = "&lt;"; //$NON-NLS-1$
					break;
				case '>' :
					replace = "&gt;"; //$NON-NLS-1$
					break;
				case '"' :
					replace = "&quot;"; //$NON-NLS-1$
					break;
				case '\'' :
					replace = "&apos;"; //$NON-NLS-1$
					break;
				case '&' :
					replace = "&amp;"; //$NON-NLS-1$
					break;
				case '\t' :
					replace = "&#x9;"; //$NON-NLS-1$
					break;
				case '\n' :
					replace = "&#xA;"; //$NON-NLS-1$
					break;
				case '\r' :
					replace = "&#xD;"; //$NON-NLS-1$
					break;
				default :
					// this is the set of legal xml scharacters in unicode excluding high surrogates since they cannot be represented with a char
					// see http://www.w3.org/TR/REC-xml/#charsets
					if ((c >= '\u0020' && c <= '\uD7FF') || (c >= '\uE000' && c <= '\uFFFD')) {
						if (buffer != null)
							buffer.append(c);
						continue;
					}
					replace = Character.isWhitespace(c) ? " " : null; //$NON-NLS-1$
			}
			if (buffer == null) {
				buffer = new StringBuffer(txt.length() + 16);
				buffer.append(txt.substring(0, i));
			}
			if (replace != null)
				buffer.append(replace);
		}

		if (buffer == null)
			return txt;

		return buffer.toString();
	}

	// write a boolean attribute if it doesn't have the default value
	public void attribute(String name, boolean value, boolean defaultValue) {
		if (value != defaultValue) {
			attribute(name, value);
		}
	}

	public void attribute(String name, boolean value) {
		attribute(name, Boolean.toString(value));
	}

	public void attribute(String name, int value) {
		attribute(name, Integer.toString(value));
	}

	public void attributeOptional(String name, String value) {
		if (value != null && value.length() > 0) {
			attribute(name, value);
		}
	}

	public void attribute(String name, Object value) {
		if (!this.open) {
			throw new AttributeAfterNestedContentError();
		}
		if (value == null) {
			return; // optional attribute with no value
		}
		print(' ');
		print(name);
		print("='"); //$NON-NLS-1$
		print(escape(value.toString()));
		print('\'');
	}

	public void cdata(String data) {
		cdata(data, true);
	}

	public void cdata(String data, boolean escape) {
		if (this.open) {
			println('>');
			this.open = false;
		}
		if (data != null) {
			printlnIndented(data, escape);
		}
	}

	public void flush() {
		this.pw.flush();
	}

	public void writeProperties(Map<String, ?> properties) {
		writeProperties(PROPERTIES_ELEMENT, properties);
	}

	public void writeProperties(String propertiesElement, Map<String, ?> properties) {
		if (properties == null || properties.isEmpty()) {
			return;
		}

		start(propertiesElement);
		attribute(COLLECTION_SIZE_ATTRIBUTE, properties.size());
		properties.forEach(this::writeProperty);
		end();
	}

	public void writeProperty(String name, Object value) {
		String type;
		String valueStr;

		if (Collection.class.isAssignableFrom(value.getClass())) {
			Collection<?> coll = (Collection<?>) value;

			type = PROPERTY_TYPE_LIST;
			String elType = resolvePropertyType(coll.iterator().next());
			if (elType != null) {
				type += String.format("<%s>", elType); //$NON-NLS-1$
			}

			valueStr = coll.stream().map(Object::toString).collect(joining(",")); //$NON-NLS-1$
		} else {
			type = resolvePropertyType(value);
			valueStr = value.toString();
		}

		start(PROPERTY_ELEMENT);
		attribute(PROPERTY_NAME_ATTRIBUTE, name);
		attribute(PROPERTY_VALUE_ATTRIBUTE, valueStr);
		attributeOptional(PROPERTY_TYPE_ATTRIBUTE, type);
		end();
	}

	private String resolvePropertyType(Object value) {
		if (value instanceof Integer) {
			return PROPERTY_TYPE_INTEGER;
		}
		if (value instanceof Long) {
			return PROPERTY_TYPE_LONG;
		}
		if (value instanceof Float) {
			return PROPERTY_TYPE_FLOAT;
		}
		if (value instanceof Double) {
			return PROPERTY_TYPE_DOUBLE;
		}
		if (value instanceof Byte) {
			return PROPERTY_TYPE_BYTE;
		}
		if (value instanceof Short) {
			return PROPERTY_TYPE_SHORT;
		}
		if (value instanceof Character) {
			return PROPERTY_TYPE_CHARACTER;
		}
		if (value instanceof Boolean) {
			return PROPERTY_TYPE_BOOLEAN;
		}
		if (value instanceof Version) {
			return PROPERTY_TYPE_VERSION;
		}

		// Null is read back as String
		// NOTE: Using string as default is needed for backward compatibility with properties that are always String like
		// the IU properties
		return null;
	}

	protected static String attributeImage(String name, String value) {
		if (value == null) {
			return ""; // optional attribute with no value //$NON-NLS-1$
		}
		return name + "='" + escape(value) + '\''; //$NON-NLS-1$
	}

	private void println(char c) {
		this.pw.println(c);
	}

	private void println(String s) {
		this.pw.println(s);
	}

	private void println() {
		this.pw.println();
	}

	private void print(char c) {
		this.pw.print(c);
	}

	private void print(String s) {
		this.pw.print(s);
	}

	private void printlnIndented(String s, boolean escape) {
		if (s.length() == 0) {
			println();
		} else {
			indent();
			println(escape ? escape(s) : s);
		}
	}

	private void indent() {
		for (int i = this.elements.size(); i > 0; i -= 1) {
			print(this.indent);
		}
	}

	public static class AttributeAfterNestedContentError extends Error {
		private static final long serialVersionUID = 1L; // not serialized
	}

	public static class EndWithoutStartError extends Error {
		private static final long serialVersionUID = 1L; // not serialized
		private String name;

		public EndWithoutStartError() {
			super();
		}

		public EndWithoutStartError(String name) {
			super();
			this.name = name;
		}

		public String getName() {
			return this.name;
		}
	}

}

Back to the top