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.dict;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.text.SimpleDateFormat;
21  import java.util.ArrayList;
22  import java.util.Date;
23  import java.util.List;
24  import java.util.Map;
25  
26  import javax.annotation.PostConstruct;
27  
28  import org.codelibs.core.io.FileUtil;
29  import org.codelibs.curl.CurlResponse;
30  import org.codelibs.elasticsearch.runner.net.EcrCurl;
31  import org.codelibs.fess.Constants;
32  import org.codelibs.fess.util.ComponentUtil;
33  import org.dbflute.optional.OptionalEntity;
34  import org.slf4j.Logger;
35  import org.slf4j.LoggerFactory;
36  
37  public class DictionaryManager {
38      private static final Logger logger = LoggerFactory.getLogger(DictionaryManager.class);
39  
40      protected List<DictionaryCreator> creatorList = new ArrayList<>();
41  
42      @PostConstruct
43      public void init() {
44          creatorList.forEach(creator -> {
45              creator.setDictionaryManager(this);
46          });
47      }
48  
49      public DictionaryFile<? extends DictionaryItem>[] getDictionaryFiles() {
50          try (CurlResponse response =
51                  ComponentUtil.getCurlHelper().get("/_configsync/file").param("fields", "path,@timestamp")
52                          .param("size", ComponentUtil.getFessConfig().getPageDictionaryMaxFetchSize()).execute()) {
53              final Map<String, Object> contentMap = response.getContent(EcrCurl.jsonParser());
54              @SuppressWarnings("unchecked")
55              final List<Map<String, Object>> fileList = (List<Map<String, Object>>) contentMap.get("file");
56              return fileList
57                      .stream()
58                      .map(fileMap -> {
59                          try {
60                              final String path = fileMap.get("path").toString();
61                              final Date timestamp =
62                                      new SimpleDateFormat(Constants.DATE_FORMAT_ISO_8601_EXTEND_UTC).parse(fileMap.get("@timestamp")
63                                              .toString());
64                              for (final DictionaryCreator creator : creatorList) {
65                                  final DictionaryFile<? extends DictionaryItem> file = creator.create(path, timestamp);
66                                  if (file != null) {
67                                      return file;
68                                  }
69                              }
70                          } catch (final Exception e) {
71                              logger.warn("Failed to load " + fileMap, e);
72                          }
73                          return null;
74                      }).filter(file -> file != null).toArray(n -> new DictionaryFile<?>[n]);
75          } catch (final IOException e) {
76              throw new DictionaryException("Failed to access dictionaries", e);
77          }
78      }
79  
80      public OptionalEntity<DictionaryFile<? extends DictionaryItem>> getDictionaryFile(final String id) {
81          for (final DictionaryFile<? extends DictionaryItem> dictFile : getDictionaryFiles()) {
82              if (dictFile.getId().equals(id)) {
83                  return OptionalEntity.of(dictFile);
84              }
85          }
86          return OptionalEntity.empty();
87      }
88  
89      public void store(final DictionaryFile<? extends DictionaryItem> dictFile, final File file) {
90          getDictionaryFile(dictFile.getId()).ifPresent(currentFile -> {
91              if (currentFile.getTimestamp().getTime() > dictFile.getTimestamp().getTime()) {
92                  throw new DictionaryException(dictFile.getPath() + " was updated.");
93              }
94  
95              // TODO use stream
96                  try (CurlResponse response =
97                          ComponentUtil.getCurlHelper().post("/_configsync/file").param("path", dictFile.getPath())
98                                  .body(FileUtil.readUTF8(file)).execute()) {
99                      final Map<String, Object> contentMap = response.getContent(EcrCurl.jsonParser());
100                     if (!Constants.TRUE.equalsIgnoreCase(contentMap.get("acknowledged").toString())) {
101                         throw new DictionaryException("Failed to update " + dictFile.getPath());
102                     }
103                 } catch (final IOException e) {
104                     throw new DictionaryException("Failed to update " + dictFile.getPath(), e);
105                 }
106 
107             }).orElse(() -> {
108             throw new DictionaryException(dictFile.getPath() + " does not exist.");
109         });
110     }
111 
112     public CurlResponse getContentResponse(final DictionaryFile<? extends DictionaryItem> dictFile) {
113         return ComponentUtil.getCurlHelper().get("/_configsync/file").param("path", dictFile.getPath()).execute();
114     }
115 
116     public void addCreator(final DictionaryCreator creator) {
117         creatorList.add(creator);
118     }
119 
120 }