Skip to main content
summaryrefslogtreecommitdiffstats
blob: 11d273117a396173b3c4558db02d461063669fe1 (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
/*******************************************************************************
 * Copyright (c) 2006, 2011 IBM Corporation 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:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.help.internal.webapp.servlet;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.help.IToc;
import org.eclipse.help.ITopic;
import org.eclipse.help.base.AbstractHelpScope;
import org.eclipse.help.internal.Topic;
import org.eclipse.help.internal.base.scope.ScopeUtils;
import org.eclipse.help.internal.toc.Toc;
import org.eclipse.help.internal.webapp.WebappResources;
import org.eclipse.help.internal.webapp.data.IconFinder;
import org.eclipse.help.internal.webapp.data.RequestScope;
import org.eclipse.help.internal.webapp.data.TocData;
import org.eclipse.help.internal.webapp.data.UrlUtil;

/*
 * Creates xml representing selected parts of one or more TOCs  depending on the parameters
 * With no parameters the head of each toc is included
 * With parameter "href" the node and all its ancestors and siblings is included, corresponds to show in toc 
 * With parameter "toc" and optionally "path" the node, its ancestors and children are included
 */
public class TocFragmentServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private static Map<String, String> locale2Response = new WeakHashMap<String, String>();
	private boolean isErrorSuppress;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// set the character-set to UTF-8 before calling resp.getWriter()
		resp.setContentType("application/xml; charset=UTF-8"); //$NON-NLS-1$
		resp.getWriter().write(processRequest(req, resp));
	}
	
	protected String processRequest(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String locale = UrlUtil.getLocale(req, resp);
		req.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
	    resp.setHeader("Cache-Control","no-cache");   //$NON-NLS-1$//$NON-NLS-2$
	    resp.setHeader("Pragma","no-cache");  //$NON-NLS-1$ //$NON-NLS-2$
	    resp.setDateHeader ("Expires", 0); 	 //$NON-NLS-1$
		TocData data = new TocData(this.getServletContext(), req, resp);	
		
		readParameters(req);
		
		AbstractHelpScope scope = RequestScope.getScope(req, resp, false);
		Serializer serializer = new Serializer(data, UrlUtil.getLocaleObj(req, resp), scope);
		String response = serializer.generateTreeXml();	
		locale2Response.put(locale, response);
		
		return response;
	}

	private void readParameters(HttpServletRequest req) {
		String errorSuppressParam = req.getParameter("errorSuppress"); //$NON-NLS-1$
		isErrorSuppress = "true".equalsIgnoreCase(errorSuppressParam); //$NON-NLS-1$
	}
	
	/*
	 * Class which creates the xml file based upon the request parameters
	 */
	private class Serializer {
		
		private TocData tocData;
		private StringBuffer buf;
		private int requestKind;
		private Locale locale;
		private AbstractHelpScope scope;
		private static final int REQUEST_SHOW_IN_TOC = 1;      // Get the path to an element an element based on its href
		private static final int REQUEST_SHOW_TOCS = 2;        // Show all the tocs but not their children
		private static final int REQUEST_SHOW_CHILDREN = 3;    // Show the children of a node
		private static final int REQUEST_EXPAND_PATH = 4;      // Get all the nodes requires to expand a path in the tree

		public Serializer(TocData data, Locale locale, AbstractHelpScope scope) {
			tocData = data;
			buf = new StringBuffer();
			this.locale = locale;
			this.scope = scope;
			if (tocData.isExpandPath()) {
				requestKind = REQUEST_EXPAND_PATH;
			} else if (tocData.getTopicHref() != null) {
				requestKind = REQUEST_SHOW_IN_TOC;
			} else if (tocData.getSelectedToc() == -1) {
				requestKind = REQUEST_SHOW_TOCS;
			} else {
				requestKind = REQUEST_SHOW_CHILDREN;
			}
		}
		
		public String generateTreeXml() {
			buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //$NON-NLS-1$
			buf.append("<tree_data>\n"); //$NON-NLS-1$
				
			// Return an error for show in toc if topic was not found in toc
			if ((requestKind == REQUEST_SHOW_IN_TOC || requestKind == REQUEST_EXPAND_PATH) && tocData.getTopicPath() == null) {
				addError(WebappResources.getString("CannotSync", locale)); //$NON-NLS-1$
			} else if (requestKind == REQUEST_SHOW_IN_TOC) {
				generateNumericPath();
			} else {
			    serializeTocs();
			}
			buf.append("</tree_data>\n"); //$NON-NLS-1$
			return buf.toString();
		}
		
		
		private void generateNumericPath() {
			int selectedToc = tocData.getSelectedToc();
		    if (selectedToc < 0) {		    	
		    	addError(WebappResources.getString("CannotSync", locale)); //$NON-NLS-1$			
		    } else {
				// Count the number of enabled tocs
				int enabled = 0;
				for (int i = 0; i <= selectedToc; i++) {
					if (ScopeUtils.showInTree(tocData.getTocs()[i], scope)) {
						enabled++;
					}
				}
			    String fullNumericPath = "" + (enabled - 1); //$NON-NLS-1$
			    String numericPath = tocData.getNumericPath();
				if (numericPath != null) {
			    	fullNumericPath = fullNumericPath +  '_' + numericPath;
			    }
		    	buf.append("<numeric_path path=\"" + fullNumericPath + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$
		    }
		}

		private void addError(String message) {
			if (!isErrorSuppress) {
			    buf.append("<error>"); //$NON-NLS-1$
				buf.append(XMLGenerator.xmlEscape(message));
				buf.append("</error>"); //$NON-NLS-1$	
			}
		}

		private void serializeTocs() {
 			ITopic[] topicPath = tocData.getTopicPath();
	
			int selectedToc = tocData.getSelectedToc();
			// Iterate over all tocs - if there is a selected toc only generate that
			// toc, otherwise generate the root of every toc.
			for (int toc=0; toc< tocData.getTocCount(); toc++) {
				boolean shouldLoad = requestKind == REQUEST_SHOW_TOCS || toc == selectedToc;
	            if (shouldLoad) {
	            	boolean isSelected = false; // Should this node be selected in the tree
	            	if (requestKind == REQUEST_SHOW_TOCS) {
	            		isSelected = toc == 0;
	            	} else if (requestKind == REQUEST_SHOW_CHILDREN) {
	            		isSelected = tocData.getRootPath() == null;
	            	}
					serializeToc(tocData.getTocs()[toc], toc, topicPath, isSelected);
				}
			}
		}
	
		private void serializeToc(IToc toc, int tocIndex, ITopic[] topicPath, boolean isSelected) {		
			
			if (!ScopeUtils.showInTree(toc, scope)) {
				// do not generate toc when there are no leaf topics or if it is filtered out
				return;
			}
			ITopic[] topics = toc.getTopics();
			
			if (requestKind == REQUEST_SHOW_CHILDREN) {
				topicPath = tocData.getTopicPathFromRootPath(toc);
			}
			
			buf.append("<node"); //$NON-NLS-1$
			if (toc.getLabel() != null) { 
				buf.append('\n' + "      title=\"" + XMLGenerator.xmlEscape(toc.getLabel()) + '"'); //$NON-NLS-1$
			}
			buf.append('\n' + "      id=\"" + XMLGenerator.xmlEscape(toc.getHref()) + "\""); //$NON-NLS-1$ //$NON-NLS-2$

			String href = fixupHref(toc.getTopic(null).getHref(), "" + tocIndex); //$NON-NLS-1$
			buf.append('\n' + "      href=\"" + XMLGenerator.xmlEscape(UrlUtil.getHelpURL(href)) + "\""); //$NON-NLS-1$ //$NON-NLS-2$

			buf.append(createTocImageTag(toc));
				
			boolean serializeChildren = true;
			if (requestKind == REQUEST_SHOW_TOCS) {
				serializeChildren = false;
			}
			if (requestKind == REQUEST_EXPAND_PATH && topicPath.length == 0) {
				serializeChildren = false;
				buf.append('\n' + "      is_selected=\"true\"" ); //$NON-NLS-1$
				buf.append('\n' + "      is_highlighted=\"true\"" ); //$NON-NLS-1$	
			}
			buf.append(">\n"); //$NON-NLS-1$
			if (serializeChildren) { 
				serializeChildTopics(topics, topicPath, "", isSelected); //$NON-NLS-1$
			}
			buf.append("</node>\n"); //$NON-NLS-1$
			
		}

		private void serializeTopic(ITopic topic, ITopic[] topicPath, boolean isSelected, String parentPath)  {
		    ITopic[] subtopics = topic.getSubtopics();
		     boolean isLeaf = !ScopeUtils.hasInScopeDescendent(topic, scope);
		    buf.append("<node"); //$NON-NLS-1$
			if (topic.getLabel() != null) { 
				buf.append('\n'	+ "      title=\"" + XMLGenerator.xmlEscape(topic.getLabel()) + '"'); //$NON-NLS-1$
			}
	
			buf.append('\n' + "      id=\"" + parentPath + "\""); //$NON-NLS-1$ //$NON-NLS-2$

			String href = topic.getHref();
			href = fixupHref(href, "" + tocData.getSelectedToc() + '_' + parentPath); //$NON-NLS-1$
			buf.append('\n' + "      href=\"" + XMLGenerator.xmlEscape( //$NON-NLS-1$
					UrlUtil.getHelpURL(href)) + '"');
			if (isLeaf ) {
				buf.append('\n' + "      is_leaf=\"true\"" ); //$NON-NLS-1$
			}
			if (isSelected && requestKind == REQUEST_EXPAND_PATH) {
				buf.append('\n' + "      is_selected=\"true\"" ); //$NON-NLS-1$
				buf.append('\n' + "      is_highlighted=\"true\"" ); //$NON-NLS-1$	
			}
			String imageTags = createTopicImageTags(topic, isLeaf);
			buf.append(imageTags); 
			
			buf.append(">\n"); //$NON-NLS-1$
			serializeChildTopics(subtopics, topicPath, parentPath, isSelected);
			buf.append("</node>\n"); //$NON-NLS-1$	
		}
		
		private String createTocImageTag(IToc toc) {
			if (toc instanceof Toc) {
				String icon = ((Toc) toc).getIcon();
				
				if (IconFinder.isIconDefined(icon)) {			
				    String openIcon = IconFinder.getImagePathFromId(icon, IconFinder.TYPEICON_OPEN);
					String closedIcon = IconFinder.getImagePathFromId(icon, IconFinder.TYPEICON_CLOSED);
					String imageTags = '\n' + "      openImage=\"/"+ openIcon + "\""; //$NON-NLS-1$ //$NON-NLS-2$ 
					if (!openIcon.equals(closedIcon)) {
					    imageTags += '\n' + "      closedImage=\"/" + closedIcon + "\""; //$NON-NLS-1$ //$NON-NLS-2$
					}
					String altText = IconFinder.getIconAltFromId(icon);
					if(altText != null) {
						imageTags += '\n' + "      imageAlt=\""+ altText + "\""; //$NON-NLS-1$ //$NON-NLS-2$
					}
					return imageTags;
				}
			}
			return '\n' + "      image=\"toc_closed\""; //$NON-NLS-1$
		}

		private String createTopicImageTags(ITopic topic, boolean isLeaf) {
			if (topic instanceof Topic) {
				String icon = ((Topic) topic).getIcon();
			    String altText = IconFinder.getIconAltFromId(icon);
				
				if (IconFinder.isIconDefined(icon)) {					
					String imageTags;
					if (isLeaf) {		
						imageTags = '\n' + "      openImage=\"/" +IconFinder.getImagePathFromId(icon, IconFinder.TYPEICON_LEAF) + "\"";   //$NON-NLS-1$//$NON-NLS-2$
					} else {
					    String openIcon = IconFinder.getImagePathFromId(icon, IconFinder.TYPEICON_OPEN);
						String closedIcon = IconFinder.getImagePathFromId(icon, IconFinder.TYPEICON_CLOSED);
						imageTags = '\n' + "      openImage=\"/" + openIcon+ "\""; //$NON-NLS-1$ //$NON-NLS-2$ 
						if (!openIcon.equals(closedIcon)) {
						    imageTags += '\n' + "      closedImage=\"/" +  closedIcon + "\""; //$NON-NLS-1$ //$NON-NLS-2$
						}
				    }
					if(altText != null) {
						imageTags += '\n' + "      imageAlt=\""+ altText + "\""; //$NON-NLS-1$ //$NON-NLS-2$
					}	
					return imageTags;
				}
			}
			String icon;
			if (isLeaf) {
				icon = "topic"; //$NON-NLS-1$
			} else if (topic.getHref() == null) {
				icon = "container_obj"; //$NON-NLS-1$
			} else {
				icon = "container_topic"; //$NON-NLS-1$
			}
			String imageTags = '\n' + "      image=\"" + icon + "\""; //$NON-NLS-1$ //$NON-NLS-2$
			return imageTags;
		}
	
		private void serializeChildTopics(ITopic[] childTopics, ITopic[] topicPath, String parentPath, boolean parentIsSelected) {
			if (parentIsSelected && requestKind == REQUEST_SHOW_CHILDREN) {
				// Show the children of this node
				for (int subtopic = 0; subtopic < childTopics.length; subtopic++) {
				    ITopic childTopic = childTopics[subtopic];
				    if (ScopeUtils.showInTree(childTopic, scope)) {
					    serializeTopic(childTopic, null, false, addSuffix(parentPath, subtopic));
				    }
				}
			} else if (topicPath != null) {
				for (int subtopic = 0; subtopic < childTopics.length; subtopic++) {
					ITopic childTopic = childTopics[subtopic];
				    if (ScopeUtils.showInTree(childTopic, scope)) {
						if (topicPath[0].getLabel().equals(childTopic.getLabel())) {
							ITopic[] newPath = null;
							if (topicPath.length > 1) {
								newPath = new ITopic[topicPath.length - 1];
								System.arraycopy(topicPath, 1, newPath, 0, topicPath.length - 1);
							}
					        serializeTopic(childTopic, newPath, topicPath.length == 1, addSuffix(parentPath, subtopic));
						} else {
							serializeTopic(childTopic, null, false, addSuffix(parentPath, subtopic));
						}
					}
				}
			} 
		}

		private String addSuffix(String parentPath, int subtopic) {
			if (parentPath.length() == 0) {
				return parentPath + subtopic;
			} 
			return parentPath + '_' + subtopic;
		}
	}
	
	/*
	 * Add an extra parameter which represents the path within the tree. This enables show
	 * in Toc, print selected topic and search selected topic and all subtopics to work
	 * correctly even if the same page appears more than once in the table of contents, Bug 330868
	 * Static for testing purposes
	 */
	public static String  fixupHref(String href, String path) {
		if (href == null) {
			return "/../nav/" + path; //$NON-NLS-1$
		}
		int aIndex = href.indexOf('#');
		String anchorPart = ""; //$NON-NLS-1$
		String hrefPart = href;
		if (aIndex > 0) {
			anchorPart = href.substring(aIndex);
			hrefPart = href.substring(0, aIndex);
		}

		int questionIndex = href.indexOf('?');
		if  (questionIndex > 0 ) {
			return hrefPart + "&" + TocData.COMPLETE_PATH_PARAM + '=' + path + anchorPart; //$NON-NLS-1$			
		} else {
			return hrefPart + "?" + TocData.COMPLETE_PATH_PARAM + '=' + path + anchorPart; //$NON-NLS-1$
		}

	}

}

Back to the top