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.util;
17  
18  import static org.codelibs.core.stream.StreamUtil.split;
19  
20  import java.util.ArrayList;
21  import java.util.Arrays;
22  import java.util.HashMap;
23  import java.util.LinkedList;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.regex.Pattern;
27  import java.util.stream.Collectors;
28  
29  import javax.xml.XMLConstants;
30  import javax.xml.parsers.SAXParser;
31  import javax.xml.parsers.SAXParserFactory;
32  
33  import org.codelibs.core.lang.StringUtil;
34  import org.codelibs.fess.Constants;
35  import org.codelibs.fess.es.config.exentity.FileConfig;
36  import org.codelibs.fess.es.config.exentity.LabelType;
37  import org.codelibs.fess.es.config.exentity.WebConfig;
38  import org.codelibs.fess.exception.GsaConfigException;
39  import org.dbflute.optional.OptionalEntity;
40  import org.slf4j.Logger;
41  import org.slf4j.LoggerFactory;
42  import org.xml.sax.Attributes;
43  import org.xml.sax.InputSource;
44  import org.xml.sax.SAXException;
45  import org.xml.sax.helpers.DefaultHandler;
46  
47  public class GsaConfigParser extends DefaultHandler {
48  
49      private static final Logger logger = LoggerFactory.getLogger(GsaConfigParser.class);
50  
51      public static final String REGEXP = "regexp:";
52  
53      public static final String REGEXP_CASE = "regexpCase:";
54  
55      public static final String REGEXP_IGNORE_CASE = "regexpIgnoreCase:";
56  
57      public static final String CONTAINS = "contains:";
58  
59      protected static final String COLLECTIONS = "collections";
60  
61      protected static final String COLLECTION = "collection";
62  
63      protected static final String GLOBALPARAMS = "globalparams";
64  
65      protected static final String START_URLS = "start_urls";
66  
67      protected static final String GOOD_URLS = "good_urls";
68  
69      protected static final String BAD_URLS = "bad_urls";
70  
71      protected String[] webProtocols = new String[] { "http:", "https:" };
72  
73      protected String[] fileProtocols = new String[] { "file:", "smb:", "smb1:", "ftp:" };
74  
75      protected LinkedList<String> tagQueue;
76  
77      protected List<LabelType> labelList;
78  
79      protected LabelType labelType;
80  
81      protected Map<String, String> globalParams = new HashMap<>();
82  
83      protected WebConfig webConfig = null;
84  
85      protected FileConfig fileConfig = null;
86  
87      protected StringBuilder textBuf = new StringBuilder(1000);
88  
89      protected String userAgent = "gsa-crawler";
90  
91      public void parse(final InputSource is) {
92          try {
93              final SAXParserFactory factory = SAXParserFactory.newInstance();
94              factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
95              final SAXParser parser = factory.newSAXParser();
96              parser.parse(is, this);
97          } catch (final Exception e) {
98              throw new GsaConfigException("Failed to parse XML file.", e);
99          }
100     }
101 
102     @Override
103     public void startDocument() throws SAXException {
104         tagQueue = new LinkedList<>();
105         labelList = new ArrayList<>();
106         labelType = null;
107     }
108 
109     @Override
110     public void endDocument() throws SAXException {
111         globalParams.clear();
112         tagQueue.clear();
113     }
114 
115     @Override
116     public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
117         if (logger.isDebugEnabled()) {
118             logger.debug("Start Element: " + qName);
119         }
120         if (tagQueue.isEmpty() && !"eef".equalsIgnoreCase(qName)) {
121             throw new GsaConfigException("Invalid format.");
122         } else if (COLLECTION.equalsIgnoreCase(qName) && COLLECTIONS.equalsIgnoreCase(tagQueue.peekLast())) {
123             final long now = System.currentTimeMillis();
124             final String name = attributes.getValue("Name");
125             labelType = new LabelType();
126             labelType.setName(name);
127             labelType.setValue(name);
128             labelType.setPermissions(new String[] { "Rguest" });
129             labelType.setCreatedBy(Constants.SYSTEM_USER);
130             labelType.setCreatedTime(now);
131             labelType.setUpdatedBy(Constants.SYSTEM_USER);
132             labelType.setUpdatedTime(now);
133         }
134         tagQueue.offer(qName);
135     }
136 
137     @Override
138     public void endElement(final String uri, final String localName, final String qName) throws SAXException {
139         if (logger.isDebugEnabled()) {
140             logger.debug("End Element: " + qName);
141         }
142         if (GOOD_URLS.equalsIgnoreCase(qName)) {
143             if (labelType != null) {
144                 labelType.setIncludedPaths(parseFilterPaths(textBuf.toString(), true, true));
145             } else if (GLOBALPARAMS.equalsIgnoreCase(tagQueue.get(tagQueue.size() - 2))) {
146                 globalParams.put(GOOD_URLS, textBuf.toString());
147             }
148         } else if (BAD_URLS.equalsIgnoreCase(qName)) {
149             if (labelType != null) {
150                 labelType.setExcludedPaths(parseFilterPaths(textBuf.toString(), true, true));
151             } else if (GLOBALPARAMS.equalsIgnoreCase(tagQueue.get(tagQueue.size() - 2))) {
152                 globalParams.put(BAD_URLS, textBuf.toString());
153             }
154         } else if (START_URLS.equalsIgnoreCase(qName) && GLOBALPARAMS.equalsIgnoreCase(tagQueue.get(tagQueue.size() - 2))) {
155             globalParams.put(START_URLS, textBuf.toString());
156         } else if (labelType != null && COLLECTION.equalsIgnoreCase(qName)) {
157             labelList.add(labelType);
158             labelType = null;
159         } else if (GLOBALPARAMS.equalsIgnoreCase(qName)) {
160             final Object startUrls = globalParams.get(START_URLS);
161             if (startUrls != null) {
162                 final long now = System.currentTimeMillis();
163                 final List<String> urlList =
164                         split(startUrls.toString(), "\n").get(
165                                 stream -> stream.map(String::trim).filter(StringUtil::isNotBlank).collect(Collectors.toList()));
166 
167                 final String webUrls =
168                         urlList.stream().filter(s -> Arrays.stream(webProtocols).anyMatch(p -> s.startsWith(p)))
169                                 .collect(Collectors.joining("\n"));
170                 if (StringUtil.isNotBlank(webUrls)) {
171                     webConfig = new WebConfig();
172                     webConfig.setName("Default");
173                     webConfig.setAvailable(true);
174                     webConfig.setBoost(1.0f);
175                     webConfig.setConfigParameter(StringUtil.EMPTY);
176                     webConfig.setIntervalTime(1000);
177                     webConfig.setNumOfThread(3);
178                     webConfig.setSortOrder(1);
179                     webConfig.setUrls(webUrls);
180                     webConfig.setIncludedUrls(parseFilterPaths(globalParams.get(GOOD_URLS), true, false));
181                     webConfig.setIncludedDocUrls(StringUtil.EMPTY);
182                     webConfig.setExcludedUrls(parseFilterPaths(globalParams.get(BAD_URLS), true, false));
183                     webConfig.setExcludedDocUrls(StringUtil.EMPTY);
184                     webConfig.setUserAgent(userAgent);
185                     webConfig.setPermissions(new String[] { "Rguest" });
186                     webConfig.setCreatedBy(Constants.SYSTEM_USER);
187                     webConfig.setCreatedTime(now);
188                     webConfig.setUpdatedBy(Constants.SYSTEM_USER);
189                     webConfig.setUpdatedTime(now);
190                 }
191 
192                 final String fileUrls =
193                         urlList.stream().filter(s -> Arrays.stream(fileProtocols).anyMatch(p -> s.startsWith(p)))
194                                 .collect(Collectors.joining("\n"));
195                 if (StringUtil.isNotBlank(fileUrls)) {
196                     fileConfig = new FileConfig();
197                     fileConfig.setName("Default");
198                     fileConfig.setAvailable(true);
199                     fileConfig.setBoost(1.0f);
200                     fileConfig.setConfigParameter(StringUtil.EMPTY);
201                     fileConfig.setIntervalTime(0);
202                     fileConfig.setNumOfThread(5);
203                     fileConfig.setSortOrder(2);
204                     fileConfig.setPaths(fileUrls);
205                     fileConfig.setIncludedPaths(parseFilterPaths(globalParams.get(GOOD_URLS), false, true));
206                     fileConfig.setIncludedDocPaths(StringUtil.EMPTY);
207                     fileConfig.setExcludedPaths(parseFilterPaths(globalParams.get(BAD_URLS), false, true));
208                     fileConfig.setExcludedDocPaths(StringUtil.EMPTY);
209                     fileConfig.setPermissions(new String[] { "Rguest" });
210                     fileConfig.setCreatedBy(Constants.SYSTEM_USER);
211                     fileConfig.setCreatedTime(now);
212                     fileConfig.setUpdatedBy(Constants.SYSTEM_USER);
213                     fileConfig.setUpdatedTime(now);
214                 }
215             }
216         } else if ("user_agent".equalsIgnoreCase(qName) && GLOBALPARAMS.equalsIgnoreCase(tagQueue.get(tagQueue.size() - 2))) {
217             userAgent = textBuf.toString().trim();
218         }
219         tagQueue.pollLast();
220         textBuf.setLength(0);
221     }
222 
223     @Override
224     public void characters(final char[] ch, final int start, final int length) throws SAXException {
225         final String text = new String(ch, start, length);
226         if (logger.isDebugEnabled()) {
227             logger.debug("Text: " + text);
228         }
229         textBuf.append(text);
230     }
231 
232     protected String parseFilterPaths(final String text, final boolean web, final boolean file) {
233         return split(text, "\n").get(stream -> stream.map(String::trim).filter(StringUtil::isNotBlank).map(s -> {
234             return getFilterPath(s);
235         }).filter(s -> {
236             if (StringUtil.isBlank(s)) {
237                 return false;
238             }
239             if (Arrays.stream(webProtocols).anyMatch(p -> s.startsWith(p))) {
240                 return web;
241             }
242             if (Arrays.stream(fileProtocols).anyMatch(p -> s.startsWith(p))) {
243                 return file;
244             }
245             return true;
246         }).collect(Collectors.joining("\n")));
247     }
248 
249     protected String getFilterPath(final String s) {
250         if (s.startsWith("#")) {
251             return StringUtil.EMPTY;
252         } else if (s.startsWith(CONTAINS)) {
253             final String v = s.substring(CONTAINS.length());
254             final StringBuilder buf = new StringBuilder(100);
255             return ".*" + appendFileterPath(buf, escape(v)) + ".*";
256         } else if (s.startsWith(REGEXP_IGNORE_CASE)) {
257             final String v = s.substring(REGEXP_IGNORE_CASE.length());
258             final StringBuilder buf = new StringBuilder(100);
259             buf.append("(?i)");
260             return appendFileterPath(buf, unescape(v));
261         } else if (s.startsWith(REGEXP_CASE)) {
262             final String v = s.substring(REGEXP_CASE.length());
263             final StringBuilder buf = new StringBuilder(100);
264             return appendFileterPath(buf, unescape(v));
265         } else if (s.startsWith(REGEXP)) {
266             final String v = s.substring(REGEXP.length());
267             final StringBuilder buf = new StringBuilder(100);
268             return appendFileterPath(buf, unescape(v));
269         } else if (Arrays.stream(webProtocols).anyMatch(p -> s.startsWith(p))) {
270             return escape(s) + ".*";
271         } else if (Arrays.stream(fileProtocols).anyMatch(p -> s.startsWith(p))) {
272             return escape(s) + ".*";
273         } else {
274             final StringBuilder buf = new StringBuilder(100);
275             return appendFileterPath(buf, escape(s));
276         }
277     }
278 
279     protected String escape(final String s) {
280         if (s.startsWith("#")) {
281             return StringUtil.EMPTY;
282         } else if (s.startsWith("^") && s.endsWith("$")) {
283             return "^" + Pattern.quote(s.substring(1, s.length() - 1)) + "$";
284         } else if (s.startsWith("^")) {
285             return "^" + Pattern.quote(s.substring(1));
286         } else if (s.endsWith("$")) {
287             return Pattern.quote(s.substring(0, s.length() - 1)) + "$";
288         }
289         return Pattern.quote(s);
290     }
291 
292     protected String unescape(final String s) {
293         return s.replace("\\\\", "\\");
294     }
295 
296     protected String appendFileterPath(final StringBuilder buf, final String v) {
297         if (StringUtil.isBlank(v)) {
298             return StringUtil.EMPTY;
299         }
300 
301         if (v.startsWith("^")) {
302             buf.append(v);
303             if (!v.endsWith("$")) {
304                 buf.append(".*");
305             }
306         } else if (v.endsWith("$")) {
307             buf.append(".*");
308             buf.append(v);
309         } else if (v.endsWith("/\\E")) {
310             buf.append(".*");
311             buf.append(v);
312             buf.append(".*");
313         } else {
314             buf.append(v);
315         }
316         return buf.toString();
317     }
318 
319     public void setWebProtocols(final String[] webProtocols) {
320         this.webProtocols = webProtocols;
321     }
322 
323     public void setFileProtocols(final String[] fileProtocols) {
324         this.fileProtocols = fileProtocols;
325     }
326 
327     @Override
328     public String toString() {
329         return "GsaConfigParser [labelList=" + labelList + ", webConfig=" + webConfig + ", fileConfig=" + fileConfig + "]";
330     }
331 
332     public OptionalEntity<WebConfig> getWebConfig() {
333         return OptionalUtil.ofNullable(webConfig);
334     }
335 
336     public OptionalEntity<FileConfig> getFileConfig() {
337         return OptionalUtil.ofNullable(fileConfig);
338     }
339 
340     public LabelType[] getLabelTypes() {
341         return labelList.toArray(new LabelType[labelList.size()]);
342     }
343 
344 }