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.duplicatehost;
17  
18  import javax.annotation.Resource;
19  
20  import org.codelibs.fess.Constants;
21  import org.codelibs.fess.annotation.Secured;
22  import org.codelibs.fess.app.pager.DuplicateHostPager;
23  import org.codelibs.fess.app.service.DuplicateHostService;
24  import org.codelibs.fess.app.web.CrudMode;
25  import org.codelibs.fess.app.web.base.FessAdminAction;
26  import org.codelibs.fess.es.config.exentity.DuplicateHost;
27  import org.codelibs.fess.helper.SystemHelper;
28  import org.codelibs.fess.util.ComponentUtil;
29  import org.codelibs.fess.util.RenderDataUtil;
30  import org.dbflute.optional.OptionalEntity;
31  import org.dbflute.optional.OptionalThing;
32  import org.lastaflute.web.Execute;
33  import org.lastaflute.web.response.HtmlResponse;
34  import org.lastaflute.web.response.render.RenderData;
35  import org.lastaflute.web.ruts.process.ActionRuntime;
36  
37  /**
38   * @author codelibs
39   * @author Keiichi Watanabe
40   */
41  public class AdminDuplicatehostAction extends FessAdminAction {
42  
43      public static final String ROLE = "admin-duplicatehost";
44  
45      // ===================================================================================
46      //                                                                           Attribute
47      //                                                                           =========
48      @Resource
49      private DuplicateHostService duplicateHostService;
50      @Resource
51      private DuplicateHostPager duplicateHostPager;
52  
53      // ===================================================================================
54      //                                                                               Hook
55      //                                                                              ======
56      @Override
57      protected void setupHtmlData(final ActionRuntime runtime) {
58          super.setupHtmlData(runtime);
59          runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameDuplicatehost()));
60      }
61  
62      @Override
63      protected String getActionRole() {
64          return ROLE;
65      }
66  
67      // ===================================================================================
68      //                                                                      Search Execute
69      //                                                                      ==============
70      @Execute
71      @Secured({ ROLE, ROLE + VIEW })
72      public HtmlResponse index(final SearchForm form) {
73          return asListHtml();
74      }
75  
76      @Execute
77      @Secured({ ROLE, ROLE + VIEW })
78      public HtmlResponse list(final OptionalThing<Integer> pageNumber, final SearchForm form) {
79          pageNumber.ifPresent(num -> {
80              duplicateHostPager.setCurrentPageNumber(pageNumber.get());
81          }).orElse(() -> {
82              duplicateHostPager.setCurrentPageNumber(0);
83          });
84          return asHtml(path_AdminDuplicatehost_AdminDuplicatehostJsp).renderWith(data -> {
85              searchPaging(data, form);
86          });
87      }
88  
89      @Execute
90      @Secured({ ROLE, ROLE + VIEW })
91      public HtmlResponse search(final SearchForm form) {
92          copyBeanToBean(form, duplicateHostPager, op -> op.exclude(Constants.PAGER_CONVERSION_RULE));
93          return asHtml(path_AdminDuplicatehost_AdminDuplicatehostJsp).renderWith(data -> {
94              searchPaging(data, form);
95          });
96      }
97  
98      @Execute
99      @Secured({ ROLE, ROLE + VIEW })
100     public HtmlResponse reset(final SearchForm form) {
101         duplicateHostPager.clear();
102         return asHtml(path_AdminDuplicatehost_AdminDuplicatehostJsp).renderWith(data -> {
103             searchPaging(data, form);
104         });
105     }
106 
107     protected void searchPaging(final RenderData data, final SearchForm form) {
108         RenderDataUtil.register(data, "duplicateHostItems", duplicateHostService.getDuplicateHostList(duplicateHostPager)); // page navi
109 
110         // restore from pager
111         copyBeanToBean(duplicateHostPager, form, op -> op.include("regularName", "duplicateHostName"));
112     }
113 
114     // ===================================================================================
115     //                                                                        Edit Execute
116     //                                                                        ============
117     // -----------------------------------------------------
118     //                                            Entry Page
119     //                                            ----------
120     @Execute
121     @Secured({ ROLE })
122     public HtmlResponse createnew() {
123         saveToken();
124         return asHtml(path_AdminDuplicatehost_AdminDuplicatehostEditJsp).useForm(CreateForm.class, op -> {
125             op.setup(form -> {
126                 form.initialize();
127                 form.crudMode = CrudMode.CREATE;
128             });
129         });
130     }
131 
132     @Execute
133     @Secured({ ROLE })
134     public HtmlResponse edit(final EditForm form) {
135         validate(form, messages -> {}, this::asListHtml);
136         final String id = form.id;
137         duplicateHostService.getDuplicateHost(id).ifPresent(entity -> {
138             copyBeanToBean(entity, form, op -> {});
139         }).orElse(() -> {
140             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asListHtml);
141         });
142         saveToken();
143         if (form.crudMode.intValue() == CrudMode.EDIT) {
144             // back
145             form.crudMode = CrudMode.DETAILS;
146             return asDetailsHtml();
147         }
148         form.crudMode = CrudMode.EDIT;
149         return asEditHtml();
150     }
151 
152     // -----------------------------------------------------
153     //                                               Details
154     //                                               -------
155     @Execute
156     @Secured({ ROLE, ROLE + VIEW })
157     public HtmlResponse details(final int crudMode, final String id) {
158         verifyCrudMode(crudMode, CrudMode.DETAILS);
159         saveToken();
160         return asHtml(path_AdminDuplicatehost_AdminDuplicatehostDetailsJsp).useForm(EditForm.class, op -> {
161             op.setup(form -> {
162                 duplicateHostService.getDuplicateHost(id).ifPresent(entity -> {
163                     copyBeanToBean(entity, form, copyOp -> {
164                         copyOp.excludeNull();
165                     });
166                     form.crudMode = crudMode;
167                 }).orElse(() -> {
168                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asListHtml);
169                 });
170             });
171         });
172     }
173 
174     // -----------------------------------------------------
175     //                                         Actually Crud
176     //                                         -------------
177     @Execute
178     @Secured({ ROLE })
179     public HtmlResponse create(final CreateForm form) {
180         verifyCrudMode(form.crudMode, CrudMode.CREATE);
181         validate(form, messages -> {}, this::asEditHtml);
182         verifyToken(this::asEditHtml);
183         getDuplicateHost(form).ifPresent(entity -> {
184             try {
185                 duplicateHostService.store(entity);
186                 saveInfo(messages -> messages.addSuccessCrudCreateCrudTable(GLOBAL));
187             } catch (final Exception e) {
188                 throwValidationError(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)),
189                         this::asEditHtml);
190             }
191         }).orElse(() -> {
192             throwValidationError(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL), this::asEditHtml);
193         });
194         return redirect(getClass());
195     }
196 
197     @Execute
198     @Secured({ ROLE })
199     public HtmlResponse update(final EditForm form) {
200         verifyCrudMode(form.crudMode, CrudMode.EDIT);
201         validate(form, messages -> {}, this::asEditHtml);
202         verifyToken(this::asEditHtml);
203         getDuplicateHost(form).ifPresent(entity -> {
204             try {
205                 duplicateHostService.store(entity);
206                 saveInfo(messages -> messages.addSuccessCrudUpdateCrudTable(GLOBAL));
207             } catch (final Exception e) {
208                 throwValidationError(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)),
209                         this::asEditHtml);
210             }
211         }).orElse(() -> {
212             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.id), this::asEditHtml);
213         });
214         return redirect(getClass());
215     }
216 
217     @Execute
218     @Secured({ ROLE })
219     public HtmlResponse delete(final EditForm form) {
220         verifyCrudMode(form.crudMode, CrudMode.DETAILS);
221         validate(form, messages -> {}, this::asDetailsHtml);
222         verifyToken(this::asDetailsHtml);
223         final String id = form.id;
224         duplicateHostService.getDuplicateHost(id).ifPresent(entity -> {
225             try {
226                 duplicateHostService.delete(entity);
227                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
228             } catch (final Exception e) {
229                 throwValidationError(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)),
230                         this::asEditHtml);
231             }
232         }).orElse(() -> {
233             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), this::asDetailsHtml);
234         });
235         return redirect(getClass());
236     }
237 
238     // ===================================================================================
239     //                                                                        Assist Logic
240     //                                                                        ============
241     public static OptionalEntity<DuplicateHost> getEntity(final CreateForm form, final String username, final long currentTime) {
242         switch (form.crudMode) {
243         case CrudMode.CREATE:
244             return OptionalEntity.of(new DuplicateHost()).map(entity -> {
245                 entity.setCreatedBy(username);
246                 entity.setCreatedTime(currentTime);
247                 return entity;
248             });
249         case CrudMode.EDIT:
250             if (form instanceof EditForm) {
251                 return ComponentUtil.getComponent(DuplicateHostService.class).getDuplicateHost(((EditForm) form).id);
252             }
253             break;
254         default:
255             break;
256         }
257         return OptionalEntity.empty();
258     }
259 
260     public static OptionalEntity<DuplicateHost> getDuplicateHost(final CreateForm form) {
261         final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
262         final String username = systemHelper.getUsername();
263         final long currentTime = systemHelper.getCurrentTimeAsLong();
264         return getEntity(form, username, currentTime).map(entity -> {
265             entity.setUpdatedBy(username);
266             entity.setUpdatedTime(currentTime);
267             copyBeanToBean(form, entity, op -> op.exclude(Constants.COMMON_CONVERSION_RULE));
268             return entity;
269         });
270     }
271 
272     // ===================================================================================
273     //                                                                        Small Helper
274     //                                                                        ============
275     protected void verifyCrudMode(final int crudMode, final int expectedMode) {
276         if (crudMode != expectedMode) {
277             throwValidationError(messages -> {
278                 messages.addErrorsCrudInvalidMode(GLOBAL, String.valueOf(expectedMode), String.valueOf(crudMode));
279             }, this::asListHtml);
280         }
281     }
282 
283     // ===================================================================================
284     //                                                                              JSP
285     //                                                                           =========
286 
287     private HtmlResponse asListHtml() {
288         return asHtml(path_AdminDuplicatehost_AdminDuplicatehostJsp).renderWith(data -> {
289             RenderDataUtil.register(data, "duplicateHostItems", duplicateHostService.getDuplicateHostList(duplicateHostPager)); // page navi
290         }).useForm(SearchForm.class, setup -> {
291             setup.setup(form -> {
292                 copyBeanToBean(duplicateHostPager, form, op -> op.include("regularName", "duplicateHostName"));
293             });
294         });
295     }
296 
297     private HtmlResponse asEditHtml() {
298         return asHtml(path_AdminDuplicatehost_AdminDuplicatehostEditJsp);
299     }
300 
301     private HtmlResponse asDetailsHtml() {
302         return asHtml(path_AdminDuplicatehost_AdminDuplicatehostDetailsJsp);
303     }
304 }