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