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.BufferedReader;
19  import java.io.ByteArrayInputStream;
20  import java.io.ByteArrayOutputStream;
21  import java.io.IOException;
22  import java.io.InputStreamReader;
23  import java.io.Reader;
24  import java.io.StringReader;
25  import java.util.Base64;
26  import java.util.HashSet;
27  import java.util.Map;
28  import java.util.Set;
29  import java.util.zip.GZIPInputStream;
30  import java.util.zip.GZIPOutputStream;
31  
32  import org.apache.commons.lang3.StringUtils;
33  import org.codelibs.core.io.ReaderUtil;
34  import org.codelibs.core.io.SerializeUtil;
35  import org.codelibs.core.lang.StringUtil;
36  import org.codelibs.fess.Constants;
37  import org.codelibs.fess.crawler.builder.RequestDataBuilder;
38  import org.codelibs.fess.crawler.client.CrawlerClient;
39  import org.codelibs.fess.crawler.client.CrawlerClientFactory;
40  import org.codelibs.fess.crawler.entity.RequestData;
41  import org.codelibs.fess.crawler.entity.ResponseData;
42  import org.codelibs.fess.crawler.entity.ResultData;
43  import org.codelibs.fess.crawler.exception.ChildUrlsException;
44  import org.codelibs.fess.crawler.exception.CrawlerSystemException;
45  import org.codelibs.fess.crawler.exception.CrawlingAccessException;
46  import org.codelibs.fess.crawler.processor.ResponseProcessor;
47  import org.codelibs.fess.crawler.processor.impl.DefaultResponseProcessor;
48  import org.codelibs.fess.crawler.rule.Rule;
49  import org.codelibs.fess.crawler.rule.RuleManager;
50  import org.codelibs.fess.crawler.transformer.Transformer;
51  import org.codelibs.fess.crawler.util.TextUtil;
52  import org.codelibs.fess.es.config.exentity.CrawlingConfig;
53  import org.codelibs.fess.mylasta.direction.FessConfig;
54  import org.codelibs.fess.util.ComponentUtil;
55  import org.lastaflute.di.core.SingletonLaContainer;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  public class DocumentHelper {
60      private static final Logger logger = LoggerFactory.getLogger(DocumentHelper.class);
61  
62      protected static final String SIMILAR_DOC_HASH_PREFIX = "$";
63  
64      public String getTitle(final ResponseData responseData, final String title, final Map<String, Object> dataMap) {
65          if (title == null) {
66              return StringUtil.EMPTY; // empty
67          }
68  
69          final int[] spaceChars = getSpaceChars();
70          try (final Reader reader = new StringReader(title)) {
71              return TextUtil.normalizeText(reader).initialCapacity(title.length()).spaceChars(spaceChars).execute();
72          } catch (final IOException e) {
73              return StringUtil.EMPTY; // empty
74          }
75      }
76  
77      public String getContent(final ResponseData responseData, final String content, final Map<String, Object> dataMap) {
78          if (content == null) {
79              return StringUtil.EMPTY; // empty
80          }
81  
82          final int maxAlphanumTermSize = getMaxAlphanumTermSize();
83          final int maxSymbolTermSize = getMaxSymbolTermSize();
84          final boolean duplicateTermRemoved = isDuplicateTermRemoved();
85          final int[] spaceChars = getSpaceChars();
86          try (final Reader reader = new StringReader(content)) {
87              return TextUtil.normalizeText(reader).initialCapacity(content.length()).maxAlphanumTermSize(maxAlphanumTermSize)
88                      .maxSymbolTermSize(maxSymbolTermSize).duplicateTermRemoved(duplicateTermRemoved).spaceChars(spaceChars).execute();
89          } catch (final IOException e) {
90              return StringUtil.EMPTY; // empty
91          }
92      }
93  
94      protected int getMaxAlphanumTermSize() {
95          final FessConfig fessConfig = ComponentUtil.getFessConfig();
96          return fessConfig.getCrawlerDocumentMaxAlphanumTermSizeAsInteger().intValue();
97      }
98  
99      protected int getMaxSymbolTermSize() {
100         final FessConfig fessConfig = ComponentUtil.getFessConfig();
101         return fessConfig.getCrawlerDocumentMaxSymbolTermSizeAsInteger().intValue();
102     }
103 
104     protected boolean isDuplicateTermRemoved() {
105         final FessConfig fessConfig = ComponentUtil.getFessConfig();
106         return fessConfig.isCrawlerDocumentDuplicateTermRemoved();
107     }
108 
109     protected int[] getSpaceChars() {
110         final FessConfig fessConfig = ComponentUtil.getFessConfig();
111         return fessConfig.getCrawlerDocumentSpaceCharsAsArray();
112     }
113 
114     public String getDigest(final ResponseData responseData, final String content, final Map<String, Object> dataMap, final int maxWidth) {
115         if (content == null) {
116             return StringUtil.EMPTY; // empty
117         }
118 
119         String subContent;
120         if (content.length() < maxWidth * 2) {
121             subContent = content;
122         } else {
123             subContent = content.substring(0, maxWidth * 2);
124         }
125 
126         final int[] spaceChars = getSpaceChars();
127         try (final Reader reader = new StringReader(subContent)) {
128             final String originalStr = TextUtil.normalizeText(reader).initialCapacity(content.length()).spaceChars(spaceChars).execute();
129             return StringUtils.abbreviate(originalStr, maxWidth);
130         } catch (final IOException e) {
131             return StringUtil.EMPTY; // empty
132         }
133     }
134 
135     public Map<String, Object> processRequest(final CrawlingConfig crawlingConfig, final String crawlingInfoId, final String url) {
136         if (StringUtil.isBlank(crawlingInfoId)) {
137             throw new CrawlingAccessException("sessionId is null.");
138         }
139 
140         final CrawlerClientFactory crawlerClientFactory = ComponentUtil.getCrawlerClientFactory();
141         crawlingConfig.initializeClientFactory(crawlerClientFactory);
142         final CrawlerClient client = crawlerClientFactory.getClient(url);
143         if (client == null) {
144             throw new CrawlingAccessException("CrawlerClient is null for " + url);
145         }
146 
147         final long startTime = System.currentTimeMillis();
148         try (final ResponseData responseData = client.execute(RequestDataBuilder.newRequestData().get().url(url).build())) {
149             if (responseData.getRedirectLocation() != null) {
150                 final Set<RequestData> childUrlList = new HashSet<>();
151                 childUrlList.add(RequestDataBuilder.newRequestData().get().url(responseData.getRedirectLocation()).build());
152                 throw new ChildUrlsException(childUrlList, this.getClass().getName() + "#RedirectedFrom:" + url);
153             }
154             responseData.setExecutionTime(System.currentTimeMillis() - startTime);
155             responseData.setSessionId(crawlingInfoId);
156 
157             final RuleManager ruleManager = SingletonLaContainer.getComponent(RuleManager.class);
158             final Rule rule = ruleManager.getRule(responseData);
159             if (rule == null) {
160                 throw new CrawlingAccessException("No url rule for " + url);
161             } else {
162                 responseData.setRuleId(rule.getRuleId());
163                 final ResponseProcessor responseProcessor = rule.getResponseProcessor();
164                 if (responseProcessor instanceof DefaultResponseProcessor) {
165                     final Transformer transformer = ((DefaultResponseProcessor) responseProcessor).getTransformer();
166                     final ResultData resultData = transformer.transform(responseData);
167                     final byte[] data = resultData.getData();
168                     if (data != null) {
169                         try {
170                             @SuppressWarnings("unchecked")
171                             final Map<String, Object> result = (Map<String, Object>) SerializeUtil.fromBinaryToObject(data);
172                             return result;
173                         } catch (final Exception e) {
174                             throw new CrawlerSystemException("Could not create an instance from bytes.", e);
175                         }
176                     }
177                 } else {
178                     throw new CrawlingAccessException("The response processor is not DefaultResponseProcessor. responseProcessor: "
179                             + responseProcessor + ", url: " + url);
180                 }
181             }
182             return null;
183         } catch (final Exception e) {
184             throw new CrawlingAccessException("Failed to parse " + url, e);
185         }
186     }
187 
188     public String decodeSimilarDocHash(final String hash) {
189         if (hash != null && hash.startsWith(SIMILAR_DOC_HASH_PREFIX) && hash.length() > SIMILAR_DOC_HASH_PREFIX.length()) {
190             final byte[] decode = Base64.getUrlDecoder().decode(hash.substring(SIMILAR_DOC_HASH_PREFIX.length()));
191             try (BufferedReader reader =
192                     new BufferedReader(new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(decode)), Constants.UTF_8))) {
193                 return ReaderUtil.readText(reader);
194             } catch (final IOException e) {
195                 if (logger.isDebugEnabled()) {
196                     logger.debug("Failed to decode " + hash, e);
197                 }
198             }
199         }
200         return hash;
201     }
202 
203     public String encodeSimilarDocHash(final String hash) {
204         if (hash != null && !hash.startsWith(SIMILAR_DOC_HASH_PREFIX)) {
205             try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
206                 try (GZIPOutputStream gos = new GZIPOutputStream(baos)) {
207                     gos.write(hash.getBytes(Constants.UTF_8));
208                 }
209                 return SIMILAR_DOC_HASH_PREFIX + Base64.getUrlEncoder().withoutPadding().encodeToString(baos.toByteArray());
210             } catch (final IOException e) {
211                 logger.warn("Failed to encode " + hash, e);
212             }
213         }
214         return hash;
215     }
216 
217 }