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 static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.UnsupportedEncodingException;
24  import java.net.InetAddress;
25  import java.net.URLEncoder;
26  import java.net.UnknownHostException;
27  import java.nio.file.Files;
28  import java.nio.file.Path;
29  import java.time.LocalDateTime;
30  import java.util.ArrayList;
31  import java.util.Date;
32  import java.util.HashMap;
33  import java.util.LinkedHashMap;
34  import java.util.List;
35  import java.util.Locale;
36  import java.util.Map;
37  import java.util.Properties;
38  import java.util.UUID;
39  import java.util.concurrent.ExecutionException;
40  import java.util.concurrent.TimeUnit;
41  import java.util.concurrent.atomic.AtomicBoolean;
42  import java.util.concurrent.atomic.AtomicInteger;
43  import java.util.regex.Pattern;
44  
45  import javax.annotation.PostConstruct;
46  import javax.annotation.PreDestroy;
47  import javax.servlet.ServletContext;
48  
49  import org.apache.commons.lang3.LocaleUtils;
50  import org.apache.commons.lang3.StringUtils;
51  import org.apache.logging.log4j.Level;
52  import org.apache.logging.log4j.core.config.Configurator;
53  import org.codelibs.core.lang.StringUtil;
54  import org.codelibs.core.misc.Pair;
55  import org.codelibs.fess.Constants;
56  import org.codelibs.fess.crawler.util.CharUtil;
57  import org.codelibs.fess.exception.FessSystemException;
58  import org.codelibs.fess.mylasta.action.FessMessages;
59  import org.codelibs.fess.mylasta.action.FessUserBean;
60  import org.codelibs.fess.mylasta.direction.FessConfig;
61  import org.codelibs.fess.util.ComponentUtil;
62  import org.codelibs.fess.util.GsaConfigParser;
63  import org.codelibs.fess.util.ResourceUtil;
64  import org.codelibs.fess.validation.FessActionValidator;
65  import org.lastaflute.core.message.supplier.UserMessagesCreator;
66  import org.lastaflute.web.TypicalAction;
67  import org.lastaflute.web.response.HtmlResponse;
68  import org.lastaflute.web.ruts.process.ActionRuntime;
69  import org.lastaflute.web.servlet.request.RequestManager;
70  import org.lastaflute.web.util.LaServletContextUtil;
71  import org.lastaflute.web.validation.ActionValidator;
72  import org.slf4j.Logger;
73  import org.slf4j.LoggerFactory;
74  
75  import com.google.common.cache.CacheBuilder;
76  import com.google.common.cache.CacheLoader;
77  import com.google.common.cache.LoadingCache;
78  import com.ibm.icu.util.ULocale;
79  
80  public class SystemHelper {
81  
82      private static final Logger logger = LoggerFactory.getLogger(SystemHelper.class);
83  
84      protected final Map<String, String> designJspFileNameMap = new LinkedHashMap<>();
85  
86      protected final AtomicBoolean forceStop = new AtomicBoolean(false);
87  
88      protected LoadingCache<String, List<Map<String, String>>> langItemsCache;
89  
90      protected String filterPathEncoding;
91  
92      protected String[] supportedLanguages;
93  
94      protected List<Runnable> shutdownHookList = new ArrayList<>();
95  
96      protected AtomicInteger previousClusterState = new AtomicInteger(0);
97  
98      protected String version;
99  
100     protected int majorVersion;
101 
102     protected int minorVersion;
103 
104     protected String productVersion;
105 
106     @PostConstruct
107     public void init() {
108         final FessConfig fessConfig = ComponentUtil.getFessConfig();
109         filterPathEncoding = fessConfig.getPathEncoding();
110         supportedLanguages = fessConfig.getSupportedLanguagesAsArray();
111         langItemsCache =
112                 CacheBuilder.newBuilder().maximumSize(20).expireAfterAccess(1, TimeUnit.HOURS)
113                         .build(new CacheLoader<String, List<Map<String, String>>>() {
114                             @Override
115                             public List<Map<String, String>> load(final String key) throws Exception {
116                                 final ULocale uLocale = new ULocale(key);
117                                 final Locale displayLocale = uLocale.toLocale();
118                                 final List<Map<String, String>> langItems = new ArrayList<>(supportedLanguages.length);
119                                 final String msg = ComponentUtil.getMessageManager().getMessage(displayLocale, "labels.allLanguages");
120                                 final Map<String, String> defaultMap = new HashMap<>(2);
121                                 defaultMap.put(Constants.ITEM_LABEL, msg);
122                                 defaultMap.put(Constants.ITEM_VALUE, "all");
123                                 langItems.add(defaultMap);
124 
125                                 for (final String lang : supportedLanguages) {
126                                     final Locale locale = LocaleUtils.toLocale(lang);
127                                     final String label = locale.getDisplayName(displayLocale);
128                                     final Map<String, String> map = new HashMap<>(2);
129                                     map.put(Constants.ITEM_LABEL, label);
130                                     map.put(Constants.ITEM_VALUE, lang);
131                                     langItems.add(map);
132                                 }
133                                 return langItems;
134                             }
135                         });
136 
137         ComponentUtil.doInitProcesses(p -> p.run());
138 
139         parseProjectProperties();
140     }
141 
142     protected void parseProjectProperties() {
143         final Path propPath = ResourceUtil.getProjectPropertiesFile();
144         try (final InputStream in = Files.newInputStream(propPath)) {
145             final Properties prop = new Properties();
146             prop.load(in);
147             version = prop.getProperty("fess.version", "0.0.0");
148             final String[] values = version.split("\\.");
149             majorVersion = Integer.parseInt(values[0]);
150             minorVersion = Integer.parseInt(values[1]);
151             productVersion = majorVersion + "." + minorVersion;
152             System.setProperty("fess.version", version);
153             System.setProperty("fess.product.version", productVersion);
154         } catch (final Exception e) {
155             throw new FessSystemException("Failed to parse project.properties.", e);
156         }
157     }
158 
159     @PreDestroy
160     public void destroy() {
161         shutdownHookList.forEach(action -> {
162             try {
163                 action.run();
164             } catch (final Exception e) {
165                 logger.warn("Failed to process shutdown task.", e);
166             }
167         });
168     }
169 
170     public String getUsername() {
171         final RequestManager requestManager = ComponentUtil.getRequestManager();
172         return requestManager.findUserBean(FessUserBean.class).map(user -> {
173             return user.getUserId();
174         }).orElse(Constants.GUEST_USER);
175     }
176 
177     public Date getCurrentTime() {
178         return new Date();
179     }
180 
181     public long getCurrentTimeAsLong() {
182         return System.currentTimeMillis();
183     }
184 
185     public LocalDateTime getCurrentTimeAsLocalDateTime() {
186         return LocalDateTime.now();
187     }
188 
189     public String getLogFilePath() {
190         final String value = System.getProperty("fess.log.path");
191         if (value != null) {
192             return value;
193         } else {
194             final String userDir = System.getProperty("user.dir");
195             final File targetDir = new File(userDir, "target");
196             return new File(targetDir, "logs").getAbsolutePath();
197         }
198     }
199 
200     public String encodeUrlFilter(final String path) {
201         if (filterPathEncoding == null || path == null) {
202             return path;
203         }
204 
205         try {
206             final StringBuilder buf = new StringBuilder(path.length() + 100);
207             for (int i = 0; i < path.length(); i++) {
208                 final char c = path.charAt(i);
209                 if (CharUtil.isUrlChar(c) || c == '^' || c == '{' || c == '}' || c == '|' || c == '\\') {
210                     buf.append(c);
211                 } else {
212                     buf.append(URLEncoder.encode(String.valueOf(c), filterPathEncoding));
213                 }
214             }
215             return buf.toString();
216         } catch (final UnsupportedEncodingException e) {
217             return path;
218         }
219     }
220 
221     public String normalizeConfigPath(final String path) {
222 
223         if (StringUtil.isBlank(path)) {
224             return StringUtils.EMPTY;
225         }
226 
227         final String p = path.trim();
228         if (p.startsWith("#")) {
229             return StringUtils.EMPTY;
230         }
231 
232         if (p.startsWith(GsaConfigParser.CONTAINS)) {
233             return ".*" + Pattern.quote(p.substring(GsaConfigParser.CONTAINS.length())) + ".*";
234         }
235 
236         if (p.startsWith(GsaConfigParser.REGEXP)) {
237             return p.substring(GsaConfigParser.REGEXP.length());
238         }
239 
240         if (p.startsWith(GsaConfigParser.REGEXP_CASE)) {
241             return p.substring(GsaConfigParser.REGEXP_CASE.length());
242         }
243 
244         if (p.startsWith(GsaConfigParser.REGEXP_IGNORE_CASE)) {
245             return "(?i)" + p.substring(GsaConfigParser.REGEXP_IGNORE_CASE.length());
246         }
247 
248         return p;
249     }
250 
251     public String getHelpLink(final String name) {
252         final String url = ComponentUtil.getFessConfig().getOnlineHelpBaseLink() + name + "-guide.html";
253         return getHelpUrl(url);
254     }
255 
256     protected String getHelpUrl(final String url) {
257         final Locale locale = ComponentUtil.getRequestManager().getUserLocale();
258         if (locale != null) {
259             final String lang = locale.getLanguage();
260             if (ComponentUtil.getFessConfig().isOnlineHelpSupportedLang(lang)) {
261                 return url.replaceFirst("\\{lang\\}", lang).replaceFirst("\\{version\\}", majorVersion + "." + minorVersion);
262             }
263         }
264         return getDefaultHelpLink(url);
265     }
266 
267     protected String getDefaultHelpLink(final String url) {
268         return url.replaceFirst("/\\{lang\\}/", "/").replaceFirst("\\{version\\}", majorVersion + "." + minorVersion);
269     }
270 
271     public void addDesignJspFileName(final String key, final String value) {
272         designJspFileNameMap.put(key, value);
273     }
274 
275     public String getDesignJspFileName(final String fileName) {
276         return designJspFileNameMap.get(fileName);
277     }
278 
279     @SuppressWarnings("unchecked")
280     public Pair<String, String>[] getDesignJspFileNames() {
281         return designJspFileNameMap.entrySet().stream().map(e -> new Pair<>(e.getKey(), e.getValue())).toArray(n -> new Pair[n]);
282     }
283 
284     public void refreshDesignJspFiles() {
285         final ServletContext servletContext = LaServletContextUtil.getServletContext();
286         stream(ComponentUtil.getVirtualHostHelper().getVirtualHostPaths()).of(
287                 stream -> stream.filter(s -> s != null && !s.equals("/")).forEach(
288                         key -> {
289                             designJspFileNameMap
290                                     .entrySet()
291                                     .stream()
292                                     .forEach(
293                                             e -> {
294                                                 final File jspFile =
295                                                         new File(servletContext.getRealPath("/WEB-INF/view" + key + "/" + e.getValue()));
296                                                 if (!jspFile.exists()) {
297                                                     jspFile.getParentFile().mkdirs();
298                                                     final File baseJspFile =
299                                                             new File(servletContext.getRealPath("/WEB-INF/view/" + e.getValue()));
300                                                     try {
301                                                         Files.copy(baseJspFile.toPath(), jspFile.toPath());
302                                                     } catch (final IOException ex) {
303                                                         logger.warn("Could not copy from " + baseJspFile.getAbsolutePath() + " to "
304                                                                 + jspFile.getAbsolutePath(), ex);
305                                                     }
306                                                 }
307                                             });
308                         }));
309     }
310 
311     public boolean isForceStop() {
312         return forceStop.get();
313     }
314 
315     public void setForceStop(final boolean b) {
316         forceStop.set(true);
317     }
318 
319     public String generateDocId(final Map<String, Object> map) {
320         return UUID.randomUUID().toString().replace("-", StringUtil.EMPTY);
321     }
322 
323     public String abbreviateLongText(final String str) {
324         return StringUtils.abbreviate(str, ComponentUtil.getFessConfig().getMaxLogOutputLengthAsInteger().intValue());
325     }
326 
327     public String normalizeHtmlLang(final String value) {
328         final String defaultLang = ComponentUtil.getFessConfig().getCrawlerDocumentHtmlDefaultLang();
329         if (StringUtil.isNotBlank(defaultLang)) {
330             return defaultLang;
331         }
332 
333         return normalizeLang(value);
334     }
335 
336     public String normalizeLang(final String value) {
337         if (StringUtil.isBlank(value)) {
338             return null;
339         }
340 
341         final String localeName = value.trim().toLowerCase(Locale.ENGLISH).replace("-", "_");
342 
343         for (final String supportedLang : supportedLanguages) {
344             if (localeName.startsWith(supportedLang.toLowerCase(Locale.ENGLISH))) {
345                 return supportedLang;
346             }
347         }
348         return null;
349     }
350 
351     public List<Map<String, String>> getLanguageItems(final Locale locale) {
352         try {
353             final String localeStr = locale.toString();
354             return langItemsCache.get(localeStr);
355         } catch (final ExecutionException e) {
356             final List<Map<String, String>> langItems = new ArrayList<>(supportedLanguages.length);
357             final String msg = ComponentUtil.getMessageManager().getMessage(locale, "labels.allLanguages");
358             final Map<String, String> defaultMap = new HashMap<>(2);
359             defaultMap.put(Constants.ITEM_LABEL, msg);
360             defaultMap.put(Constants.ITEM_VALUE, "all");
361             langItems.add(defaultMap);
362             return langItems;
363         }
364     }
365 
366     public void sleep(final int sec) {
367         try {
368             Thread.sleep(sec * 1000L);
369         } catch (final InterruptedException e) {
370             if (logger.isDebugEnabled()) {
371                 logger.debug("Interrupted.", e);
372             }
373         }
374     }
375 
376     public void addShutdownHook(final Runnable hook) {
377         shutdownHookList.add(hook);
378     }
379 
380     public String getHostname() {
381         final Map<String, String> env = System.getenv();
382         if (env.containsKey("COMPUTERNAME")) {
383             return env.get("COMPUTERNAME");
384         } else if (env.containsKey("HOSTNAME")) {
385             return env.get("HOSTNAME");
386         }
387         try {
388             return InetAddress.getLocalHost().getHostAddress();
389         } catch (final UnknownHostException e) {
390             logger.debug("Unknown hostname.", e);
391         }
392         return "Unknown";
393     }
394 
395     public void setupAdminHtmlData(final TypicalAction action, final ActionRuntime runtime) {
396         runtime.registerData("developmentMode", ComponentUtil.getFessEsClient().isEmbedded());
397         final String url = ComponentUtil.getFessConfig().getOnlineHelpInstallation();
398         runtime.registerData("installationLink", getHelpUrl(url));
399     }
400 
401     public String getSearchRoleByUser(final String name) {
402         return createSearchRole(ComponentUtil.getFessConfig().getRoleSearchUserPrefix(), name);
403     }
404 
405     public String getSearchRoleByGroup(final String name) {
406         return createSearchRole(ComponentUtil.getFessConfig().getRoleSearchGroupPrefix(), name);
407     }
408 
409     public String getSearchRoleByRole(final String name) {
410         return createSearchRole(ComponentUtil.getFessConfig().getRoleSearchRolePrefix(), name);
411     }
412 
413     protected String createSearchRole(final String type, final String name) {
414         final String value = type + ComponentUtil.getFessConfig().getCanonicalLdapName(name);
415         if (logger.isDebugEnabled()) {
416             logger.debug("Search Role: " + type + ":" + name + "=" + value);
417         }
418         return value;
419     }
420 
421     public void reloadConfiguration() {
422         ComponentUtil.getFessEsClient().refresh();
423         ComponentUtil.getLabelTypeHelper().init();
424         ComponentUtil.getPathMappingHelper().init();
425         ComponentUtil.getSuggestHelper().init();
426         ComponentUtil.getPopularWordHelper().init();
427         ComponentUtil.getJobManager().reboot();
428         ComponentUtil.getLdapManager().updateConfig();
429         ComponentUtil.getRelatedContentHelper().update();
430         ComponentUtil.getRelatedQueryHelper().update();
431         ComponentUtil.getKeyMatchHelper().update();
432     }
433 
434     public String updateConfiguration() {
435         final StringBuilder buf = new StringBuilder();
436         buf.append("Label: ").append(ComponentUtil.getLabelTypeHelper().update()).append("\n");
437         buf.append("PathMapping: ").append(ComponentUtil.getPathMappingHelper().update()).append("\n");
438         buf.append("RelatedContent: ").append(ComponentUtil.getRelatedContentHelper().update()).append("\n");
439         buf.append("RelatedQuery: ").append(ComponentUtil.getRelatedQueryHelper().update()).append("\n");
440         return buf.toString();
441     }
442 
443     public boolean isChangedClusterState(final int status) {
444         return previousClusterState.getAndSet(status) != status;
445     }
446 
447     public ActionValidator<FessMessages> createValidator(final RequestManager requestManager,
448             final UserMessagesCreator<FessMessages> messagesCreator, final Class<?>[] runtimeGroups) {
449         return new FessActionValidator<>(requestManager, messagesCreator, runtimeGroups);
450     }
451 
452     public HtmlResponse getRedirectResponseToLogin(final HtmlResponse response) {
453         return response;
454     }
455 
456     public HtmlResponse getRedirectResponseToRoot(final HtmlResponse response) {
457         return response;
458     }
459 
460     public void setLogLevel(final String level) {
461         final Level logLevel = Level.toLevel(level, Level.WARN);
462         System.setProperty(Constants.FESS_LOG_LEVEL, logLevel.toString());
463         Configurator.setLevel("org.codelibs.fess", logLevel);
464         Configurator.setLevel("org.dbflute", logLevel);
465         Configurator.setLevel("org.lastaflute", logLevel);
466     }
467 
468     public String getLogLevel() {
469         return System.getProperty(Constants.FESS_LOG_LEVEL, Level.WARN.toString());
470     }
471 
472     public String getVersion() {
473         return version;
474     }
475 
476     public int getMajorVersion() {
477         return majorVersion;
478     }
479 
480     public int getMinorVersion() {
481         return minorVersion;
482     }
483 
484     public String getProductVersion() {
485         return productVersion;
486     }
487 
488 }