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.crawler.transformer;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.io.BufferedInputStream;
21  import java.net.MalformedURLException;
22  import java.net.URL;
23  import java.util.ArrayList;
24  import java.util.Collections;
25  import java.util.Date;
26  import java.util.HashMap;
27  import java.util.HashSet;
28  import java.util.LinkedHashMap;
29  import java.util.List;
30  import java.util.Locale;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.stream.Collectors;
34  
35  import javax.annotation.PostConstruct;
36  import javax.xml.transform.TransformerException;
37  
38  import org.apache.xpath.objects.XObject;
39  import org.codelibs.core.io.InputStreamUtil;
40  import org.codelibs.core.io.SerializeUtil;
41  import org.codelibs.core.lang.StringUtil;
42  import org.codelibs.core.misc.ValueHolder;
43  import org.codelibs.fess.Constants;
44  import org.codelibs.fess.crawler.builder.RequestDataBuilder;
45  import org.codelibs.fess.crawler.entity.AccessResultData;
46  import org.codelibs.fess.crawler.entity.RequestData;
47  import org.codelibs.fess.crawler.entity.ResponseData;
48  import org.codelibs.fess.crawler.entity.ResultData;
49  import org.codelibs.fess.crawler.entity.UrlQueue;
50  import org.codelibs.fess.crawler.exception.ChildUrlsException;
51  import org.codelibs.fess.crawler.exception.CrawlerSystemException;
52  import org.codelibs.fess.crawler.exception.CrawlingAccessException;
53  import org.codelibs.fess.crawler.transformer.impl.XpathTransformer;
54  import org.codelibs.fess.crawler.util.CrawlingParameterUtil;
55  import org.codelibs.fess.es.config.exentity.CrawlingConfig;
56  import org.codelibs.fess.es.config.exentity.CrawlingConfig.ConfigName;
57  import org.codelibs.fess.helper.CrawlingConfigHelper;
58  import org.codelibs.fess.helper.CrawlingInfoHelper;
59  import org.codelibs.fess.helper.DocumentHelper;
60  import org.codelibs.fess.helper.DuplicateHostHelper;
61  import org.codelibs.fess.helper.FileTypeHelper;
62  import org.codelibs.fess.helper.LabelTypeHelper;
63  import org.codelibs.fess.helper.PathMappingHelper;
64  import org.codelibs.fess.helper.SystemHelper;
65  import org.codelibs.fess.mylasta.direction.FessConfig;
66  import org.codelibs.fess.util.ComponentUtil;
67  import org.codelibs.fess.util.PrunedTag;
68  import org.codelibs.nekohtml.parsers.DOMParser;
69  import org.slf4j.Logger;
70  import org.slf4j.LoggerFactory;
71  import org.w3c.dom.Document;
72  import org.w3c.dom.NamedNodeMap;
73  import org.w3c.dom.Node;
74  import org.w3c.dom.NodeList;
75  import org.xml.sax.InputSource;
76  
77  public class FessXpathTransformer extends XpathTransformer implements FessTransformer {
78  
79      private static final Logger logger = LoggerFactory.getLogger(FessXpathTransformer.class);
80  
81      private static final String X_ROBOTS_TAG = "X-Robots-Tag";
82  
83      private static final String HTML_CANONICAL_XPATH = "html.canonical.xpath";
84  
85      private static final String IGNORE_ROBOTS_TAGS = "ignore.robots.tags";
86  
87      private static final String META_NAME_THUMBNAIL_CONTENT = "//META[@name=\"thumbnail\" or @name=\"THUMBNAIL\"]/@content";
88  
89      private static final String META_PROPERTY_OGIMAGE_CONTENT = "//META[@property=\"og:image\"]/@content";
90  
91      private static final String META_NAME_ROBOTS_CONTENT = "//META[@name=\"robots\" or @name=\"ROBOTS\"]/@content";
92  
93      private static final String ROBOTS_TAG_NONE = "none";
94  
95      private static final String ROBOTS_TAG_NOINDEX = "noindex";
96  
97      private static final String ROBOTS_TAG_NOFOLLOW = "nofollow";
98  
99      private static final int UTF8_BOM_SIZE = 3;
100 
101     public boolean prunedContent = true;
102 
103     public Map<String, String> convertUrlMap = new HashMap<>();
104 
105     protected FessConfig fessConfig;
106 
107     protected boolean useGoogleOffOn = true;
108 
109     protected Map<String, Boolean> fieldPrunedRuleMap = new HashMap<>();
110 
111     @PostConstruct
112     public void init() {
113         fessConfig = ComponentUtil.getFessConfig();
114     }
115 
116     @Override
117     public FessConfig getFessConfig() {
118         return fessConfig;
119     }
120 
121     @Override
122     public Logger getLogger() {
123         return logger;
124     }
125 
126     @Override
127     protected void storeData(final ResponseData responseData, final ResultData resultData) {
128         final DOMParser parser = getDomParser();
129         try (final BufferedInputStream bis = new BufferedInputStream(responseData.getResponseBody())) {
130             final byte[] bomBytes = new byte[UTF8_BOM_SIZE];
131             bis.mark(UTF8_BOM_SIZE);
132             final int size = bis.read(bomBytes);
133             if (size < 3 || !isUtf8BomBytes(bomBytes)) {
134                 bis.reset();
135             }
136             final InputSource is = new InputSource(bis);
137             if (responseData.getCharSet() != null) {
138                 is.setEncoding(responseData.getCharSet());
139             }
140             parser.parse(is);
141         } catch (final Exception e) {
142             throw new CrawlingAccessException("Could not parse " + responseData.getUrl(), e);
143         }
144 
145         final Document document = parser.getDocument();
146 
147         processMetaRobots(responseData, resultData, document);
148         processXRobotsTag(responseData, resultData);
149 
150         final Map<String, Object> dataMap = new LinkedHashMap<>();
151         for (final Map.Entry<String, String> entry : fieldRuleMap.entrySet()) {
152             final String path = entry.getValue();
153             try {
154                 final XObject xObj = getXPathAPI().eval(document, path);
155                 final int type = xObj.getType();
156                 switch (type) {
157                 case XObject.CLASS_BOOLEAN:
158                     final boolean b = xObj.bool();
159                     putResultDataBody(dataMap, entry.getKey(), Boolean.toString(b));
160                     break;
161                 case XObject.CLASS_NUMBER:
162                     final double d = xObj.num();
163                     putResultDataBody(dataMap, entry.getKey(), Double.toString(d));
164                     break;
165                 case XObject.CLASS_STRING:
166                     final String str = xObj.str();
167                     putResultDataBody(dataMap, entry.getKey(), str);
168                     break;
169                 case XObject.CLASS_NULL:
170                 case XObject.CLASS_UNKNOWN:
171                 case XObject.CLASS_NODESET:
172                 case XObject.CLASS_RTREEFRAG:
173                 case XObject.CLASS_UNRESOLVEDVARIABLE:
174                 default:
175                     final Boolean isPruned = fieldPrunedRuleMap.get(entry.getKey());
176                     Node value = getXPathAPI().selectSingleNode(document, entry.getValue());
177                     if (value != null && isPruned != null && isPruned.booleanValue()) {
178                         value = pruneNode(value);
179                     }
180                     putResultDataBody(dataMap, entry.getKey(), value != null ? value.getTextContent() : null);
181                     break;
182                 }
183             } catch (final TransformerException e) {
184                 logger.warn("Could not parse a value of " + entry.getKey() + ":" + entry.getValue(), e);
185             }
186         }
187 
188         putAdditionalData(dataMap, responseData, document);
189         normalizeData(responseData, dataMap);
190 
191         try {
192             resultData.setData(SerializeUtil.fromObjectToBinary(dataMap));
193         } catch (final Exception e) {
194             throw new CrawlingAccessException("Could not serialize object: " + responseData.getUrl(), e);
195         }
196         resultData.setEncoding(charsetName);
197     }
198 
199     protected void normalizeData(final ResponseData responseData, final Map<String, Object> dataMap) {
200         final Object titleObj = dataMap.get(fessConfig.getIndexFieldTitle());
201         if (titleObj != null) {
202             dataMap.put(fessConfig.getIndexFieldTitle(),
203                     ComponentUtil.getDocumentHelper().getTitle(responseData, titleObj.toString(), dataMap));
204         }
205     }
206 
207     protected void processMetaRobots(final ResponseData responseData, final ResultData resultData, final Document document) {
208         final Map<String, String> configMap = getConfigPrameterMap(responseData, ConfigName.CONFIG);
209         final String ignore = configMap.get(IGNORE_ROBOTS_TAGS);
210         if (ignore == null) {
211             if (fessConfig.isCrawlerIgnoreRobotsTags()) {
212                 return;
213             }
214         } else if (Boolean.parseBoolean(ignore)) {
215             return;
216         }
217 
218         // meta tag
219         try {
220             final Node value = getXPathAPI().selectSingleNode(document, META_NAME_ROBOTS_CONTENT);
221             if (value != null) {
222                 boolean noindex = false;
223                 boolean nofollow = false;
224                 final String content = value.getTextContent().toLowerCase(Locale.ROOT);
225                 if (content.contains(ROBOTS_TAG_NONE)) {
226                     noindex = true;
227                     nofollow = true;
228                 } else {
229                     if (content.contains(ROBOTS_TAG_NOINDEX)) {
230                         noindex = true;
231                     }
232                     if (content.contains(ROBOTS_TAG_NOFOLLOW)) {
233                         nofollow = true;
234                     }
235                 }
236                 if (noindex && nofollow) {
237                     logger.info("META(robots=noindex,nofollow): " + responseData.getUrl());
238                     throw new ChildUrlsException(Collections.emptySet(), "#processMetaRobots");
239                 } else if (noindex) {
240                     logger.info("META(robots=noindex): " + responseData.getUrl());
241                     storeChildUrls(responseData, resultData);
242                     throw new ChildUrlsException(resultData.getChildUrlSet(), "#processMetaRobots");
243                 } else if (nofollow) {
244                     logger.info("META(robots=nofollow): " + responseData.getUrl());
245                     responseData.setNoFollow(true);
246                 }
247             }
248         } catch (final TransformerException e) {
249             logger.warn("Could not parse a value of " + META_NAME_ROBOTS_CONTENT, e);
250         }
251 
252     }
253 
254     protected void processXRobotsTag(final ResponseData responseData, final ResultData resultData) {
255         final Map<String, String> configMap = getConfigPrameterMap(responseData, ConfigName.CONFIG);
256         final String ignore = configMap.get(IGNORE_ROBOTS_TAGS);
257         if (ignore == null) {
258             if (fessConfig.isCrawlerIgnoreRobotsTags()) {
259                 return;
260             }
261         } else if (Boolean.parseBoolean(ignore)) {
262             return;
263         }
264 
265         // X-Robots-Tag
266         responseData.getMetaDataMap().entrySet().stream().filter(e -> e.getKey().equalsIgnoreCase(X_ROBOTS_TAG) && e.getValue() != null)
267                 .forEach(e -> {
268                     boolean noindex = false;
269                     boolean nofollow = false;
270                     final String value = e.getValue().toString().toLowerCase(Locale.ROOT);
271                     if (value.contains(ROBOTS_TAG_NONE)) {
272                         noindex = true;
273                         nofollow = true;
274                     } else {
275                         if (value.contains(ROBOTS_TAG_NOINDEX)) {
276                             noindex = true;
277                         }
278                         if (value.contains(ROBOTS_TAG_NOFOLLOW)) {
279                             nofollow = true;
280                         }
281                     }
282                     if (noindex && nofollow) {
283                         logger.info("HEADER(robots=noindex,nofollow): " + responseData.getUrl());
284                         throw new ChildUrlsException(Collections.emptySet(), "#processXRobotsTag");
285                     } else if (noindex) {
286                         logger.info("HEADER(robots=noindex): " + responseData.getUrl());
287                         storeChildUrls(responseData, resultData);
288                         throw new ChildUrlsException(resultData.getChildUrlSet(), "#processXRobotsTag");
289                     } else if (nofollow) {
290                         logger.info("HEADER(robots=nofollow): " + responseData.getUrl());
291                         responseData.setNoFollow(true);
292                     }
293                 });
294     }
295 
296     protected Map<String, String> getConfigPrameterMap(final ResponseData responseData, final ConfigName config) {
297         final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
298         final CrawlingConfig crawlingConfig = crawlingConfigHelper.get(responseData.getSessionId());
299         final Map<String, String> configMap = crawlingConfig.getConfigParameterMap(config);
300         return configMap;
301     }
302 
303     protected boolean isValidUrl(final String urlStr) {
304         if (StringUtil.isBlank(urlStr)) {
305             return false;
306         }
307         final String value;
308         if (urlStr.startsWith("://")) {
309             value = "http" + urlStr;
310         } else if (urlStr.startsWith("//")) {
311             value = "http:" + urlStr;
312         } else {
313             value = urlStr;
314         }
315         try {
316             final URL url = new java.net.URL(value);
317             final String host = url.getHost();
318             if (StringUtil.isBlank(host)) {
319                 return false;
320             }
321             if ("http".equalsIgnoreCase(host) || "https".equalsIgnoreCase(host)) {
322                 return false;
323             }
324         } catch (final MalformedURLException e) {
325             return false;
326         }
327         return true;
328     }
329 
330     protected boolean isValidCanonicalUrl(final String url, final String canonicalUrl) {
331         if (url.startsWith("https:") && canonicalUrl.startsWith("http:")) {
332             if (logger.isDebugEnabled()) {
333                 logger.debug("Invalid Canonical Url(https->http): " + url + " -> " + canonicalUrl);
334             }
335             return false;
336         }
337         return true;
338     }
339 
340     protected void putAdditionalData(final Map<String, Object> dataMap, final ResponseData responseData, final Document document) {
341         // canonical
342         final String canonicalUrl = getCanonicalUrl(responseData, document);
343         if (canonicalUrl != null && !canonicalUrl.equals(responseData.getUrl()) && isValidUrl(canonicalUrl)
344                 && isValidCanonicalUrl(responseData.getUrl(), canonicalUrl)) {
345             final Set<RequestData> childUrlSet = new HashSet<>();
346             childUrlSet.add(RequestDataBuilder.newRequestData().get().url(canonicalUrl).build());
347             logger.info("CANONICAL: " + responseData.getUrl() + " -> " + canonicalUrl);
348             throw new ChildUrlsException(childUrlSet, this.getClass().getName() + "#putAdditionalData");
349         }
350 
351         final FessConfig fessConfig = ComponentUtil.getFessConfig();
352         final CrawlingInfoHelper crawlingInfoHelper = ComponentUtil.getCrawlingInfoHelper();
353         final String sessionId = crawlingInfoHelper.getCanonicalSessionId(responseData.getSessionId());
354         final PathMappingHelper pathMappingHelper = ComponentUtil.getPathMappingHelper();
355         final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
356         final CrawlingConfig crawlingConfig = crawlingConfigHelper.get(responseData.getSessionId());
357         final Date documentExpires = crawlingInfoHelper.getDocumentExpires(crawlingConfig);
358         final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
359         final FileTypeHelper fileTypeHelper = ComponentUtil.getFileTypeHelper();
360         final DocumentHelper documentHelper = ComponentUtil.getDocumentHelper();
361         final LabelTypeHelper labelTypeHelper = ComponentUtil.getLabelTypeHelper();
362         String url = responseData.getUrl();
363         final String indexingTarget = crawlingConfig.getIndexingTarget(url);
364         url = pathMappingHelper.replaceUrl(sessionId, url);
365         final String mimeType = responseData.getMimeType();
366 
367         final Map<String, String> fieldConfigMap = crawlingConfig.getConfigParameterMap(ConfigName.FIELD);
368         final Map<String, String> xpathConfigMap = crawlingConfig.getConfigParameterMap(ConfigName.XPATH);
369 
370         String urlEncoding;
371         final UrlQueue<?> urlQueue = CrawlingParameterUtil.getUrlQueue();
372         if (urlQueue != null && urlQueue.getEncoding() != null) {
373             urlEncoding = urlQueue.getEncoding();
374         } else {
375             urlEncoding = responseData.getCharSet();
376         }
377 
378         // cid
379         final String configId = crawlingConfig.getConfigId();
380         if (configId != null) {
381             putResultDataBody(dataMap, fessConfig.getIndexFieldConfigId(), configId);
382         }
383         //  expires
384         if (documentExpires != null) {
385             putResultDataBody(dataMap, fessConfig.getIndexFieldExpires(), documentExpires);
386         }
387         // lang
388         final String lang = systemHelper.normalizeHtmlLang(getSingleNodeValue(document, getLangXpath(fessConfig, xpathConfigMap), true));
389         if (lang != null) {
390             putResultDataBody(dataMap, fessConfig.getIndexFieldLang(), lang);
391         }
392         // title
393         // content
394         final String body = getSingleNodeValue(document, getContentXpath(fessConfig, xpathConfigMap), prunedContent);
395         putResultDataBody(dataMap, fessConfig.getIndexFieldContent(), documentHelper.getContent(responseData, body, dataMap));
396         if ((Constants.TRUE.equalsIgnoreCase(fieldConfigMap.get(fessConfig.getIndexFieldCache())) || fessConfig
397                 .isCrawlerDocumentCacheEnabled()) && fessConfig.isSupportedDocumentCacheMimetypes(mimeType)) {
398             if (responseData.getContentLength() > 0
399                     && responseData.getContentLength() <= fessConfig.getCrawlerDocumentCacheMaxSizeAsInteger().longValue()) {
400                 String charSet = responseData.getCharSet();
401                 if (charSet == null) {
402                     charSet = Constants.UTF_8;
403                 }
404                 try (final BufferedInputStream is = new BufferedInputStream(responseData.getResponseBody())) {
405                     // cache
406                     putResultDataBody(dataMap, fessConfig.getIndexFieldCache(), new String(InputStreamUtil.getBytes(is), charSet));
407                     putResultDataBody(dataMap, fessConfig.getIndexFieldHasCache(), Constants.TRUE);
408                 } catch (final Exception e) {
409                     logger.warn("Failed to write a cache: " + sessionId + ":" + responseData, e);
410                 }
411             } else {
412                 logger.debug("Content size is too large({} > {}): {}", responseData.getContentLength(),
413                         fessConfig.getCrawlerDocumentCacheMaxSizeAsInteger(), responseData.getUrl());
414             }
415         }
416         // digest
417         final String digest = getSingleNodeValue(document, getDigestXpath(fessConfig, xpathConfigMap), false);
418         if (StringUtil.isNotBlank(digest)) {
419             putResultDataBody(dataMap, fessConfig.getIndexFieldDigest(), digest);
420         } else {
421             putResultDataBody(dataMap, fessConfig.getIndexFieldDigest(),
422                     documentHelper.getDigest(responseData, body, dataMap, fessConfig.getCrawlerDocumentHtmlMaxDigestLengthAsInteger()));
423         }
424         // segment
425         putResultDataBody(dataMap, fessConfig.getIndexFieldSegment(), sessionId);
426         // host
427         putResultDataBody(dataMap, fessConfig.getIndexFieldHost(), getHost(url));
428         // site
429         putResultDataBody(dataMap, fessConfig.getIndexFieldSite(), getSite(url, urlEncoding));
430         // filename
431         final String fileName = getFileName(url, urlEncoding);
432         if (StringUtil.isNotBlank(fileName)) {
433             putResultDataBody(dataMap, fessConfig.getIndexFieldFilename(), fileName);
434         }
435         // url
436         putResultDataBody(dataMap, fessConfig.getIndexFieldUrl(), url);
437         // created
438         final Date now = systemHelper.getCurrentTime();
439         putResultDataBody(dataMap, fessConfig.getIndexFieldCreated(), now);
440         // anchor
441         putResultDataBody(dataMap, fessConfig.getIndexFieldAnchor(), getAnchorList(document, responseData));
442         // mimetype
443         putResultDataBody(dataMap, fessConfig.getIndexFieldMimetype(), mimeType);
444         if (fileTypeHelper != null) {
445             // filetype
446             putResultDataBody(dataMap, fessConfig.getIndexFieldFiletype(), fileTypeHelper.get(mimeType));
447         }
448         // content_length
449         putResultDataBody(dataMap, fessConfig.getIndexFieldContentLength(), Long.toString(responseData.getContentLength()));
450         // last_modified
451         final Date lastModified = responseData.getLastModified();
452         if (lastModified != null) {
453             putResultDataBody(dataMap, fessConfig.getIndexFieldLastModified(), lastModified);
454             // timestamp
455             putResultDataBody(dataMap, fessConfig.getIndexFieldTimestamp(), lastModified);
456         } else {
457             // timestamp
458             putResultDataBody(dataMap, fessConfig.getIndexFieldTimestamp(), now);
459         }
460         // indexingTarget
461         putResultDataBody(dataMap, Constants.INDEXING_TARGET, indexingTarget);
462         //  boost
463         putResultDataBody(dataMap, fessConfig.getIndexFieldBoost(), crawlingConfig.getDocumentBoost());
464         // label: labelType
465         putResultDataBody(dataMap, fessConfig.getIndexFieldLabel(), labelTypeHelper.getMatchedLabelValueSet(url));
466         // role: roleType
467         final List<String> roleTypeList = new ArrayList<>();
468         stream(crawlingConfig.getPermissions()).of(stream -> stream.forEach(p -> roleTypeList.add(p)));
469         putResultDataBody(dataMap, fessConfig.getIndexFieldRole(), roleTypeList);
470         // virtualHosts
471         putResultDataBody(dataMap, fessConfig.getIndexFieldVirtualHost(),
472                 stream(crawlingConfig.getVirtualHosts()).get(stream -> stream.filter(StringUtil::isNotBlank).collect(Collectors.toList())));
473         // id
474         putResultDataBody(dataMap, fessConfig.getIndexFieldId(), crawlingInfoHelper.generateId(dataMap));
475         // parentId
476         String parentUrl = responseData.getParentUrl();
477         if (StringUtil.isNotBlank(parentUrl)) {
478             parentUrl = pathMappingHelper.replaceUrl(sessionId, parentUrl);
479             putResultDataBody(dataMap, fessConfig.getIndexFieldUrl(), parentUrl);
480             putResultDataBody(dataMap, fessConfig.getIndexFieldParentId(), crawlingInfoHelper.generateId(dataMap));
481             putResultDataBody(dataMap, fessConfig.getIndexFieldUrl(), url); // set again
482         }
483         // thumbnail
484         final String thumbnailUrl = getThumbnailUrl(responseData, document);
485         if (StringUtil.isNotBlank(thumbnailUrl)) {
486             putResultDataBody(dataMap, fessConfig.getIndexFieldThumbnail(), thumbnailUrl);
487         }
488 
489         // from config
490         final Map<String, String> scriptConfigMap = crawlingConfig.getConfigParameterMap(ConfigName.SCRIPT);
491         xpathConfigMap.entrySet().stream().filter(e -> !e.getKey().startsWith("default.")).forEach(e -> {
492             final String key = e.getKey();
493             final String value = getSingleNodeValue(document, e.getValue(), true);
494             putResultDataWithTemplate(dataMap, key, value, scriptConfigMap.get(key));
495         });
496         crawlingConfig.getConfigParameterMap(ConfigName.VALUE).entrySet().stream().forEach(e -> {
497             final String key = e.getKey();
498             final String value = e.getValue();
499             putResultDataWithTemplate(dataMap, key, value, scriptConfigMap.get(key));
500         });
501     }
502 
503     protected String getLangXpath(final FessConfig fessConfig, final Map<String, String> xpathConfigMap) {
504         final String xpath = xpathConfigMap.get("default.lang");
505         if (StringUtil.isNotBlank(xpath)) {
506             return xpath;
507         }
508         return fessConfig.getCrawlerDocumentHtmlLangXpath();
509     }
510 
511     protected String getContentXpath(final FessConfig fessConfig, final Map<String, String> xpathConfigMap) {
512         final String xpath = xpathConfigMap.get("default.content");
513         if (StringUtil.isNotBlank(xpath)) {
514             return xpath;
515         }
516         return fessConfig.getCrawlerDocumentHtmlContentXpath();
517     }
518 
519     protected String getDigestXpath(final FessConfig fessConfig, final Map<String, String> xpathConfigMap) {
520         final String xpath = xpathConfigMap.get("default.digest");
521         if (StringUtil.isNotBlank(xpath)) {
522             return xpath;
523         }
524         return fessConfig.getCrawlerDocumentHtmlDigestXpath();
525     }
526 
527     protected String getCanonicalUrl(final ResponseData responseData, final Document document) {
528         final Map<String, String> configMap = getConfigPrameterMap(responseData, ConfigName.CONFIG);
529         String xpath = configMap.get(HTML_CANONICAL_XPATH);
530         if (xpath == null) {
531             xpath = fessConfig.getCrawlerDocumentHtmlCanonicalXpath();
532         }
533         if (StringUtil.isBlank(xpath)) {
534             return null;
535         }
536         final String canonicalUrl = getSingleNodeValue(document, xpath, false);
537         if (StringUtil.isBlank(canonicalUrl)) {
538             return null;
539         }
540         return normalizeCanonicalUrl(responseData.getUrl(), canonicalUrl);
541     }
542 
543     protected String normalizeCanonicalUrl(final String baseUrl, final String canonicalUrl) {
544         try {
545             final URL u = new URL(baseUrl);
546             return new URL(u, canonicalUrl.startsWith(":") ? u.getProtocol() + canonicalUrl : canonicalUrl).toString();
547         } catch (final MalformedURLException e) {
548             logger.warn("Invalid canonical url: " + baseUrl + " : " + canonicalUrl, e);
549         }
550         return null;
551     }
552 
553     protected String removeCommentTag(final String content) {
554         if (content == null) {
555             return StringUtil.EMPTY;
556         }
557         String value = content;
558         int pos = value.indexOf("<!--");
559         while (pos >= 0) {
560             final int lastPos = value.indexOf("-->", pos);
561             if (lastPos >= 0) {
562                 if (pos == 0) {
563                     value = " " + value.substring(lastPos + 3);
564                 } else {
565                     value = value.substring(0, pos) + " " + value.substring(lastPos + 3);
566                 }
567             } else {
568                 break;
569             }
570             pos = value.indexOf("<!--");
571         }
572         return value;
573     }
574 
575     protected String getSingleNodeValue(final Document document, final String xpath, final boolean pruned) {
576         StringBuilder buf = null;
577         NodeList list = null;
578         try {
579             list = getXPathAPI().selectNodeList(document, xpath);
580             for (int i = 0; i < list.getLength(); i++) {
581                 if (buf == null) {
582                     buf = new StringBuilder(1000);
583                 }
584                 Node node = list.item(i).cloneNode(true);
585                 if (useGoogleOffOn) {
586                     node = processGoogleOffOn(node, new ValueHolder<>(true));
587                 }
588                 if (pruned) {
589                     node = pruneNode(node);
590                 }
591                 parseTextContent(node, buf);
592             }
593         } catch (final Exception e) {
594             logger.warn("Could not parse a value of " + xpath);
595         }
596         if (buf == null) {
597             return null;
598         }
599         return buf.toString().trim();
600     }
601 
602     protected void parseTextContent(final Node node, final StringBuilder buf) {
603         if (node.hasChildNodes()) {
604             final NodeList nodeList = node.getChildNodes();
605             for (int i = 0; i < nodeList.getLength(); i++) {
606                 final Node childNode = nodeList.item(i);
607                 parseTextContent(childNode, buf);
608             }
609         } else if (node.getNodeType() == Node.TEXT_NODE) {
610             final String value = node.getTextContent();
611             if (value != null) {
612                 final String content = value.trim();
613                 if (content.length() > 0) {
614                     buf.append(' ').append(content);
615                 }
616             }
617         }
618     }
619 
620     protected Node processGoogleOffOn(final Node node, final ValueHolder<Boolean> flag) {
621         final NodeList nodeList = node.getChildNodes();
622         List<Node> removedNodeList = null;
623         for (int i = 0; i < nodeList.getLength(); i++) {
624             final Node childNode = nodeList.item(i);
625             if (childNode.getNodeType() == Node.COMMENT_NODE) {
626                 final String comment = childNode.getNodeValue().trim();
627                 if (comment.startsWith("googleoff:")) {
628                     flag.setValue(false);
629                 } else if (comment.startsWith("googleon:")) {
630                     flag.setValue(true);
631                 }
632             }
633 
634             if (!flag.getValue() && childNode.getNodeType() == Node.TEXT_NODE) {
635                 if (removedNodeList == null) {
636                     removedNodeList = new ArrayList<>();
637                 }
638                 removedNodeList.add(childNode);
639             } else {
640                 processGoogleOffOn(childNode, flag);
641             }
642         }
643 
644         if (removedNodeList != null) {
645             removedNodeList.stream().forEach(n -> node.removeChild(n));
646         }
647 
648         return node;
649     }
650 
651     protected Node pruneNode(final Node node) {
652         final NodeList nodeList = node.getChildNodes();
653         final List<Node> childNodeList = new ArrayList<>();
654         final List<Node> removedNodeList = new ArrayList<>();
655         for (int i = 0; i < nodeList.getLength(); i++) {
656             final Node childNode = nodeList.item(i);
657             if (isPrunedTag(childNode)) {
658                 removedNodeList.add(childNode);
659             } else {
660                 childNodeList.add(childNode);
661             }
662         }
663 
664         for (final Node childNode : removedNodeList) {
665             node.removeChild(childNode);
666         }
667 
668         for (final Node childNode : childNodeList) {
669             pruneNode(childNode);
670         }
671 
672         return node;
673     }
674 
675     protected boolean isPrunedTag(final Node node) {
676         for (final PrunedTag prunedTag : fessConfig.getCrawlerDocumentHtmlPrunedTagsAsArray()) {
677             if (prunedTag.matches(node)) {
678                 return true;
679             }
680         }
681         return false;
682     }
683 
684     protected String getMultipleNodeValue(final Document document, final String xpath) {
685         NodeList nodeList = null;
686         final StringBuilder buf = new StringBuilder(100);
687         try {
688             nodeList = getXPathAPI().selectNodeList(document, xpath);
689             for (int i = 0; i < nodeList.getLength(); i++) {
690                 final Node node = nodeList.item(i);
691                 buf.append(node.getTextContent());
692                 buf.append("\n");
693             }
694         } catch (final Exception e) {
695             logger.warn("Could not parse a value of " + xpath, e);
696         }
697         return buf.toString().trim();
698     }
699 
700     protected String replaceDuplicateHost(final String url) {
701         try {
702             // remove duplicate host
703             final DuplicateHostHelper duplicateHostHelper = ComponentUtil.getDuplicateHostHelper();
704             return duplicateHostHelper.convert(url);
705         } catch (final Exception e) {
706             return url;
707         }
708     }
709 
710     protected List<String> getAnchorList(final Document document, final ResponseData responseData) {
711         List<RequestData> anchorList = new ArrayList<>();
712         final String baseHref = getBaseHref(document);
713         try {
714             final URL url = getBaseUrl(responseData.getUrl(), baseHref);
715             for (final Map.Entry<String, String> entry : childUrlRuleMap.entrySet()) {
716                 for (final String u : getUrlFromTagAttribute(url, document, entry.getKey(), entry.getValue(), responseData.getCharSet())) {
717                     anchorList.add(RequestDataBuilder.newRequestData().get().url(u).build());
718                 }
719             }
720             anchorList = convertChildUrlList(anchorList);
721         } catch (final Exception e) {
722             logger.warn("Could not parse anchor tags.", e);
723         }
724 
725         final List<String> urlList = new ArrayList<>(anchorList.size());
726         for (final RequestData requestData : anchorList) {
727             urlList.add(requestData.getUrl());
728         }
729         return urlList;
730     }
731 
732     protected URL getBaseUrl(final String currentUrl, final String baseHref) throws MalformedURLException {
733         if (baseHref != null) {
734             return getURL(currentUrl, baseHref);
735         }
736         return new URL(currentUrl);
737     }
738 
739     @Override
740     protected List<RequestData> convertChildUrlList(final List<RequestData> urlList) {
741         if (urlList != null) {
742             for (final RequestData requestData : urlList) {
743                 String url = requestData.getUrl();
744                 for (final Map.Entry<String, String> entry : convertUrlMap.entrySet()) {
745                     url = url.replaceAll(entry.getKey(), entry.getValue());
746                 }
747                 requestData.setUrl(replaceDuplicateHost(url));
748             }
749         }
750         return urlList;
751     }
752 
753     @Override
754     public Object getData(final AccessResultData<?> accessResultData) {
755         final byte[] data = accessResultData.getData();
756         if (data != null) {
757             try {
758                 return SerializeUtil.fromBinaryToObject(data);
759             } catch (final Exception e) {
760                 throw new CrawlerSystemException("Could not create an instanced from bytes.", e);
761             }
762         }
763         return new HashMap<String, Object>();
764     }
765 
766     @Override
767     protected void addChildUrlFromTagAttribute(final List<String> urlList, final URL url, final String attrValue, final String encoding) {
768         final String urlValue = attrValue.trim();
769         URL childUrl;
770         String u = null;
771         try {
772             childUrl = new URL(url, urlValue.startsWith(":") ? url.getProtocol() + urlValue : urlValue);
773             u = encodeUrl(normalizeUrl(childUrl.toExternalForm()), encoding);
774         } catch (final MalformedURLException e) {
775             final int pos = urlValue.indexOf(':');
776             if (pos > 0 && pos < 10) {
777                 u = encodeUrl(normalizeUrl(urlValue), encoding);
778             }
779         }
780 
781         if (u == null) {
782             logger.warn("Ignored child URL: " + attrValue + " in " + url);
783             return;
784         }
785 
786         if (logger.isDebugEnabled()) {
787             logger.debug(attrValue + " -> " + u);
788         }
789         if (StringUtil.isNotBlank(u)) {
790             if (logger.isDebugEnabled()) {
791                 logger.debug("Add Child: " + u);
792             }
793             urlList.add(u);
794         } else {
795             if (logger.isDebugEnabled()) {
796                 logger.debug("Skip Child: " + u);
797             }
798         }
799     }
800 
801     private boolean isUtf8BomBytes(final byte[] b) {
802         return b[0] == (byte) 0xEF && b[1] == (byte) 0xBB && b[2] == (byte) 0xBF;
803     }
804 
805     public void setUseGoogleOffOn(final boolean useGoogleOffOn) {
806         this.useGoogleOffOn = useGoogleOffOn;
807     }
808 
809     protected String getThumbnailUrl(final ResponseData responseData, final Document document) {
810         // TODO PageMap
811         try {
812             // meta thumbnail
813             final Node thumbnailNode = getXPathAPI().selectSingleNode(document, META_NAME_THUMBNAIL_CONTENT);
814             if (thumbnailNode != null) {
815                 final String content = thumbnailNode.getTextContent();
816                 if (StringUtil.isNotBlank(content)) {
817                     final URL thumbnailUrl = getURL(responseData.getUrl(), content);
818                     if (thumbnailUrl != null) {
819                         return thumbnailUrl.toExternalForm();
820                     }
821                 }
822             }
823 
824             // meta og:image
825             final Node ogImageNode = getXPathAPI().selectSingleNode(document, META_PROPERTY_OGIMAGE_CONTENT);
826             if (ogImageNode != null) {
827                 final String content = ogImageNode.getTextContent();
828                 if (StringUtil.isNotBlank(content)) {
829                     final URL thumbnailUrl = getURL(responseData.getUrl(), content);
830                     if (thumbnailUrl != null) {
831                         return thumbnailUrl.toExternalForm();
832                     }
833                 }
834             }
835 
836             final NodeList imgNodeList = getXPathAPI().selectNodeList(document, fessConfig.getThumbnailHtmlImageXpath());
837             String firstThumbnailUrl = null;
838             for (int i = 0; i < imgNodeList.getLength(); i++) {
839                 final Node imgNode = imgNodeList.item(i);
840                 if (logger.isDebugEnabled()) {
841                     logger.debug("img tag: " + imgNode);
842                 }
843                 final NamedNodeMap attributes = imgNode.getAttributes();
844                 final String thumbnailUrl = getThumbnailSrc(responseData.getUrl(), attributes);
845                 final Integer height = getAttributeAsInteger(attributes, "height");
846                 final Integer width = getAttributeAsInteger(attributes, "width");
847                 if (!fessConfig.isThumbnailHtmlImageUrl(thumbnailUrl)) {
848                     continue;
849                 } else if (height != null && width != null) {
850                     try {
851                         if (fessConfig.validateThumbnailSize(width, height)) {
852                             return thumbnailUrl;
853                         }
854                     } catch (final Exception e) {
855                         logger.debug("Failed to parse " + imgNode + " at " + responseData.getUrl(), e);
856                     }
857                 } else if (firstThumbnailUrl == null) {
858                     firstThumbnailUrl = thumbnailUrl;
859                 }
860             }
861 
862             if (firstThumbnailUrl != null) {
863                 return firstThumbnailUrl;
864             }
865         } catch (final Exception e) {
866             logger.warn("Failed to retrieve thumbnail url from " + responseData.getUrl(), e);
867         }
868         return null;
869     }
870 
871     protected String getThumbnailSrc(final String url, final NamedNodeMap attributes) {
872         final Node srcNode = attributes.getNamedItem("src");
873         if (srcNode != null) {
874             try {
875                 final URL thumbnailUrl = getURL(url, srcNode.getTextContent());
876                 if (thumbnailUrl != null) {
877                     return thumbnailUrl.toExternalForm();
878                 }
879             } catch (final Exception e) {
880                 if (logger.isDebugEnabled()) {
881                     logger.debug("Failed to parse thumbnail url for " + url + " : " + attributes, e);
882                 }
883             }
884         }
885         return null;
886     }
887 
888     protected Integer getAttributeAsInteger(final NamedNodeMap attributes, final String name) {
889         final Node namedItem = attributes.getNamedItem(name);
890         if (namedItem == null) {
891             return null;
892         }
893         final String value = namedItem.getTextContent();
894         if (value == null) {
895             return null;
896         }
897         try {
898             return Integer.parseInt(value);
899         } catch (final NumberFormatException e) {
900             if (value.endsWith("%") || value.endsWith("px")) {
901                 return null;
902             }
903             return 0;
904         }
905     }
906 
907     protected URL getURL(final String currentUrl, final String url) throws MalformedURLException {
908         if (url != null) {
909             if (url.startsWith("://")) {
910                 final String protocol = currentUrl.split(":")[0];
911                 return new URL(protocol + url);
912             } else if (url.startsWith("//")) {
913                 final String protocol = currentUrl.split(":")[0];
914                 return new URL(protocol + ":" + url);
915             } else if (url.startsWith("/") || url.indexOf(':') == -1) {
916                 return new URL(new URL(currentUrl), url);
917             }
918             return new URL(url);
919         }
920         return null;
921     }
922 
923     public void addFieldRule(final String name, final String xpath, final boolean isPruned) {
924         addFieldRule(name, xpath);
925         fieldPrunedRuleMap.put(name, isPruned);
926     }
927 }