View Javadoc
1   /*
2    * Copyright 2012-2021 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.app.web.admin.fileauth;
17  
18  import java.util.ArrayList;
19  import java.util.HashMap;
20  import java.util.List;
21  import java.util.Locale;
22  import java.util.Map;
23  
24  import javax.annotation.Resource;
25  
26  import org.codelibs.fess.Constants;
27  import org.codelibs.fess.annotation.Secured;
28  import org.codelibs.fess.app.pager.FileAuthPager;
29  import org.codelibs.fess.app.service.FileAuthenticationService;
30  import org.codelibs.fess.app.service.FileConfigService;
31  import org.codelibs.fess.app.web.CrudMode;
32  import org.codelibs.fess.app.web.base.FessAdminAction;
33  import org.codelibs.fess.es.config.exentity.FileAuthentication;
34  import org.codelibs.fess.es.config.exentity.FileConfig;
35  import org.codelibs.fess.helper.SystemHelper;
36  import org.codelibs.fess.util.ComponentUtil;
37  import org.codelibs.fess.util.RenderDataUtil;
38  import org.dbflute.optional.OptionalEntity;
39  import org.dbflute.optional.OptionalThing;
40  import org.lastaflute.web.Execute;
41  import org.lastaflute.web.response.HtmlResponse;
42  import org.lastaflute.web.response.render.RenderData;
43  import org.lastaflute.web.ruts.process.ActionRuntime;
44  
45  /**
46   * @author shinsuke
47   * @author Keiichi Watanabe
48   */
49  public class AdminFileauthAction extends FessAdminAction {
50  
51      public static final String ROLE = "admin-fileauth";
52  
53      // ===================================================================================
54      //                                                                           Attribute
55      //                                                                           =========
56      @Resource
57      private FileAuthenticationService fileAuthenticationService;
58      @Resource
59      private FileAuthPager fileAuthenticationPager;
60  
61      @Resource
62      protected FileConfigService fileConfigService;
63  
64      // ===================================================================================
65      //                                                                               Hook
66      //                                                                              ======
67      @Override
68      protected void setupHtmlData(final ActionRuntime runtime) {
69          super.setupHtmlData(runtime);
70          runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameFileauth()));
71      }
72  
73      @Override
74      protected String getActionRole() {
75          return ROLE;
76      }
77  
78      // ===================================================================================
79      //                                                                      Search Execute
80      //                                                                      ==============
81      @Execute
82      @Secured({ ROLE, ROLE + VIEW })
83      public HtmlResponse index() {
84          return asListHtml();
85      }
86  
87      @Execute
88      @Secured({ ROLE, ROLE + VIEW })
89      public HtmlResponse list(final OptionalThing<Integer> pageNumber, final SearchForm form) {
90          pageNumber.ifPresent(num -> {
91              fileAuthenticationPager.setCurrentPageNumber(pageNumber.get());
92          }).orElse(() -> {
93              fileAuthenticationPager.setCurrentPageNumber(0);
94          });
95          return asHtml(path_AdminFileauth_AdminFileauthJsp).renderWith(data -> {
96              searchPaging(data, form);
97          });
98      }
99  
100     @Execute
101     @Secured({ ROLE, ROLE + VIEW })
102     public HtmlResponse search(final SearchForm form) {
103         copyBeanToBean(form, fileAuthenticationPager, op -> op.exclude(Constants.PAGER_CONVERSION_RULE));
104         return asHtml(path_AdminFileauth_AdminFileauthJsp).renderWith(data -> {
105             searchPaging(data, form);
106         });
107     }
108 
109     @Execute
110     @Secured({ ROLE, ROLE + VIEW })
111     public HtmlResponse reset(final SearchForm form) {
112         fileAuthenticationPager.clear();
113         return asHtml(path_AdminFileauth_AdminFileauthJsp).renderWith(data -> {
114             searchPaging(data, form);
115         });
116     }
117 
118     protected void searchPaging(final RenderData data, final SearchForm form) {
119         RenderDataUtil.register(data, "fileAuthenticationItems",
120                 fileAuthenticationService.getFileAuthenticationList(fileAuthenticationPager)); // page navi
121         RenderDataUtil.register(data, "displayCreateLink", !crawlingConfigHelper.getAllFileConfigList(false, false, false, null).isEmpty());
122         // restore from pager
123         copyBeanToBean(fileAuthenticationPager, form, op -> op.include("id"));
124     }
125 
126     // ===================================================================================
127     //                                                                        Edit Execute
128     //                                                                        ============
129     // -----------------------------------------------------
130     //                                            Entry Page
131     //                                            ----------
132     @Execute
133     @Secured({ ROLE })
134     public HtmlResponse createnew() {
135         saveToken();
136         return asHtml(path_AdminFileauth_AdminFileauthEditJsp).useForm(CreateForm.class, op -> {
137             op.setup(form -> {
138                 form.initialize();
139                 form.crudMode = CrudMode.CREATE;
140             });
141         }).renderWith(data -> {
142             registerProtocolSchemeItems(data);
143             registerFileConfigItems(data);
144         });
145     }
146 
147     @Execute
148     @Secured({ ROLE })
149     public HtmlResponse edit(final EditForm form) {
150         validate(form, messages -> {}, this::asListHtml);
151         final String id = form.id;
152         fileAuthenticationService.getFileAuthentication(id).ifPresent(entity -> {
153             copyBeanToBean(entity, form, op -> {});
154         }).orElse(() -> {
155             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asListHtml);
156         });
157         saveToken();
158         if (form.crudMode.intValue() == CrudMode.EDIT) {
159             // back
160             form.crudMode = CrudMode.DETAILS;
161             return asDetailsHtml();
162         }
163         form.crudMode = CrudMode.EDIT;
164         return asEditHtml();
165     }
166 
167     // -----------------------------------------------------
168     //                                               Details
169     //                                               -------
170     @Execute
171     @Secured({ ROLE, ROLE + VIEW })
172     public HtmlResponse details(final int crudMode, final String id) {
173         verifyCrudMode(crudMode, CrudMode.DETAILS);
174         saveToken();
175         return asDetailsHtml().useForm(EditForm.class, op -> {
176             op.setup(form -> {
177                 fileAuthenticationService.getFileAuthentication(id).ifPresent(entity -> {
178                     copyBeanToBean(entity, form, copyOp -> {
179                         copyOp.excludeNull();
180                     });
181                     form.crudMode = crudMode;
182                 }).orElse(() -> {
183                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asListHtml);
184                 });
185             });
186         });
187     }
188 
189     // -----------------------------------------------------
190     //                                         Actually Crud
191     //                                         -------------
192     @Execute
193     @Secured({ ROLE })
194     public HtmlResponse create(final CreateForm form) {
195         verifyCrudMode(form.crudMode, CrudMode.CREATE);
196         validate(form, messages -> {}, this::asEditHtml);
197         verifyToken(this::asEditHtml);
198         getFileAuthentication(form).ifPresent(entity -> {
199             try {
200                 fileAuthenticationService.store(entity);
201                 saveInfo(messages -> messages.addSuccessCrudCreateCrudTable(GLOBAL));
202             } catch (final Exception e) {
203                 throwValidationError(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)),
204                         this::asEditHtml);
205             }
206         }).orElse(() -> {
207             throwValidationError(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL), this::asEditHtml);
208         });
209         return redirect(getClass());
210     }
211 
212     @Execute
213     @Secured({ ROLE })
214     public HtmlResponse update(final EditForm form) {
215         verifyCrudMode(form.crudMode, CrudMode.EDIT);
216         validate(form, messages -> {}, this::asEditHtml);
217         verifyToken(this::asEditHtml);
218         getFileAuthentication(form).ifPresent(entity -> {
219             try {
220                 fileAuthenticationService.store(entity);
221                 saveInfo(messages -> messages.addSuccessCrudUpdateCrudTable(GLOBAL));
222             } catch (final Exception e) {
223                 throwValidationError(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)),
224                         this::asEditHtml);
225             }
226         }).orElse(() -> {
227             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.id), this::asEditHtml);
228         });
229         return redirect(getClass());
230     }
231 
232     @Execute
233     @Secured({ ROLE })
234     public HtmlResponse delete(final EditForm form) {
235         verifyCrudMode(form.crudMode, CrudMode.DETAILS);
236         validate(form, messages -> {}, this::asDetailsHtml);
237         verifyToken(this::asDetailsHtml);
238         final String id = form.id;
239         fileAuthenticationService.getFileAuthentication(id).ifPresent(entity -> {
240             try {
241                 fileAuthenticationService.delete(entity);
242                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
243             } catch (final Exception e) {
244                 throwValidationError(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)),
245                         this::asEditHtml);
246             }
247         }).orElse(() -> {
248             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asDetailsHtml);
249         });
250         return redirect(getClass());
251     }
252 
253     //===================================================================================
254     //                                                                        Assist Logic
255     //                                                                        ============
256     public static OptionalEntity<FileAuthentication> getEntity(final CreateForm form, final String username, final long currentTime) {
257         switch (form.crudMode) {
258         case CrudMode.CREATE:
259             return OptionalEntity.of(new FileAuthentication()).map(entity -> {
260                 entity.setCreatedBy(username);
261                 entity.setCreatedTime(currentTime);
262                 return entity;
263             });
264         case CrudMode.EDIT:
265             if (form instanceof EditForm) {
266                 return ComponentUtil.getComponent(FileAuthenticationService.class).getFileAuthentication(((EditForm) form).id);
267             }
268             break;
269         default:
270             break;
271         }
272         return OptionalEntity.empty();
273     }
274 
275     public static OptionalEntity<FileAuthentication> getFileAuthentication(final CreateForm form) {
276         final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
277         final String username = systemHelper.getUsername();
278         final long currentTime = systemHelper.getCurrentTimeAsLong();
279         return getEntity(form, username, currentTime).map(entity -> {
280             entity.setUpdatedBy(username);
281             entity.setUpdatedTime(currentTime);
282             copyBeanToBean(form, entity, op -> op.exclude(Constants.COMMON_CONVERSION_RULE));
283             return entity;
284         });
285     }
286 
287     protected void registerProtocolSchemeItems(final RenderData data) {
288         final List<Map<String, String>> itemList = new ArrayList<>();
289         final Locale locale = ComponentUtil.getRequestManager().getUserLocale();
290         itemList.add(createItem(ComponentUtil.getMessageManager().getMessage(locale, "labels.file_auth_scheme_samba"), Constants.SAMBA));
291         itemList.add(createItem(ComponentUtil.getMessageManager().getMessage(locale, "labels.file_auth_scheme_ftp"), Constants.FTP));
292         RenderDataUtil.register(data, "protocolSchemeItems", itemList);
293     }
294 
295     protected void registerFileConfigItems(final RenderData data) {
296         final List<Map<String, String>> itemList = new ArrayList<>();
297         final List<FileConfig> fileConfigList = crawlingConfigHelper.getAllFileConfigList(false, false, false, null);
298         for (final FileConfig fileConfig : fileConfigList) {
299             itemList.add(createItem(fileConfig.getName(), fileConfig.getId().toString()));
300         }
301         RenderDataUtil.register(data, "fileConfigItems", itemList);
302     }
303 
304     protected Map<String, String> createItem(final String label, final String value) {
305         final Map<String, String> map = new HashMap<>(2);
306         map.put(Constants.ITEM_LABEL, label);
307         map.put(Constants.ITEM_VALUE, value);
308         return map;
309     }
310 
311     // ===================================================================================
312     //                                                                        Small Helper
313     //                                                                        ============
314     protected void verifyCrudMode(final int crudMode, final int expectedMode) {
315         if (crudMode != expectedMode) {
316             throwValidationError(messages -> {
317                 messages.addErrorsCrudInvalidMode(GLOBAL, String.valueOf(expectedMode), String.valueOf(crudMode));
318             }, this::asListHtml);
319         }
320     }
321 
322     // ===================================================================================
323     //                                                                              JSP
324     //                                                                           =========
325 
326     private HtmlResponse asListHtml() {
327         return asHtml(path_AdminFileauth_AdminFileauthJsp).renderWith(data -> {
328             RenderDataUtil.register(data, "fileAuthenticationItems",
329                     fileAuthenticationService.getFileAuthenticationList(fileAuthenticationPager)); // page navi
330             RenderDataUtil.register(data, "displayCreateLink",
331                     !crawlingConfigHelper.getAllFileConfigList(false, false, false, null).isEmpty());
332         }).useForm(SearchForm.class, setup -> {
333             setup.setup(form -> {
334                 copyBeanToBean(fileAuthenticationPager, form, op -> op.include("id"));
335             });
336         });
337     }
338 
339     private HtmlResponse asEditHtml() {
340         return asHtml(path_AdminFileauth_AdminFileauthEditJsp).renderWith(data -> {
341             registerProtocolSchemeItems(data);
342             registerFileConfigItems(data);
343         });
344     }
345 
346     private HtmlResponse asDetailsHtml() {
347         return asHtml(path_AdminFileauth_AdminFileauthDetailsJsp).renderWith(data -> {
348             registerProtocolSchemeItems(data);
349             registerFileConfigItems(data);
350         });
351     }
352 }