Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a907169f871dfc23bf601c839609fe375a29a079 (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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*******************************************************************************
 * Copyright (c) 2006, 2013 Soyatec (http://www.soyatec.com), CEA, and others.
 * 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:
 *     Soyatec - initial API and implementation
 *     Christian W. Damus (CEA) - Fix failure to propagate stream handlers of URLs (CDO)
 *******************************************************************************/
package org.eclipse.papyrus.xwt.internal.xml;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.eclipse.papyrus.xwt.IConstants;
import org.eclipse.papyrus.xwt.XWTException;

/**
 * @author yyang
 * @since 1.0
 */
public class DocumentRoot {

	/**
	 * The file type(Can be resolved by java.io.File)
	 */
	public static final int TYPE_FILE = 0;

	/**
	 * The path type(Can be resolved by java.net.URL)
	 */
	public static final int TYPE_PATH = 1;

	/**
	 * The zip format.
	 */
	public static final int FORMAT_ZIP = 2;

	/**
	 * The gzip format.
	 */
	public static final int FORMAT_GZIP = 3;

	/**
	 * The plain format.
	 */
	public static final int FORMAT_NONE = 4;

	private int type = TYPE_PATH;

	private int format = FORMAT_NONE;

	/**
	 * The absolute path.
	 */
	private String basePath;

	/**
	 * The relative path.
	 */
	private URL baseURL;

	/**
	 * The main file name.
	 */
	private String baseFile;

	private static URL DOCUMENT_ROOT;

	static {
		try {
			DOCUMENT_ROOT = new File(System.getProperty("user.dir")).toURI().toURL();
		} catch (MalformedURLException e) {
			DOCUMENT_ROOT = null;
		}
	}

	public DocumentRoot() {
		reset();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.soyatec.xaml.IDocumentRoot#getFormat()
	 */
	public int getFormat() {
		return format;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.soyatec.xaml.IDocumentRoot#getType()
	 */
	public int getType() {
		return type;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.soyatec.xaml.IDocumentRoot#getPath()
	 */
	public URL getPath() {
		return baseURL;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.soyatec.xaml.IDocumentRoot#getFile()
	 */
	public String getFile() {
		return baseFile;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.soyatec.xaml.IDocumentRoot#openStream()
	 */
	public InputStream openStream() throws IOException {
		switch(format) {
		case FORMAT_GZIP:
			return new GZIPInputStream(new URL(basePath + "/" + baseFile).openStream());
		default:
			return new URL(baseURL, basePath + "/" + baseFile).openStream(); // preserve the stream handler
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.soyatec.xaml.IDocumentRoot#openStream(java.lang.String)
	 */
	public InputStream openStream(String path) throws IOException {
		assert path != null;
		InputStream in = null;

		if(path.indexOf(':') < 0) {
			if(format == FORMAT_ZIP) {
				// If it is zip format, that means all directories and files in
				// zip file are extracted to temporary directory.
				File file = new File(basePath + "/" + path);
				in = new FileInputStream(file);
			} else {
				// Else, maybe the file parent or url path.
				switch(type) {
				case TYPE_FILE:
					File file;
					if(path.startsWith("/")) {
						// Use absolute path
						file = new File(path);
					} else {
						// Use relative path
						file = new File(basePath + "/" + path);
					}
					in = new FileInputStream(file);
					break;
				case TYPE_PATH:
					URL url = new URL(basePath + "/" + path);
					in = url.openStream();
					break;
				}
			}
		} else {
			if(path.startsWith("classpath:")) {
				// Use class path
				String p = path.substring(10);
				in = getClass().getResourceAsStream(p);
				if(in == null) {
					in = String.class.getResourceAsStream(p);
				}
				if(in == null) {
					in = Thread.currentThread().getClass().getResourceAsStream(p);
				}
				if(in == null) {
					throw new IOException("File not found in classpath: " + p);
				}
			} else {
				File file = new File(path);
				if(file.exists()) {
					// Use Windows File path. For example, G:\\somefile.txt
					in = new FileInputStream(file);
				} else {
					// Use URL path
					in = new URL(path).openStream();
				}
			}
		}

		// Automatically select the stream type
		PushbackInputStream pis = new PushbackInputStream(in, 4);
		if(Format.isGZIP(pis)) {
			return new GZIPInputStream(pis);
		} else if(Format.isZIP(pis)) {
			ZipInputStream zis = new ZipInputStream(pis);
			// Skip entry of directory or file which contains directory
			// path("someDirectory/someFile.suffix").
			for(ZipEntry entry = zis.getNextEntry(); entry != null && (entry.isDirectory() || entry.getName().indexOf('/') != -1); entry = zis.getNextEntry());
			return zis;
		} else {
			return pis;
		}
	}

	/**
	 * This method is used in <code>ModelLoader</code>
	 * 
	 * @param file
	 *        the xaml file path.
	 */
	protected void init(InputStream inputStream, URL url) throws IOException {
		File file = null;
		
		try {
			file = "file".equals(url.getProtocol()) ? new File(url.toURI()) : null;
		} catch (URISyntaxException e) {
			// not a valid file URL.  Fine
		}
		
		if((inputStream == null) && (file != null) && file.exists()) {
			// Is file
			init(file);
		} else {
			// Is URL
			basePath = null;
			baseURL = url;
			PushbackInputStream pis = null;
			boolean shouldClose_pis = false;
			if(inputStream instanceof PushbackInputStream) {
				pis = (PushbackInputStream)inputStream;
			} else {
				if(inputStream == null) {
					pis = new PushbackInputStream(baseURL.openStream(), 4);
					shouldClose_pis = true;
				} else {
					pis = new PushbackInputStream(inputStream, 4);
				}
			}
			if(Format.isGZIP(pis)) {
				format = FORMAT_GZIP;
			} else if(Format.isZIP(pis)) {
				format = FORMAT_ZIP;
				File tempDir = extractZipToTemporary(pis);
				basePath = "file:/" + tempDir.getAbsolutePath();
				baseFile = getMainFile(tempDir);
			}
			if(shouldClose_pis) {
				pis.close();
			}

			if(basePath == null) {
				String path = url.toString();
				while(path.endsWith("/")) {
					path = path.substring(0, path.length() - 1);
				}

				int lastIndex = path.lastIndexOf("/");
				if(lastIndex > 0) {
					basePath = path.substring(0, lastIndex);
					baseFile = path.substring(lastIndex + 1);
					baseURL = new URL(url, basePath); // be sure to preserve the stream handler
				} else {
					basePath = System.getProperty("user.dir");
					baseURL = new File(basePath).toURI().toURL();
					baseFile = path;
				}
			}

			type = TYPE_PATH;
		}
	}

	/**
	 * This method is used in <code>ModelLoader</code>
	 */
	protected void reset() {
		type = TYPE_PATH;
		format = FORMAT_NONE;
		baseURL = DOCUMENT_ROOT;
		basePath = DOCUMENT_ROOT.toString();
		baseFile = null;
	}

	/**
	 * This method is used in <code>ModelLoader</code>
	 * 
	 * @param file
	 *        the XAML file.
	 */
	private void init(File file) throws IOException {
		FileInputStream fis = new FileInputStream(file);
		PushbackInputStream pis = new PushbackInputStream(fis, 4);
		baseURL = file.getParentFile().toURI().toURL();
		basePath = baseURL.toString();
		baseFile = file.getName();
		if(Format.isGZIP(pis)) {
			format = FORMAT_GZIP;
		} else if(Format.isZIP(pis)) {
			format = FORMAT_ZIP;
			File tempDir = extractZipToTemporary(pis);
			basePath = "file:/" + tempDir.getAbsolutePath();
			baseFile = getMainFile(tempDir);
			baseURL = file.toURI().toURL();
		}

		type = TYPE_FILE;
	}

	private String getMainFile(File tempDir) {
		File[] tempFiles = tempDir.listFiles(new FileFilter() {

			public boolean accept(File pathname) {
				return pathname.isFile() && pathname.getName().toLowerCase().endsWith(IConstants.XWT_EXTENSION_SUFFIX);
			}
		});
		for(File tempFile : tempFiles) {
			return tempFile.getName();
		}
		return null;
	}

	/**
	 * Extract zip stream to temporary directory.
	 * 
	 * @param stream
	 *        zip stream.
	 * @return Returns the directory file the zip stream extracted.
	 */
	private File extractZipToTemporary(InputStream stream) throws IOException {
		File file = new File(System.getProperty("java.io.tmpdir") + "/cb" + System.currentTimeMillis() + Math.random());
		if(!file.mkdir()) {
			throw new XWTException("Folder creation fails: " + file.toString());
		}
		file.deleteOnExit();

		String directory = file.getAbsolutePath();
		ZipInputStream in = new ZipInputStream(stream);
		ZipEntry z;
		while((z = in.getNextEntry()) != null) {
			if(z.isDirectory()) {
				String name = z.getName();
				name = name.substring(0, name.length() - 1);
				File f = new File(directory + File.separator + name);
				if(!f.mkdir()) {
					throw new XWTException("Folder creation fails: " + f.toString());
				}
				f.deleteOnExit();
			} else {
				File f = new File(directory + File.separator + z.getName());
				if(!f.createNewFile()) {
					throw new XWTException("File creation fails: " + f.toString());
				}
				f.deleteOnExit();
				FileOutputStream out = new FileOutputStream(f);
				byte[] cache = new byte[4096];
				for(int i = in.read(cache); i != -1; i = in.read(cache)) {
					out.write(cache, 0, i);
				}
				out.close();
			}
		}
		in.close();

		return file;
	}

	/**
	 * File format uitility.
	 * <p>
	 * To check the format of file or stream.
	 * </p>
	 * 
	 */
	static class Format {

		/**
		 * Check the stream is a gzip format or not.
		 * 
		 * @param stream
		 *        the checked stream.
		 * @return Returns true is the stream is a gzip format.
		 */
		public static boolean isGZIP(PushbackInputStream stream) throws IOException {
			assert stream != null;

			byte[] cachedBytes = new byte[2];
			if(stream.read(cachedBytes) != cachedBytes.length) {
				throw new RuntimeException("data content wrong.");
			}
			stream.unread(cachedBytes);
			// GZIP's header data starts with two bytes{1F,8B},
			if((cachedBytes[0] & 0xff) == 0x1f && (cachedBytes[1] & 0xff) == 0x8b) {
				return true;
			} else {
				return false;
			}
		}

		/**
		 * Check the file is a gzip format or not.
		 * 
		 * @param file
		 *        the checked file.
		 * @return Returns true is the file is a gzip format.
		 */
		public static boolean isGZIP(File file) throws IOException {
			assert file != null;

			FileInputStream fis = new FileInputStream(file);
			PushbackInputStream pis = new PushbackInputStream(fis, 2);
			boolean returnValue = isGZIP(pis);
			pis.close();
			return returnValue;
		}

		/**
		 * Check the stream is a zip format or not.
		 * 
		 * @param stream
		 *        the checked stream.
		 * @return Returns true is the stream is a zip format.
		 */
		public static boolean isZIP(PushbackInputStream stream) throws IOException {
			assert stream != null;

			byte[] cachedBytes = new byte[4];
			if(stream.read(cachedBytes) != cachedBytes.length) {
				throw new RuntimeException("data content wrong.");
			}
			stream.unread(cachedBytes);
			// ZIP's header data starts with four bytes{0x50, 0x4b, 0x03, 0x04},
			if((cachedBytes[0] & 0xff) == 0x50 && (cachedBytes[1] & 0xff) == 0x4b && (cachedBytes[2] & 0xff) == 0x03 && (cachedBytes[3] & 0xff) == 0x04) {
				return true;
			} else {
				return false;
			}
		}

		/**
		 * Check the file is a zip format or not.
		 * 
		 * @param file
		 *        the checked file.
		 * @return Returns true is the file is a zip format.
		 */
		public static boolean isZIP(File file) throws IOException {
			assert file != null;

			FileInputStream fis = new FileInputStream(file);
			PushbackInputStream pis = new PushbackInputStream(fis, 4);
			boolean returnValue = isZIP(pis);
			pis.close();
			return returnValue;
		}
	}
}

Back to the top