Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 2433b119611dc13a2f33a9a2a5e99ffe6eac8a26 (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
/*******************************************************************************
 * Copyright (c) 2006 Sybase, Inc. 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:
 *     Sybase, Inc. - initial API and implementation
 *******************************************************************************/
package org.eclipse.jst.pagedesigner.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.Map.Entry;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.jst.jsf.common.ui.IFileFolderConstants;
import org.eclipse.jst.jsf.common.ui.internal.logging.Logger;
import org.eclipse.jst.jsf.common.ui.internal.utils.PathUtil;
import org.eclipse.jst.pagedesigner.PDPlugin;
import org.eclipse.jst.pagedesigner.css2.property.ICSSPropertyID;
import org.eclipse.ui.IEditorInput;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author mengbo
 */
public class PreviewUtil {
	/** Create the logger for this class */
	private static Logger _log = PDPlugin.getLogger(PreviewUtil.class);

	/** line separator */
	public static final String LINE_SEPARATOR = System
			.getProperty("line.separator"); //$NON-NLS-1$

	/** web root path */
	private final static String WEBROOT_PATH = null;

	/** the file being previewed */
	private static IFile CURRENT_FILE = null;

	/** the property bundel */
	private static PropertyResourceBundle BUNDLE = null;

	/** the property bundel map used for loadbundle preview action */
	private static Map BUNDLE_MAP = null;

	/** the variable name used for loadbundel preview action */
	private static String VAR = null;

	/** key is prefix value is uri */
	private static Map _taglibMap = new HashMap();


	/**
	 * @return the current bundle
	 */
	public static final PropertyResourceBundle getBUNDLE() {
        return BUNDLE;
    }

    /**
     * @param bundle
     */
    public static final void setBUNDLE(PropertyResourceBundle bundle) {
        BUNDLE = bundle;
    }

    /**
     * @return the current bundle map
     */
    public static final Map getBUNDLE_MAP() {
        return BUNDLE_MAP;
    }

    /**
     * @param bundle_map
     */
    public static final void setBUNDLE_MAP(Map bundle_map) {
        BUNDLE_MAP = bundle_map;
    }

    /**
     * @return the current variable
     */
    public static final String getVAR() {
        return VAR;
    }

    /**
     * @param var
     */
    public static final void setVAR(String var) {
        VAR = var;
    }

    /**
	 * @return Returns the _taglibMap.
	 */
	public static Map getTaglibMap() {
		return _taglibMap;
	}

	/**
	 * @param map
	 *            The _taglibMap to set.
	 */
	public static void setTaglibMap(Map map) {
		_taglibMap = map;
	}

	/**
	 * Get tag attribute string from attribute map
	 * 
	 * @param map
	 *            tag attribute map
	 * @return the attribute string
	 */
	public static String getAttributesAsString(Map map) {
		return getAttributesAsString(map, true);
	}

	/**
	 * Get file path from uri
	 * 
	 * @param uri
	 *            taglib uri
	 * @return the path as a string
	 */
	public static String getPathFromURI(String uri) {
		if (uri == null) {
			return uri;
		}

		if (uri.startsWith(IFileFolderConstants.PATH_SEPARATOR)) {
			return PreviewUtil.WEBROOT_PATH + uri;
		}
		IFile curFile = PreviewUtil.CURRENT_FILE;
		if (curFile != null) {
			IContainer con = curFile.getParent();
			if (con != null) {
				IPath path = con.getLocation();
				if (path != null) {
					String aPath = path.toString() + File.separator + uri;

					aPath = aPath.replace('/', File.separatorChar);
					aPath = aPath.replace('\\', File.separatorChar);
					if (aPath.endsWith(File.separator)) {
						aPath += File.separator;
					}
					File file = new File(aPath);
					if (file.exists()) {
						return aPath;
					}
                    return uri;
				}
			}
		}
		return null;
	}

	/**
	 * Get bundle value for expression
	 * 
	 * @param attrValue
	 *            expression
	 * @return the value
	 */
	public static String getValueOFEP(String attrValue) {
		if (attrValue != null) {
			if (attrValue.startsWith("#{")) //$NON-NLS-1$
			{
				String key, value = null;
				int i = attrValue.lastIndexOf("."); //$NON-NLS-1$
				if (i > 0) {
					key = attrValue.substring(i + 1, attrValue.length() - 1)
							.trim();
					String bundleVariable = attrValue.substring(2, i).trim();
					if (BUNDLE_MAP == null) {
						return attrValue;
					}
					PropertyResourceBundle bundle = (PropertyResourceBundle) BUNDLE_MAP
							.get(bundleVariable);

					if (bundle != null) {
						try {
							value = bundle.getString(key);
							if (value != null) {
								return value;
							}
                            return attrValue;
						} catch (MissingResourceException e1) {
							// "Error in resource bundle processing:"
							_log.info("PreviewUtil.Error.0", e1); //$NON-NLS-1$
						}
					}
				}
			}
		}
		return attrValue;
	}

	/**
	 * Get tag attribute string from attribute map
	 * 
	 * @param map
	 *            tag attribute map
	 * @param flag
	 *            state
	 * @return the attributes as a single string
	 */
	private static String getAttributesAsString(Map<String, String> map, boolean flag) {
		if (map == null) {
			return null;
		}

		StringBuffer stringbuffer = new StringBuffer();
		for (Iterator<Entry<String, String>> e = map.entrySet().iterator(); e.hasNext();) {
		    Map.Entry<String,String> entry = e.next();
			String attrName = entry.getKey();
			String attrValue = entry.getValue();
			attrValue = getValueOFEP(attrValue);
			if (ICSSPropertyID.ATTR_SRC.equalsIgnoreCase(attrName)
					|| ICSSPropertyID.ATTR_HREF.equalsIgnoreCase(attrName)
					|| ICSSPropertyID.ATTR_URI.equalsIgnoreCase(attrName)
					|| ICSSPropertyID.ATTR_BINDING.equalsIgnoreCase(attrName)
					|| ICSSPropertyID.ATTR_PAGE.equalsIgnoreCase(attrName)) {
				if (PreviewUtil.WEBROOT_PATH != null && attrValue != null
						&& !attrValue.startsWith("http") //$NON-NLS-1$
						&& !attrValue.startsWith("file")) //$NON-NLS-1$
				{
					attrValue = getPathFromURI(attrValue);
				}
			}
			if (attrValue != null) {
				stringbuffer.append(" ").append(attrName); //$NON-NLS-1$
				if (attrValue.indexOf(34) != -1) {
					StringBuffer stringbuffer1 = new StringBuffer();
					for (int j = 0; j < attrValue.length(); j++) {
						char c = attrValue.charAt(j);
						if (c != '"') {
							stringbuffer1.append(c);
						}
					}

					attrValue = stringbuffer1.toString();
				}
				if (attrValue != null && attrValue.startsWith("#{")) //$NON-NLS-1$
				{
					attrValue = ""; //$NON-NLS-1$
				}
				stringbuffer.append("=\"").append(attrValue).append('"'); //$NON-NLS-1$
			}
		}
		// System.out.println("BBBB:" +stringbuffer.toString());

		return stringbuffer.toString();
	}

	/**
	 * Change NamedNodeMap type to Map type
	 * 
	 * @param nodeMap
	 *            NamedNodeMap type
	 * @return the map
	 */
	public static Map getAttributeMap(NamedNodeMap nodeMap) {
		if (nodeMap != null) {
			int len = nodeMap.getLength();
			HashMap map = new HashMap();
			for (int i = 0; i < len; i++) {
				Node node = nodeMap.item(i);
				String name = node.getNodeName();
				String value = node.getNodeValue();
				if (name != null
						&& !name.trim().equalsIgnoreCase("") && value != null) //$NON-NLS-1$
				{
					map.put(name, value);
				}
			}
			return map;
		}
		return null;
	}

	/**
	 * @param result
	 * @param editorInput
	 * @return the file
	 */
	public static File toFile(StringBuffer result, IEditorInput editorInput) {
		try {
			File file = File.createTempFile("previewtmp", ".html"); //$NON-NLS-1$ //$NON-NLS-2$
			if (!file.exists()) {
				file.createNewFile();
			}
			
			//fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=202613 kindly contributed by Eiji Morito. 
			IContentTypeManager contentTypeManager = Platform.getContentTypeManager();
			IContentType contentType = contentTypeManager.getContentType("org.eclipse.wst.html.core.htmlsource"); //$NON-NLS-1$
			IContentDescription contentDescription = contentType.getDescriptionFor(new StringReader(result.toString()), null);
			String charset = contentDescription.getCharset();
			
			if (charset == null || !Charset.isSupported(charset)) {
				charset = ResourcesPlugin.getEncoding();
				if (charset == null)
					charset = "UTF-8"; //$NON-NLS-1$
			}

			FileOutputStream fos = new FileOutputStream(file);
			PrintStream ps = new PrintStream(fos, true, charset);
			ps.print(result.toString());
			ps.close();
			fos.close();
			return file;
		} catch (IOException e) {
			// "Error in file open:"
			_log.info("PreviewUtil.Error.3", e); //$NON-NLS-1$
			return null;
		}
	}


	/**
	 * do preivew on Node recursively translate escape char for Node and Node's
	 * child translate relative path for Node and Node's child
	 * 
	 * @param node
	 *            root node that will be previewed
	 */
	public static void previewNode(Node node) {
		if (node == null) {
			return;
		}
		NodeList nodeList = node.getChildNodes();
		if (nodeList == null) {
			return;
		}
		NamedNodeMap attrMap = node.getAttributes();

		if (attrMap != null) {
			for (int i = 0, n = attrMap.getLength(); i < n; i++) {
				Node attrNode = attrMap.item(i);
				if (attrNode instanceof Attr) {
					Attr attr = (Attr) attrNode;
					String value = attr.getNodeValue();
					value = getValueOFEP(value);
					//Bug 307801 - [WPE] WPE does not render Images with URL encoding in their path in the preview pane
					try {
						value = URLDecoder.decode(value, "UTF-8"); //$NON-NLS-1$
					} catch(UnsupportedEncodingException uee) {
						//we tried to decode using recommended encoding, we failed
					} catch(IllegalArgumentException iae) {
						//we tried to decode using recommended encoding, we failed
					}
					value = PathUtil.convertToAbsolutePath(value, null);
					attr.setNodeValue(value);
				}
			}
		}
		for (int i = 0, n = nodeList.getLength(); i < n; i++) {
			previewNode(nodeList.item(i));
		}
	}

	// /**
	// * handle escape attebute of tag
	// *
	// * @param node
	// * @return
	// */
	// public static boolean escapeFoeNode(Node node)
	// {
	// if (node == null)
	// {
	// return false;
	// }
	// NamedNodeMap attrMap = node.getAttributes();
	// if (attrMap != null)
	// {
	// for (int i = 0, n = attrMap.getLength(); i < n; i++)
	// {
	// Node attrNode = attrMap.item(i);
	// if (attrNode != null && attrNode instanceof Attr)
	// {
	// if ("escape".equalsIgnoreCase(attrNode.getNodeName())
	// && "true".equalsIgnoreCase(attrNode.getNodeValue()))
	// {
	// return true;
	// }
	// }
	// }
	// }
	// return false;
	// }

}

Back to the top