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.taglib;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  
20  import java.io.File;
21  import java.math.RoundingMode;
22  import java.nio.file.Files;
23  import java.nio.file.Path;
24  import java.nio.file.Paths;
25  import java.text.DecimalFormat;
26  import java.text.NumberFormat;
27  import java.text.SimpleDateFormat;
28  import java.time.LocalDateTime;
29  import java.time.format.DateTimeFormatter;
30  import java.util.Base64;
31  import java.util.Calendar;
32  import java.util.Date;
33  import java.util.Enumeration;
34  import java.util.List;
35  import java.util.Locale;
36  import java.util.Map;
37  import java.util.Objects;
38  import java.util.concurrent.ExecutionException;
39  import java.util.concurrent.TimeUnit;
40  import java.util.stream.Collectors;
41  
42  import javax.servlet.http.HttpServletRequest;
43  
44  import org.apache.commons.text.StringEscapeUtils;
45  import org.apache.pdfbox.util.DateConverter;
46  import org.codelibs.core.lang.StringUtil;
47  import org.codelibs.fess.Constants;
48  import org.codelibs.fess.entity.FacetQueryView;
49  import org.codelibs.fess.helper.ViewHelper;
50  import org.codelibs.fess.util.ComponentUtil;
51  import org.elasticsearch.common.joda.Joda;
52  import org.lastaflute.di.util.LdiURLUtil;
53  import org.lastaflute.web.util.LaRequestUtil;
54  import org.lastaflute.web.util.LaResponseUtil;
55  import org.lastaflute.web.util.LaServletContextUtil;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  import com.google.common.cache.CacheBuilder;
60  import com.google.common.cache.CacheLoader;
61  import com.google.common.cache.LoadingCache;
62  
63  public class FessFunctions {
64      private static final Logger logger = LoggerFactory.getLogger(FessFunctions.class);
65  
66      private static final String GEO_PREFIX = "geo.";
67  
68      private static final String FACET_PREFIX = "facet.";
69  
70      private static final String PDF_DATE = "pdf_date";
71  
72      private static LoadingCache<String, Long> resourceHashCache = CacheBuilder.newBuilder().maximumSize(1000)
73              .expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<String, Long>() {
74                  @Override
75                  public Long load(final String key) throws Exception {
76                      try {
77                          final Path path = Paths.get(LaServletContextUtil.getServletContext().getRealPath(key));
78                          if (Files.isRegularFile(path)) {
79                              return Files.getLastModifiedTime(path).toMillis();
80                          }
81                      } catch (final Exception e) {
82                          logger.debug("Failed to access " + key, e);
83                      }
84                      return 0L;
85                  }
86              });
87  
88      protected FessFunctions() {
89          // nothing
90      }
91  
92      public static Boolean labelExists(final String value) {
93          @SuppressWarnings("unchecked")
94          final Map<String, String> labelValueMap = (Map<String, String>) LaRequestUtil.getRequest().getAttribute(Constants.LABEL_VALUE_MAP);
95          if (labelValueMap != null) {
96              return labelValueMap.get(value) != null;
97          }
98          return false;
99      }
100 
101     public static String label(final String value) {
102         @SuppressWarnings("unchecked")
103         final Map<String, String> labelValueMap = (Map<String, String>) LaRequestUtil.getRequest().getAttribute(Constants.LABEL_VALUE_MAP);
104         if (labelValueMap != null) {
105             final String name = labelValueMap.get(value);
106             if (name != null) {
107                 return name;
108             }
109         }
110         return value;
111     }
112 
113     public static Date date(final Long value) {
114         if (value == null) {
115             return null;
116         }
117         return new Date(value.longValue());
118     }
119 
120     public static Date parseDate(final String value) {
121         return parseDate(value, Constants.DATE_OPTIONAL_TIME);
122     }
123 
124     public static Date parseDate(final String value, final String format) {
125         if (value == null) {
126             return null;
127         }
128 
129         try {
130             if (PDF_DATE.equals(format)) {
131                 final Calendar cal = DateConverter.toCalendar(value);
132                 return cal != null ? cal.getTime() : null;
133             }
134 
135             final long time = Joda.forPattern(format).parseMillis(value);
136             return new Date(time);
137         } catch (final Exception e) {
138             return null;
139         }
140     }
141 
142     public static String formatDate(final Date date) {
143         if (date == null) {
144             return StringUtil.EMPTY;
145         }
146         final SimpleDateFormat sdf = new SimpleDateFormat(Constants.ISO_DATETIME_FORMAT);
147         sdf.setTimeZone(Constants.TIMEZONE_UTC);
148         return sdf.format(date);
149     }
150 
151     public static String formatDate(final LocalDateTime date) {
152         if (date == null) {
153             return StringUtil.EMPTY;
154         }
155         return date.format(DateTimeFormatter.ofPattern(Constants.ISO_DATETIME_FORMAT, Locale.ROOT));
156     }
157 
158     public static String formatNumber(final long value, final String pattern) {
159         final DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(getUserLocale());
160         df.applyPattern(pattern);
161         return df.format(value);
162     }
163 
164     private static Locale getUserLocale() {
165         final Locale locale = ComponentUtil.getRequestManager().getUserLocale();
166         if (locale == null) {
167             return Locale.ROOT;
168         }
169         return locale;
170     }
171 
172     public static String formatFileSize(final long value) {
173         double target = (double) value;
174         String unit = ""; // TODO l10n?
175         String format = "0.#";
176         if (value < 1024) {
177             format = "0";
178         } else if (value < 1024L * 1024L) {
179             target /= 1024;
180             unit = "K";
181         } else if (value < 1024L * 1024L * 1024L) {
182             target /= 1024;
183             target /= 1024;
184             unit = "M";
185         } else if (value < 1024L * 1024L * 1024L * 1024L) {
186             target /= 1024;
187             target /= 1024;
188             target /= 1024;
189             unit = "G";
190         } else {
191             target /= 1024;
192             target /= 1024;
193             target /= 1024;
194             target /= 1024;
195             unit = "T";
196         }
197         final DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(getUserLocale());
198         df.applyPattern(format);
199         df.setRoundingMode(RoundingMode.HALF_UP);
200         return df.format(target) + unit;
201     }
202 
203     public static String pagingQuery(final String query) {
204         final HttpServletRequest request = LaRequestUtil.getRequest();
205         @SuppressWarnings("unchecked")
206         final List<String> pagingQueryList = (List<String>) request.getAttribute(Constants.PAGING_QUERY_LIST);
207         if (pagingQueryList != null) {
208             final String prefix;
209             if (query != null) {
210                 prefix = "ex_q=" + query.split(":")[0] + "%3A";
211             } else {
212                 prefix = null;
213             }
214             return pagingQueryList.stream().filter(s -> prefix == null || !s.startsWith(prefix))
215                     .collect(Collectors.joining("&", "&", StringUtil.EMPTY));
216         }
217         return StringUtil.EMPTY;
218     }
219 
220     public static String facetQuery() {
221         return createQuery(Constants.FACET_QUERY, FACET_PREFIX);
222     }
223 
224     public static String geoQuery() {
225         return createQuery(Constants.GEO_QUERY, GEO_PREFIX);
226     }
227 
228     public static String facetForm() {
229         return createForm(Constants.FACET_FORM, FACET_PREFIX);
230     }
231 
232     public static String geoForm() {
233         return createForm(Constants.GEO_FORM, GEO_PREFIX);
234     }
235 
236     public static List<FacetQueryView> facetQueryViewList() {
237         final ViewHelper viewHelper = ComponentUtil.getViewHelper();
238         return viewHelper.getFacetQueryViewList();
239     }
240 
241     private static String createQuery(final String key, final String prefix) {
242         final HttpServletRequest request = LaRequestUtil.getRequest();
243         String query = (String) request.getAttribute(key);
244         if (query == null) {
245             final StringBuilder buf = new StringBuilder(100);
246             final Enumeration<String> names = request.getParameterNames();
247             while (names.hasMoreElements()) {
248                 final String name = names.nextElement();
249                 if (name.startsWith(prefix)) {
250                     final String[] values = request.getParameterValues(name);
251                     if (values != null) {
252                         for (final String value : values) {
253                             buf.append('&');
254                             buf.append(LdiURLUtil.encode(name, Constants.UTF_8));
255                             buf.append('=');
256                             buf.append(LdiURLUtil.encode(value, Constants.UTF_8));
257                         }
258                     }
259                 }
260             }
261             query = buf.toString();
262             request.setAttribute(key, query);
263         }
264         return query;
265     }
266 
267     private static String createForm(final String key, final String prefix) {
268         final HttpServletRequest request = LaRequestUtil.getRequest();
269         String query = (String) request.getAttribute(key);
270         if (query == null) {
271             final StringBuilder buf = new StringBuilder(100);
272             final Enumeration<String> names = request.getParameterNames();
273             while (names.hasMoreElements()) {
274                 final String name = names.nextElement();
275                 if (name.startsWith(prefix)) {
276                     final String[] values = request.getParameterValues(name);
277                     if (values != null) {
278                         for (final String value : values) {
279                             buf.append("<input type=\"hidden\" name=\"");
280                             buf.append(StringEscapeUtils.escapeHtml4(name));
281                             buf.append("\" value=\"");
282                             buf.append(StringEscapeUtils.escapeHtml4(value));
283                             buf.append("\"/>");
284                         }
285                     }
286                 }
287             }
288             query = buf.toString();
289             request.setAttribute(key, query);
290         }
291         return query;
292     }
293 
294     public static String base64(final String value) {
295         if (value == null) {
296             return StringUtil.EMPTY;
297         }
298         return Base64.getUrlEncoder().encodeToString(value.getBytes(Constants.CHARSET_UTF_8));
299     }
300 
301     public static boolean fileExists(final String path) {
302         final File file = new File(LaServletContextUtil.getServletContext().getRealPath(path));
303         return file.exists();
304     }
305 
306     public static String url(final String input) {
307         if (input == null) {
308             final String msg = "The argument 'input' should not be null.";
309             throw new IllegalArgumentException(msg);
310         }
311         if (!input.startsWith("/")) {
312             final String msg = "The argument 'input' should start with slash '/': " + input;
313             throw new IllegalArgumentException(msg);
314         }
315         final String contextPath = LaRequestUtil.getRequest().getContextPath();
316         final StringBuilder sb = new StringBuilder();
317         if (contextPath.length() > 1) {
318             sb.append(contextPath);
319         }
320         sb.append(input);
321         if (input.indexOf('?') == -1) {
322             try {
323                 final Long value = resourceHashCache.get(input);
324                 if (value.longValue() > 0) {
325                     sb.append("?t=").append(value.toString());
326                 }
327             } catch (final ExecutionException e) {
328                 logger.debug("Failed to access " + input, e);
329             }
330         }
331         return LaResponseUtil.getResponse().encodeURL(sb.toString());
332     }
333 
334     public static String sdh(final String input) {
335         if (StringUtil.isBlank(input)) {
336             return input;
337         }
338         return ComponentUtil.getDocumentHelper().encodeSimilarDocHash(input);
339     }
340 
341     public static String join(final Object input) {
342         String[] values = null;
343         if (input instanceof String[]) {
344             values = (String[]) input;
345         } else if (input instanceof List) {
346             values = ((List<?>) input).stream().filter(Objects::nonNull).map(Object::toString).toArray(n -> new String[n]);
347         } else if (input instanceof String) {
348             return input.toString();
349         }
350         if (values != null) {
351             return stream(values).get(stream -> stream.filter(StringUtil::isNotBlank).map(String::trim).collect(Collectors.joining(" ")));
352         }
353         return StringUtil.EMPTY;
354     }
355 
356     public static String replace(final Object input, final String regex, final String replacement) {
357         if (input == null) {
358             return StringUtil.EMPTY;
359         }
360         return input.toString().replaceAll(regex, replacement);
361     }
362 }