1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.codelibs.fess.helper;
17
18 import java.io.UnsupportedEncodingException;
19 import java.net.URLEncoder;
20 import java.util.ArrayList;
21 import java.util.Base64;
22 import java.util.Collections;
23 import java.util.Date;
24 import java.util.HashMap;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import org.codelibs.core.lang.StringUtil;
30 import org.codelibs.core.security.MessageDigestUtil;
31 import org.codelibs.fess.Constants;
32 import org.codelibs.fess.app.service.CrawlingInfoService;
33 import org.codelibs.fess.es.client.FessEsClient;
34 import org.codelibs.fess.es.config.exentity.CrawlingConfig;
35 import org.codelibs.fess.es.config.exentity.CrawlingInfo;
36 import org.codelibs.fess.es.config.exentity.CrawlingInfoParam;
37 import org.codelibs.fess.exception.FessSystemException;
38 import org.codelibs.fess.mylasta.direction.FessConfig;
39 import org.codelibs.fess.util.ComponentUtil;
40 import org.elasticsearch.index.query.QueryBuilders;
41 import org.elasticsearch.search.aggregations.AggregationBuilders;
42 import org.elasticsearch.search.aggregations.BucketOrder;
43 import org.elasticsearch.search.aggregations.bucket.terms.Terms;
44 import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
45 import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class CrawlingInfoHelper {
50 private static final Logger logger = LoggerFactory.getLogger(CrawlingInfoHelper.class);
51
52 public static final String FACET_COUNT_KEY = "count";
53
54 protected Map<String, String> infoMap;
55
56 protected Long documentExpires;
57
58 protected int maxSessionIdsInList;
59
60 protected CrawlingInfoService getCrawlingInfoService() {
61 return ComponentUtil.getComponent(CrawlingInfoService.class);
62 }
63
64 public String getCanonicalSessionId(final String sessionId) {
65 final int idx = sessionId.indexOf('-');
66 if (idx >= 0) {
67 return sessionId.substring(0, idx);
68 }
69 return sessionId;
70 }
71
72 public synchronized void store(final String sessionId, final boolean create) {
73 CrawlingInfo crawlingInfo = create ? null : getCrawlingInfoService().getLast(sessionId);
74 if (crawlingInfo == null) {
75 crawlingInfo = new CrawlingInfo(sessionId);
76 try {
77 getCrawlingInfoService().store(crawlingInfo);
78 } catch (final Exception e) {
79 throw new FessSystemException("No crawling session.", e);
80 }
81 }
82
83 if (infoMap != null) {
84 final List<CrawlingInfoParam> crawlingInfoParamList = new ArrayList<>();
85 for (final Map.Entry<String, String> entry : infoMap.entrySet()) {
86 final CrawlingInfoParamaram.html#CrawlingInfoParam">CrawlingInfoParam crawlingInfoParam = new CrawlingInfoParam();
87 crawlingInfoParam.setCrawlingInfoId(crawlingInfo.getId());
88 crawlingInfoParam.setKey(entry.getKey());
89 crawlingInfoParam.setValue(entry.getValue());
90 crawlingInfoParamList.add(crawlingInfoParam);
91 }
92 getCrawlingInfoService().storeInfo(crawlingInfoParamList);
93 }
94
95 infoMap = null;
96 }
97
98 public synchronized void putToInfoMap(final String key, final String value) {
99 if (infoMap == null) {
100 infoMap = Collections.synchronizedMap(new LinkedHashMap<String, String>());
101 }
102 logger.debug("infoMap: {}={} => {}", key, value, infoMap);
103 infoMap.put(key, value);
104 }
105
106 public void updateParams(final String sessionId, final String name, final int dayForCleanup) {
107 final CrawlingInfo crawlingInfo = getCrawlingInfoService().getLast(sessionId);
108 if (crawlingInfo == null) {
109 logger.warn("No crawling session: " + sessionId);
110 return;
111 }
112 if (StringUtil.isNotBlank(name)) {
113 crawlingInfo.setName(name);
114 } else {
115 crawlingInfo.setName(Constants.CRAWLING_INFO_SYSTEM_NAME);
116 }
117 if (dayForCleanup >= 0) {
118 final long expires = getExpiredTime(dayForCleanup);
119 crawlingInfo.setExpiredTime(expires);
120 documentExpires = expires;
121 }
122 try {
123 getCrawlingInfoService().store(crawlingInfo);
124 } catch (final Exception e) {
125 throw new FessSystemException("No crawling session.", e);
126 }
127
128 }
129
130 public Date getDocumentExpires(final CrawlingConfig config) {
131 if (config != null) {
132 final Integer timeToLive = config.getTimeToLive();
133 if (timeToLive != null) {
134
135 final long now = ComponentUtil.getSystemHelper().getCurrentTimeAsLong();
136 return new Date(now + timeToLive.longValue() * 1000 * 60);
137 }
138 }
139 return documentExpires != null ? new Date(documentExpires) : null;
140 }
141
142 protected long getExpiredTime(final int days) {
143 final long now = ComponentUtil.getSystemHelper().getCurrentTimeAsLong();
144 return now + days * Constants.ONE_DAY_IN_MILLIS;
145 }
146
147 public Map<String, String> getInfoMap(final String sessionId) {
148 final List<CrawlingInfoParam> crawlingInfoParamList = getCrawlingInfoService().getLastCrawlingInfoParamList(sessionId);
149 final Map<String, String> map = new HashMap<>();
150 for (final CrawlingInfoParam crawlingInfoParam : crawlingInfoParamList) {
151 map.put(crawlingInfoParam.getKey(), crawlingInfoParam.getValue());
152 }
153 return map;
154 }
155
156 public String generateId(final Map<String, Object> dataMap) {
157 final FessConfig fessConfig = ComponentUtil.getFessConfig();
158 final String url = (String) dataMap.get(fessConfig.getIndexFieldUrl());
159 final StringBuilder buf = new StringBuilder(1000);
160
161 @SuppressWarnings("unchecked")
162 final List<String> roleTypeList = (List<String>) dataMap.get(fessConfig.getIndexFieldRole());
163 buf.append(url);
164 if (roleTypeList != null && !roleTypeList.isEmpty()) {
165 Collections.sort(roleTypeList);
166 buf.append(";r=");
167 buf.append(String.join(",", roleTypeList));
168 }
169
170 @SuppressWarnings("unchecked")
171 final List<String> virtualHostList = (List<String>) dataMap.get(fessConfig.getIndexFieldVirtualHost());
172 if (virtualHostList != null && !virtualHostList.isEmpty()) {
173 Collections.sort(virtualHostList);
174 buf.append(";v=");
175 buf.append(String.join(",", virtualHostList));
176 }
177
178 final String urlId = buf.toString().trim();
179 return generateId(urlId);
180 }
181
182 public List<Map<String, String>> getSessionIdList(final FessEsClient fessEsClient) {
183 final FessConfig fessConfig = ComponentUtil.getFessConfig();
184 return fessEsClient.search(
185 fessConfig.getIndexDocumentSearchIndex(),
186 queryRequestBuilder -> {
187 queryRequestBuilder.setQuery(QueryBuilders.matchAllQuery());
188 final TermsAggregationBuilder termsBuilder =
189 AggregationBuilders.terms(fessConfig.getIndexFieldSegment()).field(fessConfig.getIndexFieldSegment())
190 .size(maxSessionIdsInList).order(BucketOrder.key(false));
191 queryRequestBuilder.addAggregation(termsBuilder);
192 queryRequestBuilder.setPreference(Constants.SEARCH_PREFERENCE_LOCAL);
193 return true;
194 }, (queryRequestBuilder, execTime, searchResponse) -> {
195 final List<Map<String, String>> sessionIdList = new ArrayList<>();
196 searchResponse.ifPresent(response -> {
197 final Terms terms = response.getAggregations().get(fessConfig.getIndexFieldSegment());
198 for (final Bucket bucket : terms.getBuckets()) {
199 final Map<String, String> map = new HashMap<>(2);
200 map.put(fessConfig.getIndexFieldSegment(), bucket.getKey().toString());
201 map.put(FACET_COUNT_KEY, Long.toString(bucket.getDocCount()));
202 sessionIdList.add(map);
203 }
204 });
205 return sessionIdList;
206 });
207 }
208
209 protected String generateId(final String urlId) {
210 final StringBuilder encodedBuf = new StringBuilder(urlId.length() + 100);
211 for (int i = 0; i < urlId.length(); i++) {
212 final char c = urlId.charAt(i);
213 if (c >= 'a' && c <= 'z'
214 || c >= 'A' && c <= 'Z'
215 || c >= '0' && c <= '9'
216 || c == '.'
217 || c == '-'
218 || c == '*'
219 || c == '_'
220 || c == ':'
221 || c == '+'
222 || c == '%'
223 || c == '='
224 || c == '&'
225 || c == '?'
226 || c == '#'
227 || c == '['
228 || c == ']'
229 || c == '@'
230 || c == '~'
231 || c == '!'
232 || c == '$'
233 || c == '\''
234 || c == '('
235 || c == ')'
236 || c == ','
237 || c == ';'
238 ) {
239 encodedBuf.append(c);
240 } else {
241 try {
242 final String target = String.valueOf(c);
243 final String converted = URLEncoder.encode(target, Constants.UTF_8);
244 if (target.equals(converted)) {
245 encodedBuf.append(Base64.getUrlEncoder().encodeToString(target.getBytes(Constants.CHARSET_UTF_8)));
246 } else {
247 encodedBuf.append(converted);
248 }
249 } catch (final UnsupportedEncodingException e) {
250
251 }
252 }
253 }
254
255 final String id = encodedBuf.toString();
256 return MessageDigestUtil.digest(ComponentUtil.getFessConfig().getIndexIdDigestAlgorithm(), id);
257 }
258
259 public void setMaxSessionIdsInList(final int maxSessionIdsInList) {
260 this.maxSessionIdsInList = maxSessionIdsInList;
261 }
262 }