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.InputStream;
21  import java.net.URLDecoder;
22  import java.util.ArrayList;
23  import java.util.Date;
24  import java.util.HashMap;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.stream.Collectors;
28  
29  import org.apache.commons.lang3.StringUtils;
30  import org.apache.tika.metadata.HttpHeaders;
31  import org.apache.tika.metadata.TikaMetadataKeys;
32  import org.codelibs.core.io.SerializeUtil;
33  import org.codelibs.core.lang.StringUtil;
34  import org.codelibs.core.misc.Tuple3;
35  import org.codelibs.fess.Constants;
36  import org.codelibs.fess.crawler.entity.AccessResultData;
37  import org.codelibs.fess.crawler.entity.ExtractData;
38  import org.codelibs.fess.crawler.entity.ResponseData;
39  import org.codelibs.fess.crawler.entity.ResultData;
40  import org.codelibs.fess.crawler.entity.UrlQueue;
41  import org.codelibs.fess.crawler.exception.CrawlerSystemException;
42  import org.codelibs.fess.crawler.exception.CrawlingAccessException;
43  import org.codelibs.fess.crawler.extractor.Extractor;
44  import org.codelibs.fess.crawler.transformer.impl.AbstractTransformer;
45  import org.codelibs.fess.crawler.util.CrawlingParameterUtil;
46  import org.codelibs.fess.es.config.exentity.CrawlingConfig;
47  import org.codelibs.fess.es.config.exentity.CrawlingConfig.ConfigName;
48  import org.codelibs.fess.helper.CrawlingConfigHelper;
49  import org.codelibs.fess.helper.CrawlingInfoHelper;
50  import org.codelibs.fess.helper.DocumentHelper;
51  import org.codelibs.fess.helper.FileTypeHelper;
52  import org.codelibs.fess.helper.LabelTypeHelper;
53  import org.codelibs.fess.helper.PathMappingHelper;
54  import org.codelibs.fess.helper.PermissionHelper;
55  import org.codelibs.fess.helper.SystemHelper;
56  import org.codelibs.fess.mylasta.direction.FessConfig;
57  import org.codelibs.fess.taglib.FessFunctions;
58  import org.codelibs.fess.util.ComponentUtil;
59  import org.slf4j.Logger;
60  import org.slf4j.LoggerFactory;
61  
62  public abstract class AbstractFessFileTransformer extends AbstractTransformer implements FessTransformer {
63  
64      private static final Logger logger = LoggerFactory.getLogger(AbstractFessFileTransformer.class);
65  
66      protected Map<String, String> metaContentMapping;
67  
68      protected FessConfig fessConfig;
69  
70      protected abstract Extractor getExtractor(ResponseData responseData);
71  
72      @Override
73      public ResultData transform(final ResponseData responseData) {
74          if (responseData == null || !responseData.hasResponseBody()) {
75              throw new CrawlingAccessException("No response body.");
76          }
77  
78          final ResultData resultData = new ResultData();
79          resultData.setTransformerName(getName());
80          try {
81              resultData.setData(SerializeUtil.fromObjectToBinary(generateData(responseData)));
82          } catch (final Exception e) {
83              throw new CrawlingAccessException("Could not serialize object", e);
84          }
85          resultData.setEncoding(fessConfig.getCrawlerCrawlingDataEncoding());
86  
87          return resultData;
88      }
89  
90      protected Map<String, Object> generateData(final ResponseData responseData) {
91          final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
92          final CrawlingConfig crawlingConfig = crawlingConfigHelper.get(responseData.getSessionId());
93          final Extractor extractor = getExtractor(responseData);
94          final String mimeType = responseData.getMimeType();
95          final StringBuilder contentMetaBuf = new StringBuilder(1000);
96          final Map<String, Object> dataMap = new HashMap<>();
97          final Map<String, Object> metaDataMap = new HashMap<>();
98          String content;
99          try (final InputStream in = responseData.getResponseBody()) {
100             final ExtractData extractData = getExtractData(extractor, in, createExtractParams(responseData, crawlingConfig));
101             content = extractData.getContent();
102             if (fessConfig.isCrawlerDocumentFileIgnoreEmptyContent() && StringUtil.isBlank(content)) {
103                 return null;
104             }
105             if (getLogger().isDebugEnabled()) {
106                 getLogger().debug("ExtractData: " + extractData);
107             }
108             // meta
109             extractData
110                     .getKeySet()
111                     .stream()
112                     .filter(k -> extractData.getValues(k) != null)
113                     .forEach(key -> {
114                         final String[] values = extractData.getValues(key);
115                         metaDataMap.put(key, values);
116 
117                         // meta -> content
118                             if (fessConfig.isCrawlerMetadataContentIncluded(key)) {
119                                 final String joinedValue = StringUtils.join(values, ' ');
120                                 if (StringUtil.isNotBlank(joinedValue)) {
121                                     if (contentMetaBuf.length() > 0) {
122                                         contentMetaBuf.append(' ');
123                                     }
124                                     contentMetaBuf.append(joinedValue.trim());
125                                 }
126                             }
127 
128                             final Tuple3<String, String, String> mapping = fessConfig.getCrawlerMetadataNameMapping(key);
129                             if (mapping != null) {
130                                 if (Constants.MAPPING_TYPE_ARRAY.equalsIgnoreCase(mapping.getValue2())) {
131                                     dataMap.put(mapping.getValue1(), values);
132                                 } else if (Constants.MAPPING_TYPE_STRING.equalsIgnoreCase(mapping.getValue2())) {
133                                     final String joinedValue = StringUtils.join(values, ' ');
134                                     dataMap.put(mapping.getValue1(), joinedValue.trim());
135                                 } else if (values.length == 1) {
136                                     try {
137                                         if (Constants.MAPPING_TYPE_LONG.equalsIgnoreCase(mapping.getValue2())) {
138                                             dataMap.put(mapping.getValue1(), Long.parseLong(values[0]));
139                                         } else if (Constants.MAPPING_TYPE_DOUBLE.equalsIgnoreCase(mapping.getValue2())) {
140                                             dataMap.put(mapping.getValue1(), Double.parseDouble(values[0]));
141                                         } else if (Constants.MAPPING_TYPE_DATE.equalsIgnoreCase(mapping.getValue2())
142                                                 || Constants.MAPPING_TYPE_PDF_DATE.equalsIgnoreCase(mapping.getValue2())) {
143                                             final String dateFormate;
144                                             if (StringUtil.isNotBlank(mapping.getValue3())) {
145                                                 dateFormate = mapping.getValue3();
146                                             } else if (Constants.MAPPING_TYPE_PDF_DATE.equalsIgnoreCase(mapping.getValue2())) {
147                                                 dateFormate = mapping.getValue2();
148                                             } else {
149                                                 dateFormate = Constants.DATE_OPTIONAL_TIME;
150                                             }
151                                             final Date dt = FessFunctions.parseDate(values[0], dateFormate);
152                                             if (dt != null) {
153                                                 dataMap.put(mapping.getValue1(), FessFunctions.formatDate(dt));
154                                             } else {
155                                                 logger.warn("Failed to parse " + mapping.toString());
156                                             }
157                                         } else {
158                                             logger.warn("Unknown mapping type: {}={}", key, mapping);
159                                         }
160                                     } catch (final Exception e) {
161                                         logger.warn("Failed to parse " + values[0], e);
162                                     }
163                                 }
164                             }
165 
166                         });
167         } catch (final Exception e) {
168             final CrawlingAccessException rcae = new CrawlingAccessException("Could not get a text from " + responseData.getUrl(), e);
169             rcae.setLogLevel(CrawlingAccessException.WARN);
170             throw rcae;
171         }
172         if (content == null) {
173             content = StringUtil.EMPTY;
174         }
175         final String contentMeta = contentMetaBuf.toString().trim();
176 
177         final CrawlingInfoHelper crawlingInfoHelper = ComponentUtil.getCrawlingInfoHelper();
178         final String sessionId = crawlingInfoHelper.getCanonicalSessionId(responseData.getSessionId());
179         final PathMappingHelper pathMappingHelper = ComponentUtil.getPathMappingHelper();
180         final Date documentExpires = crawlingInfoHelper.getDocumentExpires(crawlingConfig);
181         final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
182         final FileTypeHelper fileTypeHelper = ComponentUtil.getFileTypeHelper();
183         final DocumentHelper documentHelper = ComponentUtil.getDocumentHelper();
184         String url = responseData.getUrl();
185         final String indexingTarget = crawlingConfig.getIndexingTarget(url);
186         url = pathMappingHelper.replaceUrl(sessionId, url);
187 
188         final Map<String, String> fieldConfigMap = crawlingConfig.getConfigParameterMap(ConfigName.FIELD);
189 
190         String urlEncoding;
191         final UrlQueue<?> urlQueue = CrawlingParameterUtil.getUrlQueue();
192         if (urlQueue != null && urlQueue.getEncoding() != null) {
193             urlEncoding = urlQueue.getEncoding();
194         } else {
195             urlEncoding = responseData.getCharSet();
196         }
197 
198         // cid
199         final String configId = crawlingConfig.getConfigId();
200         if (configId != null) {
201             putResultDataBody(dataMap, fessConfig.getIndexFieldConfigId(), configId);
202         }
203         //  expires
204         if (documentExpires != null) {
205             putResultDataBody(dataMap, fessConfig.getIndexFieldExpires(), documentExpires);
206         }
207         // segment
208         putResultDataBody(dataMap, fessConfig.getIndexFieldSegment(), sessionId);
209         // content
210         final StringBuilder buf = new StringBuilder(content.length() + 1000);
211         if (fessConfig.isCrawlerDocumentFileAppendBodyContent()) {
212             buf.append(content);
213         }
214         if (fessConfig.isCrawlerDocumentFileAppendMetaContent()) {
215             if (buf.length() > 0) {
216                 buf.append(' ');
217             }
218             buf.append(contentMeta);
219         }
220         final String bodyBase = buf.toString().trim();
221         final String body = documentHelper.getContent(responseData, bodyBase, dataMap);
222         putResultDataBody(dataMap, fessConfig.getIndexFieldContent(), body);
223         if ((Constants.TRUE.equalsIgnoreCase(fieldConfigMap.get(fessConfig.getIndexFieldCache())) || fessConfig
224                 .isCrawlerDocumentCacheEnabled()) && fessConfig.isSupportedDocumentCacheMimetypes(mimeType)) {
225             if (responseData.getContentLength() > 0
226                     && responseData.getContentLength() <= fessConfig.getCrawlerDocumentCacheMaxSizeAsInteger().longValue()) {
227 
228                 final String cache = content.trim().replaceAll("[ \\t\\x0B\\f]+", " ");
229                 // text cache
230                 putResultDataBody(dataMap, fessConfig.getIndexFieldCache(), cache);
231                 putResultDataBody(dataMap, fessConfig.getIndexFieldHasCache(), Constants.TRUE);
232             }
233         }
234         // digest
235         putResultDataBody(dataMap, fessConfig.getIndexFieldDigest(),
236                 documentHelper.getDigest(responseData, bodyBase, dataMap, fessConfig.getCrawlerDocumentFileMaxDigestLengthAsInteger()));
237         // title
238         final String fileName = getFileName(url, urlEncoding);
239         if (!hasTitle(dataMap)) {
240             final String titleField = fessConfig.getIndexFieldTitle();
241             dataMap.remove(titleField);
242             if (url.endsWith("/")) {
243                 if (StringUtil.isNotBlank(content)) {
244                     putResultDataBody(
245                             dataMap,
246                             titleField,
247                             documentHelper.getDigest(responseData, body, dataMap,
248                                     fessConfig.getCrawlerDocumentFileMaxTitleLengthAsInteger()));
249                 } else {
250                     putResultDataBody(dataMap, titleField, fessConfig.getCrawlerDocumentFileNoTitleLabel());
251                 }
252             } else {
253                 if (StringUtil.isBlank(fileName)) {
254                     putResultDataBody(dataMap, titleField, decodeUrlAsName(url, url.startsWith("file:")));
255                 } else {
256                     putResultDataBody(dataMap, titleField, fileName);
257                 }
258             }
259         }
260         // host
261         putResultDataBody(dataMap, fessConfig.getIndexFieldHost(), getHostOnFile(url));
262         // site
263         putResultDataBody(dataMap, fessConfig.getIndexFieldSite(), getSiteOnFile(url, urlEncoding));
264         // filename
265         if (StringUtil.isNotBlank(fileName)) {
266             putResultDataBody(dataMap, fessConfig.getIndexFieldFilename(), fileName);
267         }
268         // url
269         putResultDataBody(dataMap, fessConfig.getIndexFieldUrl(), url);
270         // created
271         final Date now = systemHelper.getCurrentTime();
272         putResultDataBody(dataMap, fessConfig.getIndexFieldCreated(), now);
273         // TODO anchor
274         putResultDataBody(dataMap, fessConfig.getIndexFieldAnchor(), StringUtil.EMPTY);
275         // mimetype
276         putResultDataBody(dataMap, fessConfig.getIndexFieldMimetype(), mimeType);
277         if (fileTypeHelper != null) {
278             // filetype
279             putResultDataBody(dataMap, fessConfig.getIndexFieldFiletype(), fileTypeHelper.get(mimeType));
280         }
281         // content_length
282         putResultDataBody(dataMap, fessConfig.getIndexFieldContentLength(), Long.toString(responseData.getContentLength()));
283         // last_modified
284         final Date lastModified = getLastModified(dataMap, responseData);
285         if (lastModified != null) {
286             dataMap.put(fessConfig.getIndexFieldLastModified(), lastModified); // overwrite
287             // timestamp
288             putResultDataBody(dataMap, fessConfig.getIndexFieldTimestamp(), lastModified);
289         } else {
290             // timestamp
291             putResultDataBody(dataMap, fessConfig.getIndexFieldTimestamp(), now);
292         }
293         // indexingTarget
294         putResultDataBody(dataMap, Constants.INDEXING_TARGET, indexingTarget);
295         //  boost
296         putResultDataBody(dataMap, fessConfig.getIndexFieldBoost(), crawlingConfig.getDocumentBoost());
297         // label: labelType
298         final LabelTypeHelper labelTypeHelper = ComponentUtil.getLabelTypeHelper();
299         putResultDataBody(dataMap, fessConfig.getIndexFieldLabel(), labelTypeHelper.getMatchedLabelValueSet(url));
300         // role: roleType
301         final List<String> roleTypeList = getRoleTypes(responseData);
302         stream(crawlingConfig.getPermissions()).of(stream -> stream.forEach(p -> roleTypeList.add(p)));
303         putResultDataBody(dataMap, fessConfig.getIndexFieldRole(), roleTypeList);
304         // virtualHosts
305         putResultDataBody(dataMap, fessConfig.getIndexFieldVirtualHost(),
306                 stream(crawlingConfig.getVirtualHosts()).get(stream -> stream.filter(StringUtil::isNotBlank).collect(Collectors.toList())));
307         // TODO date
308         // lang
309         if (StringUtil.isNotBlank(fessConfig.getCrawlerDocumentFileDefaultLang())) {
310             putResultDataBody(dataMap, fessConfig.getIndexFieldLang(), fessConfig.getCrawlerDocumentFileDefaultLang());
311         }
312         // id
313         putResultDataBody(dataMap, fessConfig.getIndexFieldId(), crawlingInfoHelper.generateId(dataMap));
314         // parentId
315         String parentUrl = responseData.getParentUrl();
316         if (StringUtil.isNotBlank(parentUrl)) {
317             parentUrl = pathMappingHelper.replaceUrl(sessionId, parentUrl);
318             putResultDataBody(dataMap, fessConfig.getIndexFieldUrl(), parentUrl);
319             putResultDataBody(dataMap, fessConfig.getIndexFieldParentId(), crawlingInfoHelper.generateId(dataMap));
320             putResultDataBody(dataMap, fessConfig.getIndexFieldUrl(), url); // set again
321         }
322         // thumbnail
323         putResultDataBody(dataMap, fessConfig.getIndexFieldThumbnail(), responseData.getUrl());
324 
325         // from config
326         final Map<String, String> scriptConfigMap = crawlingConfig.getConfigParameterMap(ConfigName.SCRIPT);
327         final Map<String, String> metaConfigMap = crawlingConfig.getConfigParameterMap(ConfigName.META);
328         for (final Map.Entry<String, String> entry : metaConfigMap.entrySet()) {
329             final String key = entry.getKey();
330             final String[] values = entry.getValue().split(",");
331             for (final String value : values) {
332                 putResultDataWithTemplate(dataMap, key, metaDataMap.get(value), scriptConfigMap.get(key));
333             }
334         }
335         final Map<String, String> valueConfigMap = crawlingConfig.getConfigParameterMap(ConfigName.VALUE);
336         for (final Map.Entry<String, String> entry : valueConfigMap.entrySet()) {
337             final String key = entry.getKey();
338             putResultDataWithTemplate(dataMap, key, entry.getValue(), scriptConfigMap.get(key));
339         }
340 
341         return dataMap;
342     }
343 
344     protected Date getLastModified(final Map<String, Object> dataMap, final ResponseData responseData) {
345         final Object lastModifiedObj = dataMap.get(fessConfig.getIndexFieldLastModified());
346         if (lastModifiedObj instanceof Date) {
347             return (Date) lastModifiedObj;
348         } else if (lastModifiedObj instanceof String) {
349             final Date lastModified = FessFunctions.parseDate(lastModifiedObj.toString());
350             if (lastModified != null) {
351                 return lastModified;
352             }
353         } else if (lastModifiedObj instanceof String[]) {
354             final String[] lastModifieds = (String[]) lastModifiedObj;
355             if (lastModifieds.length > 0) {
356                 final Date lastModified = FessFunctions.parseDate(lastModifieds[0]);
357                 if (lastModified != null) {
358                     return lastModified;
359                 }
360             }
361         }
362 
363         return responseData.getLastModified();
364     }
365 
366     protected boolean hasTitle(final Map<String, Object> dataMap) {
367         final Object titleObj = dataMap.get(fessConfig.getIndexFieldTitle());
368         if (titleObj != null) {
369             if (titleObj instanceof String[]) {
370                 return stream((String[]) titleObj).get(stream -> stream.anyMatch(StringUtil::isNotBlank));
371             } else {
372                 return StringUtil.isNotBlank(titleObj.toString());
373             }
374         }
375         return false;
376     }
377 
378     protected Map<String, String> createExtractParams(final ResponseData responseData, final CrawlingConfig crawlingConfig) {
379         final Map<String, String> params = new HashMap<>(crawlingConfig.getConfigParameterMap(ConfigName.CONFIG));
380         params.put(TikaMetadataKeys.RESOURCE_NAME_KEY, getResourceName(responseData));
381         params.put(HttpHeaders.CONTENT_TYPE, responseData.getMimeType());
382         params.put(HttpHeaders.CONTENT_ENCODING, responseData.getCharSet());
383         params.put(ExtractData.URL, responseData.getUrl());
384         return params;
385     }
386 
387     protected ExtractData getExtractData(final Extractor extractor, final InputStream in, final Map<String, String> params) {
388         try {
389             return extractor.getText(in, params);
390         } catch (final RuntimeException e) {
391             if (!fessConfig.isCrawlerIgnoreContentException()) {
392                 throw e;
393             }
394             if (logger.isDebugEnabled()) {
395                 logger.debug("Could not get a text.", e);
396             }
397         }
398         return new ExtractData();
399     }
400 
401     protected String getResourceName(final ResponseData responseData) {
402         String name = responseData.getUrl();
403         final String enc = responseData.getCharSet();
404 
405         if (name == null || enc == null) {
406             return null;
407         }
408 
409         name = name.replaceAll("/+$", StringUtil.EMPTY);
410         final int idx = name.lastIndexOf('/');
411         if (idx >= 0) {
412             name = name.substring(idx + 1);
413         }
414         try {
415             return URLDecoder.decode(name, enc);
416         } catch (final Exception e) {
417             return name;
418         }
419     }
420 
421     protected String getHostOnFile(final String url) {
422         if (StringUtil.isBlank(url)) {
423             return StringUtil.EMPTY; // empty
424         }
425 
426         if (url.startsWith("file:////")) {
427             final String value = decodeUrlAsName(url.substring(9), true);
428             final int pos = value.indexOf('/');
429             if (pos > 0) {
430                 return value.substring(0, pos);
431             } else if (pos == -1) {
432                 return value;
433             } else {
434                 return "localhost";
435             }
436         } else if (url.startsWith("file:")) {
437             return "localhost";
438         }
439 
440         return getHost(url);
441     }
442 
443     protected List<String> getRoleTypes(final ResponseData responseData) {
444         final List<String> roleTypeList = new ArrayList<>();
445         final PermissionHelper permissionHelper = ComponentUtil.getPermissionHelper();
446 
447         roleTypeList.addAll(permissionHelper.getSmbRoleTypeList(responseData));
448         roleTypeList.addAll(permissionHelper.getFileRoleTypeList(responseData));
449         roleTypeList.addAll(permissionHelper.getFtpRoleTypeList(responseData));
450 
451         return roleTypeList;
452     }
453 
454     protected String getSiteOnFile(final String url, final String encoding) {
455         if (StringUtil.isBlank(url)) {
456             return StringUtil.EMPTY; // empty
457         }
458 
459         if (url.startsWith("file:////")) {
460             final String value = decodeUrlAsName(url.substring(9), true);
461             return abbreviateSite("\\\\" + value.replace('/', '\\'));
462         } else if (url.startsWith("file:")) {
463             final String value = decodeUrlAsName(url.substring(5), true);
464             if (value.length() > 2 && value.charAt(2) == ':') {
465                 // Windows
466                 return abbreviateSite(value.substring(1).replace('/', '\\'));
467             } else {
468                 // Unix
469                 return abbreviateSite(value);
470             }
471         }
472 
473         return getSite(url, encoding);
474     }
475 
476     @Override
477     public Object getData(final AccessResultData<?> accessResultData) {
478         final byte[] data = accessResultData.getData();
479         if (data != null) {
480             try {
481                 return SerializeUtil.fromBinaryToObject(data);
482             } catch (final Exception e) {
483                 throw new CrawlerSystemException("Could not create an instanced from bytes.", e);
484             }
485         }
486         return new HashMap<String, Object>();
487     }
488 
489     public void addMetaContentMapping(final String metaname, final String dynamicField) {
490         if (metaContentMapping == null) {
491             metaContentMapping = new HashMap<>();
492         }
493         metaContentMapping.put(metaname, dynamicField);
494     }
495 
496 }