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