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