View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.helper;
17  
18  import java.io.BufferedInputStream;
19  import java.io.File;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.io.UnsupportedEncodingException;
23  import java.net.URLDecoder;
24  import java.net.URLEncoder;
25  import java.util.ArrayList;
26  import java.util.Date;
27  import java.util.HashMap;
28  import java.util.HashSet;
29  import java.util.List;
30  import java.util.Locale;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.concurrent.ConcurrentHashMap;
34  import java.util.function.Consumer;
35  import java.util.function.Function;
36  import java.util.regex.Matcher;
37  import java.util.regex.Pattern;
38  import java.util.stream.Collectors;
39  
40  import javax.annotation.PostConstruct;
41  import javax.servlet.ServletContext;
42  import javax.servlet.SessionTrackingMode;
43  import javax.servlet.http.HttpServletRequest;
44  import javax.servlet.http.HttpSession;
45  
46  import org.apache.catalina.connector.ClientAbortException;
47  import org.apache.commons.lang3.StringUtils;
48  import org.apache.commons.text.StringEscapeUtils;
49  import org.codelibs.core.CoreLibConstants;
50  import org.codelibs.core.io.CloseableUtil;
51  import org.codelibs.core.lang.StringUtil;
52  import org.codelibs.core.misc.DynamicProperties;
53  import org.codelibs.fess.Constants;
54  import org.codelibs.fess.crawler.builder.RequestDataBuilder;
55  import org.codelibs.fess.crawler.client.CrawlerClient;
56  import org.codelibs.fess.crawler.client.CrawlerClientFactory;
57  import org.codelibs.fess.crawler.entity.ResponseData;
58  import org.codelibs.fess.crawler.util.CharUtil;
59  import org.codelibs.fess.entity.FacetQueryView;
60  import org.codelibs.fess.entity.HighlightInfo;
61  import org.codelibs.fess.es.config.exentity.CrawlingConfig;
62  import org.codelibs.fess.exception.FessSystemException;
63  import org.codelibs.fess.helper.UserAgentHelper.UserAgentType;
64  import org.codelibs.fess.mylasta.direction.FessConfig;
65  import org.codelibs.fess.util.ComponentUtil;
66  import org.codelibs.fess.util.DocumentUtil;
67  import org.codelibs.fess.util.ResourceUtil;
68  import org.dbflute.optional.OptionalThing;
69  import org.lastaflute.taglib.function.LaFunctions;
70  import org.lastaflute.web.response.ActionResponse;
71  import org.lastaflute.web.response.StreamResponse;
72  import org.lastaflute.web.ruts.process.ActionRuntime;
73  import org.lastaflute.web.util.LaRequestUtil;
74  import org.lastaflute.web.util.LaResponseUtil;
75  import org.lastaflute.web.util.LaServletContextUtil;
76  import org.slf4j.Logger;
77  import org.slf4j.LoggerFactory;
78  
79  import com.github.jknack.handlebars.Context;
80  import com.github.jknack.handlebars.Handlebars;
81  import com.github.jknack.handlebars.Template;
82  import com.github.jknack.handlebars.io.FileTemplateLoader;
83  import com.ibm.icu.text.SimpleDateFormat;
84  
85  public class ViewHelper {
86  
87      private static final Logger logger = LoggerFactory.getLogger(ViewHelper.class);
88  
89      protected static final String SCREEN_WIDTH = "screen_width";
90  
91      protected static final int TABLET_WIDTH = 768;
92  
93      protected static final String CONTENT_DISPOSITION = "Content-Disposition";
94  
95      protected static final String HL_CACHE = "hl_cache";
96  
97      protected static final String QUERIES = "queries";
98  
99      protected static final String CACHE_MSG = "cache_msg";
100 
101     protected static final Pattern LOCAL_PATH_PATTERN = Pattern.compile("^file:/+[a-zA-Z]:");
102 
103     protected static final Pattern SHARED_FOLDER_PATTERN = Pattern.compile("^file:/+[^/]\\.");
104 
105     protected boolean encodeUrlLink = false;
106 
107     protected String urlLinkEncoding = Constants.UTF_8;
108 
109     protected String[] highlightedFields;
110 
111     protected String originalHighlightTagPre = "<em>";
112 
113     protected String originalHighlightTagPost = "</em>";
114 
115     protected String highlightTagPre;
116 
117     protected String highlightTagPost;
118 
119     protected boolean useSession = true;
120 
121     protected final Map<String, String> pageCacheMap = new ConcurrentHashMap<>();
122 
123     protected final Map<String, String> initFacetParamMap = new HashMap<>();
124 
125     protected final Map<String, String> initGeoParamMap = new HashMap<>();
126 
127     protected final List<FacetQueryView> facetQueryViewList = new ArrayList<>();
128 
129     protected String cacheTemplateName = "cache";
130 
131     protected String escapedHighlightPre = null;
132 
133     protected String escapedHighlightPost = null;
134 
135     protected Set<Integer> hihglightTerminalCharSet = new HashSet<>();
136 
137     protected ActionHook actionHook = new ActionHook();
138 
139     protected final Set<String> inlineMimeTypeSet = new HashSet<>();
140 
141     @PostConstruct
142     public void init() {
143         final FessConfig fessConfig = ComponentUtil.getFessConfig();
144         escapedHighlightPre = LaFunctions.h(originalHighlightTagPre);
145         escapedHighlightPost = LaFunctions.h(originalHighlightTagPost);
146         highlightTagPre = fessConfig.getQueryHighlightTagPre();
147         highlightTagPost = fessConfig.getQueryHighlightTagPost();
148         highlightedFields = fessConfig.getQueryHighlightContentDescriptionFieldsAsArray();
149         fessConfig.getQueryHighlightTerminalChars().codePoints().forEach(hihglightTerminalCharSet::add);
150         try {
151             final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class);
152             servletContext.setSessionTrackingModes(fessConfig.getSessionTrackingModesAsSet().stream().map(SessionTrackingMode::valueOf)
153                     .collect(Collectors.toSet()));
154         } catch (final Throwable t) {
155             logger.warn("Failed to set SessionTrackingMode.", t);
156         }
157     }
158 
159     public String getContentTitle(final Map<String, Object> document) {
160         final FessConfig fessConfig = ComponentUtil.getFessConfig();
161         String title = DocumentUtil.getValue(document, fessConfig.getIndexFieldTitle(), String.class);
162         if (StringUtil.isBlank(title)) {
163             title = DocumentUtil.getValue(document, fessConfig.getIndexFieldFilename(), String.class);
164             if (StringUtil.isBlank(title)) {
165                 title = DocumentUtil.getValue(document, fessConfig.getIndexFieldUrl(), String.class);
166             }
167         }
168         final int size = fessConfig.getResponseMaxTitleLengthAsInteger();
169         if (size > -1) {
170             title = StringUtils.abbreviate(title, size);
171         }
172         final String value = LaFunctions.h(title);
173         if (!fessConfig.isResponseHighlightContentTitleEnabled()) {
174             return value;
175         }
176         return getQuerySet().map(
177                 querySet -> {
178                     final Matcher matcher =
179                             Pattern.compile(querySet.stream().map(LaFunctions::h).map(Pattern::quote).collect(Collectors.joining("|")),
180                                     Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(value);
181                     final StringBuffer buf = new StringBuffer(value.length() + 100);
182                     while (matcher.find()) {
183                         matcher.appendReplacement(buf, highlightTagPre + matcher.group(0) + highlightTagPost);
184                     }
185                     matcher.appendTail(buf);
186                     return buf.toString();
187                 }).orElse(value);
188     }
189 
190     protected OptionalThing<Set<String>> getQuerySet() {
191         return LaRequestUtil.getOptionalRequest().map(req -> {
192             @SuppressWarnings("unchecked")
193             final Set<String> querySet = (Set<String>) req.getAttribute(Constants.HIGHLIGHT_QUERIES);
194             return querySet;
195         }).filter(s -> s != null);
196     }
197 
198     public String getContentDescription(final Map<String, Object> document) {
199         for (final String field : highlightedFields) {
200             final String text = DocumentUtil.getValue(document, field, String.class);
201             if (StringUtil.isNotBlank(text)) {
202                 return escapeHighlight(text);
203             }
204         }
205 
206         return StringUtil.EMPTY;
207     }
208 
209     protected String escapeHighlight(final String text) {
210         final String escaped = LaFunctions.h(text);
211         int pos = escaped.indexOf(escapedHighlightPre);
212         while (pos >= 0) {
213             final int c = escaped.codePointAt(pos);
214             if (Character.isISOControl(c) || hihglightTerminalCharSet.contains(c)) {
215                 break;
216             }
217             pos--;
218         }
219 
220         final String value = escaped.substring(pos + 1);
221         return value.replaceAll(escapedHighlightPre, highlightTagPre).replaceAll(escapedHighlightPost, highlightTagPost);
222     }
223 
224     protected String removeHighlightTag(final String str) {
225         return str.replaceAll(originalHighlightTagPre, StringUtil.EMPTY).replaceAll(originalHighlightTagPost, StringUtil.EMPTY);
226     }
227 
228     public HighlightInfo createHighlightInfo() {
229         return LaRequestUtil.getOptionalRequest().map(req -> {
230             final HighlightInfol#HighlightInfo">HighlightInfo highlightInfo = new HighlightInfo();
231             final String widthStr = req.getParameter(SCREEN_WIDTH);
232             if (StringUtil.isNotBlank(widthStr)) {
233                 final int width = Integer.parseInt(widthStr);
234                 updateHighlisthInfo(highlightInfo, width);
235                 final HttpSession session = req.getSession(false);
236                 if (session != null) {
237                     session.setAttribute(SCREEN_WIDTH, width);
238                 }
239             } else {
240                 final HttpSession session = req.getSession(false);
241                 if (session != null) {
242                     final Integer width = (Integer) session.getAttribute(SCREEN_WIDTH);
243                     if (width != null) {
244                         updateHighlisthInfo(highlightInfo, width);
245                     }
246                 }
247             }
248             return highlightInfo;
249         }).orElse(new HighlightInfo());
250     }
251 
252     protected void updateHighlisthInfo(final HighlightInfo highlightInfo, final int width) {
253         if (width < TABLET_WIDTH) {
254             float ratio = ((float) width) / ((float) TABLET_WIDTH);
255             if (ratio < 0.5) {
256                 ratio = 0.5f;
257             }
258             highlightInfo.fragmentSize((int) (highlightInfo.getFragmentSize() * ratio));
259         }
260     }
261 
262     public String getUrlLink(final Map<String, Object> document) {
263         final FessConfig fessConfig = ComponentUtil.getFessConfig();
264         String url = DocumentUtil.getValue(document, fessConfig.getIndexFieldUrl(), String.class);
265 
266         if (StringUtil.isBlank(url)) {
267             return "#not-found-" + DocumentUtil.getValue(document, fessConfig.getIndexFieldDocId(), String.class);
268         }
269 
270         final boolean isSmbUrl = url.startsWith("smb:") || url.startsWith("smb1:");
271         final boolean isFtpUrl = url.startsWith("ftp:");
272         final boolean isSmbOrFtpUrl = isSmbUrl || isFtpUrl;
273 
274         // replacing url with mapping data
275         url = ComponentUtil.getPathMappingHelper().replaceUrl(url);
276 
277         final boolean isHttpUrl = url.startsWith("http:") || url.startsWith("https:");
278 
279         if (isSmbUrl) {
280             url = url.replace("smb:", "file:");
281             url = url.replace("smb1:", "file:");
282         }
283 
284         if (isHttpUrl && isSmbOrFtpUrl) {
285             //  smb/ftp->http
286             // encode
287             final StringBuilder buf = new StringBuilder(url.length() + 100);
288             for (final char c : url.toCharArray()) {
289                 if (CharUtil.isUrlChar(c)) {
290                     buf.append(c);
291                 } else {
292                     try {
293                         buf.append(URLEncoder.encode(String.valueOf(c), urlLinkEncoding));
294                     } catch (final UnsupportedEncodingException e) {
295                         buf.append(c);
296                     }
297                 }
298             }
299             url = buf.toString();
300         } else if (url.startsWith("file:")) {
301             // file, smb/ftp->http
302             url = updateFileProtocol(url);
303 
304             if (encodeUrlLink) {
305                 return appendQueryParameter(document, url);
306             }
307 
308             // decode
309             if (!isSmbOrFtpUrl) {
310                 // file
311                 try {
312                     url = URLDecoder.decode(url.replace("+", "%2B"), urlLinkEncoding);
313                 } catch (final Exception e) {
314                     if (logger.isDebugEnabled()) {
315                         logger.warn("Failed to decode " + url, e);
316                     }
317                 }
318             }
319         }
320         // http, ftp
321         // nothing
322 
323         return appendQueryParameter(document, url);
324     }
325 
326     protected String updateFileProtocol(String url) {
327         final int pos = url.indexOf(':', 5);
328         final boolean isLocalFile = pos > 0 && pos < 12;
329 
330         final UserAgentType ua = ComponentUtil.getUserAgentHelper().getUserAgentType();
331         final DynamicProperties systemProperties = ComponentUtil.getSystemProperties();
332         switch (ua) {
333         case IE:
334             if (isLocalFile) {
335                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.winlocal.ie", "file://"));
336             } else {
337                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.ie", "file://"));
338             }
339             break;
340         case FIREFOX:
341             if (isLocalFile) {
342                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.winlocal.firefox", "file://"));
343             } else {
344                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.firefox", "file://///"));
345             }
346             break;
347         case CHROME:
348             if (isLocalFile) {
349                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.winlocal.chrome", "file://"));
350             } else {
351                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.chrome", "file://"));
352             }
353             break;
354         case SAFARI:
355             if (isLocalFile) {
356                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.winlocal.safari", "file://"));
357             } else {
358                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.safari", "file:////"));
359             }
360             break;
361         case OPERA:
362             if (isLocalFile) {
363                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.winlocal.opera", "file://"));
364             } else {
365                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.opera", "file://"));
366             }
367             break;
368         default:
369             if (isLocalFile) {
370                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.winlocal.other", "file://"));
371             } else {
372                 url = url.replaceFirst("file:/+", systemProperties.getProperty("file.protocol.other", "file://"));
373             }
374             break;
375         }
376         return url;
377     }
378 
379     protected String appendQueryParameter(final Map<String, Object> document, final String url) {
380         final FessConfig fessConfig = ComponentUtil.getFessConfig();
381         if (fessConfig.isAppendQueryParameter()) {
382             if (url.indexOf('#') >= 0) {
383                 return url;
384             }
385 
386             final String mimetype = DocumentUtil.getValue(document, fessConfig.getIndexFieldMimetype(), String.class);
387             if (StringUtil.isNotBlank(mimetype)) {
388                 if ("application/pdf".equals(mimetype)) {
389                     return appendPDFSearchWord(url);
390                 } else {
391                     // TODO others..
392                     return url;
393                 }
394             }
395         }
396         return url;
397     }
398 
399     protected String appendPDFSearchWord(final String url) {
400         final String queries = (String) LaRequestUtil.getRequest().getAttribute(Constants.REQUEST_QUERIES);
401         if (queries != null) {
402             try {
403                 final StringBuilder buf = new StringBuilder(url.length() + 100);
404                 buf.append(url).append("#search=%22");
405                 buf.append(URLEncoder.encode(queries.trim(), Constants.UTF_8));
406                 buf.append("%22");
407                 return buf.toString();
408             } catch (final UnsupportedEncodingException e) {
409                 logger.warn("Unsupported encoding.", e);
410             }
411         }
412         return url;
413     }
414 
415     public String getPagePath(final String page) {
416         final Locale locale = ComponentUtil.getRequestManager().getUserLocale();
417         final String lang = locale.getLanguage();
418         final String country = locale.getCountry();
419 
420         final String pathLC = getLocalizedPagePath(page, lang, country);
421         final String pLC = pageCacheMap.get(pathLC);
422         if (pLC != null) {
423             return pLC;
424         }
425         if (existsPage(pathLC)) {
426             pageCacheMap.put(pathLC, pathLC);
427             return pathLC;
428         }
429 
430         final String pathL = getLocalizedPagePath(page, lang, null);
431         final String pL = pageCacheMap.get(pathL);
432         if (pL != null) {
433             return pL;
434         }
435         if (existsPage(pathL)) {
436             pageCacheMap.put(pathLC, pathL);
437             return pathL;
438         }
439 
440         final String path = getLocalizedPagePath(page, null, null);
441         final String p = pageCacheMap.get(path);
442         if (p != null) {
443             return p;
444         }
445         if (existsPage(path)) {
446             pageCacheMap.put(pathLC, path);
447             return path;
448         }
449 
450         return "index.jsp";
451     }
452 
453     private String getLocalizedPagePath(final String page, final String lang, final String country) {
454         final StringBuilder buf = new StringBuilder(100);
455         buf.append("/WEB-INF/view/").append(page);
456         if (StringUtil.isNotBlank(lang)) {
457             buf.append('_').append(lang);
458             if (StringUtil.isNotBlank(country)) {
459                 buf.append('_').append(country);
460             }
461         }
462         buf.append(".jsp");
463         return buf.toString();
464     }
465 
466     private boolean existsPage(final String path) {
467         final String realPath = LaServletContextUtil.getServletContext().getRealPath(path);
468         final File file = new File(realPath);
469         return file.isFile();
470     }
471 
472     public String createCacheContent(final Map<String, Object> doc, final String[] queries) {
473         final FessConfig fessConfig = ComponentUtil.getFessConfig();
474         final FileTemplateLoader loader = new FileTemplateLoader(ResourceUtil.getViewTemplatePath().toFile());
475         final Handlebars handlebars = new Handlebars(loader);
476 
477         Locale locale = ComponentUtil.getRequestManager().getUserLocale();
478         if (locale == null) {
479             locale = Locale.ENGLISH;
480         }
481         String url = DocumentUtil.getValue(doc, fessConfig.getIndexFieldUrl(), String.class);
482         if (url == null) {
483             url = ComponentUtil.getMessageManager().getMessage(locale, "labels.search_unknown");
484         }
485         doc.put(fessConfig.getResponseFieldUrlLink(), getUrlLink(doc));
486         String createdStr;
487         final Date created = DocumentUtil.getValue(doc, fessConfig.getIndexFieldCreated(), Date.class);
488         if (created != null) {
489             final SimpleDateFormat sdf = new SimpleDateFormat(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
490             createdStr = sdf.format(created);
491         } else {
492             createdStr = ComponentUtil.getMessageManager().getMessage(locale, "labels.search_unknown");
493         }
494         doc.put(CACHE_MSG, ComponentUtil.getMessageManager()
495                 .getMessage(locale, "labels.search_cache_msg", new Object[] { url, createdStr }));
496 
497         doc.put(QUERIES, queries);
498 
499         String cache = DocumentUtil.getValue(doc, fessConfig.getIndexFieldCache(), String.class);
500         if (cache != null) {
501             final String mimetype = DocumentUtil.getValue(doc, fessConfig.getIndexFieldMimetype(), String.class);
502             if (!ComponentUtil.getFessConfig().isHtmlMimetypeForCache(mimetype)) {
503                 cache = StringEscapeUtils.escapeHtml4(cache);
504             }
505             cache = ComponentUtil.getPathMappingHelper().replaceUrls(cache);
506             if (queries != null && queries.length > 0) {
507                 doc.put(HL_CACHE, replaceHighlightQueries(cache, queries));
508             } else {
509                 doc.put(HL_CACHE, cache);
510             }
511         } else {
512             doc.put(fessConfig.getIndexFieldCache(), StringUtil.EMPTY);
513             doc.put(HL_CACHE, StringUtil.EMPTY);
514         }
515 
516         try {
517             final Template template = handlebars.compile(cacheTemplateName);
518             final Context hbsContext = Context.newContext(doc);
519             return template.apply(hbsContext);
520         } catch (final Exception e) {
521             logger.warn("Failed to create a cache response.", e);
522         }
523 
524         return null;
525     }
526 
527     protected String replaceHighlightQueries(final String cache, final String[] queries) {
528         final StringBuffer buf = new StringBuffer(cache.length() + 100);
529         final StringBuffer segBuf = new StringBuffer(1000);
530         final Pattern p = Pattern.compile("<[^>]+>");
531         final Matcher m = p.matcher(cache);
532         final String[] regexQueries = new String[queries.length];
533         final String[] hlQueries = new String[queries.length];
534         for (int i = 0; i < queries.length; i++) {
535             regexQueries[i] = Pattern.quote(queries[i]);
536             hlQueries[i] = highlightTagPre + queries[i] + highlightTagPost;
537         }
538         while (m.find()) {
539             segBuf.setLength(0);
540             m.appendReplacement(segBuf, StringUtil.EMPTY);
541             String segment = segBuf.toString();
542             for (int i = 0; i < queries.length; i++) {
543                 segment = Pattern.compile(regexQueries[i], Pattern.CASE_INSENSITIVE).matcher(segment).replaceAll(hlQueries[i]);
544             }
545             buf.append(segment);
546             buf.append(m.group(0));
547         }
548         segBuf.setLength(0);
549         m.appendTail(segBuf);
550         String segment = segBuf.toString();
551         for (int i = 0; i < queries.length; i++) {
552             segment = Pattern.compile(regexQueries[i], Pattern.CASE_INSENSITIVE).matcher(segment).replaceAll(hlQueries[i]);
553         }
554         buf.append(segment);
555         return buf.toString();
556     }
557 
558     public Object getSitePath(final Map<String, Object> docMap) {
559         final FessConfig fessConfig = ComponentUtil.getFessConfig();
560         final Object urlLink = docMap.get(fessConfig.getResponseFieldUrlLink());
561         if (urlLink != null) {
562             final String returnUrl;
563             final String url = urlLink.toString();
564             if (LOCAL_PATH_PATTERN.matcher(url).find() || SHARED_FOLDER_PATTERN.matcher(url).find()) {
565                 returnUrl = url.replaceFirst("^file:/+", "");
566             } else if (url.startsWith("file:")) {
567                 returnUrl = url.replaceFirst("^file:/+", "/");
568             } else {
569                 returnUrl = url.replaceFirst("^[a-zA-Z0-9]*:/+", "");
570             }
571             final int size = fessConfig.getResponseMaxSitePathLengthAsInteger();
572             if (size > -1) {
573                 return StringUtils.abbreviate(returnUrl, size);
574             } else {
575                 return returnUrl;
576             }
577         }
578         return null;
579     }
580 
581     public StreamResponse asContentResponse(final Map<String, Object> doc) {
582         if (logger.isDebugEnabled()) {
583             logger.debug("writing the content of: " + doc);
584         }
585         final FessConfig fessConfig = ComponentUtil.getFessConfig();
586         final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
587         final String configId = DocumentUtil.getValue(doc, fessConfig.getIndexFieldConfigId(), String.class);
588         if (configId == null) {
589             throw new FessSystemException("configId is null.");
590         }
591         if (configId.length() < 2) {
592             throw new FessSystemException("Invalid configId: " + configId);
593         }
594         final CrawlingConfig config = crawlingConfigHelper.getCrawlingConfig(configId);
595         if (config == null) {
596             throw new FessSystemException("No crawlingConfig: " + configId);
597         }
598         final String url = DocumentUtil.getValue(doc, fessConfig.getIndexFieldUrl(), String.class);
599         final CrawlerClientFactory crawlerClientFactory = ComponentUtil.getComponent(CrawlerClientFactory.class);
600         config.initializeClientFactory(crawlerClientFactory);
601         final CrawlerClient client = crawlerClientFactory.getClient(url);
602         if (client == null) {
603             throw new FessSystemException("No CrawlerClient: " + configId + ", url: " + url);
604         }
605         return writeContent(configId, url, client);
606     }
607 
608     protected StreamResponse writeContent(final String configId, final String url, final CrawlerClient client) {
609         final StreamResponse response = new StreamResponse(StringUtil.EMPTY);
610         final ResponseData responseData = client.execute(RequestDataBuilder.newRequestData().get().url(url).build());
611         if (responseData.getHttpStatusCode() == 404) {
612             response.httpStatus(responseData.getHttpStatusCode());
613             CloseableUtil.closeQuietly(responseData);
614             return response;
615         }
616         writeFileName(response, responseData);
617         writeContentType(response, responseData);
618         writeNoCache(response, responseData);
619         response.stream(out -> {
620             try (final InputStream is = new BufferedInputStream(responseData.getResponseBody())) {
621                 out.write(is);
622             } catch (final IOException e) {
623                 if (!(e.getCause() instanceof ClientAbortException)) {
624                     throw new FessSystemException("Failed to write a content. configId: " + configId + ", url: " + url, e);
625                 }
626             } finally {
627                 CloseableUtil.closeQuietly(responseData);
628             }
629             if (logger.isDebugEnabled()) {
630                 logger.debug("Finished to write " + url);
631             }
632         });
633         return response;
634     }
635 
636     protected void writeNoCache(final StreamResponse response, final ResponseData responseData) {
637         response.header("Pragma", "no-cache");
638         response.header("Cache-Control", "no-cache");
639         response.header("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
640     }
641 
642     protected void writeFileName(final StreamResponse response, final ResponseData responseData) {
643         String charset = responseData.getCharSet();
644         if (charset == null) {
645             charset = Constants.UTF_8;
646         }
647         final String name;
648         final String url = responseData.getUrl();
649         final int pos = url.lastIndexOf('/');
650         try {
651             if (pos >= 0 && pos + 1 < url.length()) {
652                 name = URLDecoder.decode(url.substring(pos + 1), charset);
653             } else {
654                 name = URLDecoder.decode(url, charset);
655             }
656 
657             final String contentDispositionType;
658             if (inlineMimeTypeSet.contains(responseData.getMimeType())) {
659                 contentDispositionType = "inline";
660             } else {
661                 contentDispositionType = "attachment";
662             }
663 
664             final String encodedName = URLEncoder.encode(name, Constants.UTF_8).replace("+", "%20");
665             response.header(CONTENT_DISPOSITION, contentDispositionType + "; filename=\"" + name + "\"; filename*=utf-8''" + encodedName);
666         } catch (final Exception e) {
667             logger.warn("Failed to write a filename: " + responseData, e);
668         }
669     }
670 
671     protected void writeContentType(final StreamResponse response, final ResponseData responseData) {
672         final String mimeType = responseData.getMimeType();
673         if (logger.isDebugEnabled()) {
674             logger.debug("mimeType: " + mimeType);
675         }
676         if (mimeType == null) {
677             response.contentTypeOctetStream();
678             return;
679         }
680         if (mimeType.startsWith("text/")) {
681             final String charset = LaResponseUtil.getResponse().getCharacterEncoding();
682             if (charset != null) {
683                 response.contentType(mimeType + "; charset=" + charset);
684                 return;
685             }
686         }
687         response.contentType(mimeType);
688     }
689 
690     public String getClientIp(final HttpServletRequest request) {
691         final String value = request.getHeader("x-forwarded-for");
692         if (StringUtil.isNotBlank(value)) {
693             return value;
694         } else {
695             return request.getRemoteAddr();
696         }
697     }
698 
699     public boolean isUseSession() {
700         return useSession;
701     }
702 
703     public void setUseSession(final boolean useSession) {
704         this.useSession = useSession;
705     }
706 
707     public void addInitFacetParam(final String key, final String value) {
708         initFacetParamMap.put(value, key);
709     }
710 
711     public Map<String, String> getInitFacetParamMap() {
712         return initFacetParamMap;
713     }
714 
715     public void addInitGeoParam(final String key, final String value) {
716         initGeoParamMap.put(value, key);
717     }
718 
719     public Map<String, String> getInitGeoParamMap() {
720         return initGeoParamMap;
721     }
722 
723     public void addFacetQueryView(final FacetQueryView facetQueryView) {
724         facetQueryViewList.add(facetQueryView);
725     }
726 
727     public List<FacetQueryView> getFacetQueryViewList() {
728         return facetQueryViewList;
729     }
730 
731     public void addInlineMimeType(final String mimeType) {
732         inlineMimeTypeSet.add(mimeType);
733     }
734 
735     public ActionHook getActionHook() {
736         return actionHook;
737     }
738 
739     public void setActionHook(final ActionHook actionHook) {
740         this.actionHook = actionHook;
741     }
742 
743     public static class ActionHook {
744 
745         public ActionResponse godHandPrologue(final ActionRuntime runtime, final Function<ActionRuntime, ActionResponse> func) {
746             return func.apply(runtime);
747         }
748 
749         public ActionResponse godHandMonologue(final ActionRuntime runtime, final Function<ActionRuntime, ActionResponse> func) {
750             return func.apply(runtime);
751         }
752 
753         public void godHandEpilogue(final ActionRuntime runtime, final Consumer<ActionRuntime> consumer) {
754             consumer.accept(runtime);
755         }
756 
757         public ActionResponse hookBefore(final ActionRuntime runtime, final Function<ActionRuntime, ActionResponse> func) {
758             return func.apply(runtime);
759         }
760 
761         public void hookFinally(final ActionRuntime runtime, final Consumer<ActionRuntime> consumer) {
762             consumer.accept(runtime);
763         }
764     }
765 
766     public void setEncodeUrlLink(final boolean encodeUrlLink) {
767         this.encodeUrlLink = encodeUrlLink;
768     }
769 
770     public void setUrlLinkEncoding(final String urlLinkEncoding) {
771         this.urlLinkEncoding = urlLinkEncoding;
772     }
773 
774     public void setOriginalHighlightTagPre(final String originalHighlightTagPre) {
775         this.originalHighlightTagPre = originalHighlightTagPre;
776     }
777 
778     public void setOriginalHighlightTagPost(final String originalHighlightTagPost) {
779         this.originalHighlightTagPost = originalHighlightTagPost;
780     }
781 
782     public void setCacheTemplateName(final String cacheTemplateName) {
783         this.cacheTemplateName = cacheTemplateName;
784     }
785 }