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