View Javadoc
1   /*
2    * Copyright 2012-2019 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.dict.kuromoji;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.InputStream;
21  
22  import javax.annotation.Resource;
23  
24  import org.codelibs.core.beans.util.BeanUtil;
25  import org.codelibs.core.lang.StringUtil;
26  import org.codelibs.fess.Constants;
27  import org.codelibs.fess.app.pager.KuromojiPager;
28  import org.codelibs.fess.app.service.KuromojiService;
29  import org.codelibs.fess.app.web.CrudMode;
30  import org.codelibs.fess.app.web.admin.dict.AdminDictAction;
31  import org.codelibs.fess.app.web.base.FessAdminAction;
32  import org.codelibs.fess.app.web.base.FessBaseAction;
33  import org.codelibs.fess.dict.kuromoji.KuromojiItem;
34  import org.codelibs.fess.util.ComponentUtil;
35  import org.codelibs.fess.util.RenderDataUtil;
36  import org.dbflute.optional.OptionalEntity;
37  import org.dbflute.optional.OptionalThing;
38  import org.lastaflute.web.Execute;
39  import org.lastaflute.web.response.ActionResponse;
40  import org.lastaflute.web.response.HtmlResponse;
41  import org.lastaflute.web.response.render.RenderData;
42  import org.lastaflute.web.ruts.process.ActionRuntime;
43  import org.lastaflute.web.validation.VaErrorHook;
44  import org.lastaflute.web.validation.exception.ValidationErrorException;
45  
46  /**
47   * @author shinsuke
48   * @author Keiichi Watanabe
49   */
50  public class AdminDictKuromojiAction extends FessAdminAction {
51  
52      // ===================================================================================
53      //                                                                           Attribute
54      //                                                                           =========
55      @Resource
56      private KuromojiService kuromojiService;
57      @Resource
58      private KuromojiPager kuromojiPager;
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.getOnlineHelpNameDictKuromoji()));
67      }
68  
69      // ===================================================================================
70      //                                                                      Search Execute
71      //                                                                      ==============
72      @Execute
73      public HtmlResponse index(final SearchForm form) {
74          validate(form, messages -> {}, () -> asDictIndexHtml());
75          kuromojiPager.clear();
76          return asHtml(path_AdminDictKuromoji_AdminDictKuromojiJsp).renderWith(data -> {
77              searchPaging(data, form);
78          });
79      }
80  
81      @Execute
82      public HtmlResponse list(final OptionalThing<Integer> pageNumber, final SearchForm form) {
83          validate(form, messages -> {}, () -> asDictIndexHtml());
84          pageNumber.ifPresent(num -> {
85              kuromojiPager.setCurrentPageNumber(pageNumber.get());
86          }).orElse(() -> {
87              kuromojiPager.setCurrentPageNumber(0);
88          });
89          return asHtml(path_AdminDictKuromoji_AdminDictKuromojiJsp).renderWith(data -> {
90              searchPaging(data, form);
91          });
92      }
93  
94      @Execute
95      public HtmlResponse search(final SearchForm form) {
96          validate(form, messages -> {}, () -> asDictIndexHtml());
97          copyBeanToBean(form, kuromojiPager, op -> op.exclude(Constants.PAGER_CONVERSION_RULE));
98          return asHtml(path_AdminDictKuromoji_AdminDictKuromojiJsp).renderWith(data -> {
99              searchPaging(data, form);
100         });
101     }
102 
103     @Execute
104     public HtmlResponse reset(final SearchForm form) {
105         validate(form, messages -> {}, () -> asDictIndexHtml());
106         kuromojiPager.clear();
107         return asHtml(path_AdminDictKuromoji_AdminDictKuromojiJsp).renderWith(data -> {
108             searchPaging(data, form);
109         });
110     }
111 
112     protected void searchPaging(final RenderData data, final SearchForm form) {
113         // page navi
114         RenderDataUtil.register(data, "kuromojiItemItems", kuromojiService.getKuromojiList(form.dictId, kuromojiPager));
115 
116         // restore from pager
117         BeanUtil.copyBeanToBean(kuromojiPager, form, op -> {
118             op.exclude(Constants.PAGER_CONVERSION_RULE);
119         });
120     }
121 
122     // ===================================================================================
123     //                                                                        Edit Execute
124     //                                                                        ============
125     // -----------------------------------------------------
126     //                                            Entry Page
127     //                                            ----------
128     @Execute
129     public HtmlResponse createnew(final String dictId) {
130         saveToken();
131         return asHtml(path_AdminDictKuromoji_AdminDictKuromojiEditJsp).useForm(CreateForm.class, op -> {
132             op.setup(form -> {
133                 form.initialize();
134                 form.crudMode = CrudMode.CREATE;
135                 form.dictId = dictId;
136             });
137         });
138     }
139 
140     @Execute
141     public HtmlResponse edit(final EditForm form) {
142         validate(form, messages -> {}, () -> asListHtml(form.dictId));
143         kuromojiService
144                 .getKuromojiItem(form.dictId, form.id)
145                 .ifPresent(entity -> {
146                     copyBeanToBean(entity, form, op -> {});
147                 })
148                 .orElse(() -> {
149                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.getDisplayId()),
150                             () -> asListHtml(form.dictId));
151                 });
152         saveToken();
153         if (form.crudMode.intValue() == CrudMode.EDIT) {
154             // back
155             form.crudMode = CrudMode.DETAILS;
156             return asDetailsHtml();
157         } else {
158             form.crudMode = CrudMode.EDIT;
159             return asEditHtml();
160         }
161     }
162 
163     // -----------------------------------------------------
164     //                                               Details
165     //                                               -------
166     @Execute
167     public HtmlResponse details(final String dictId, final int crudMode, final long id) {
168         verifyCrudMode(crudMode, CrudMode.DETAILS, dictId);
169         saveToken();
170         return asDetailsHtml().useForm(
171                 EditForm.class,
172                 op -> {
173                     op.setup(form -> {
174                         kuromojiService
175                                 .getKuromojiItem(dictId, id)
176                                 .ifPresent(entity -> {
177                                     copyBeanToBean(entity, form, copyOp -> {
178                                         copyOp.excludeNull();
179                                     });
180                                     form.crudMode = crudMode;
181                                 })
182                                 .orElse(() -> {
183                                     throwValidationError(
184                                             messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, dictId + ":" + id),
185                                             () -> asListHtml(dictId));
186                                 });
187                         form.dictId = dictId;
188                     });
189                 });
190     }
191 
192     // -----------------------------------------------------
193     //                                              Download
194     //                                               -------
195     @Execute
196     public HtmlResponse downloadpage(final String dictId) {
197         saveToken();
198         return asHtml(path_AdminDictKuromoji_AdminDictKuromojiDownloadJsp).useForm(DownloadForm.class, op -> {
199             op.setup(form -> {
200                 form.dictId = dictId;
201             });
202         }).renderWith(data -> {
203             kuromojiService.getKuromojiFile(dictId).ifPresent(file -> {
204                 RenderDataUtil.register(data, "path", file.getPath());
205             }).orElse(() -> {
206                 throwValidationError(messages -> messages.addErrorsFailedToDownloadKuromojiFile(GLOBAL), () -> asDictIndexHtml());
207             });
208         });
209     }
210 
211     @Execute
212     public ActionResponse download(final DownloadForm form) {
213         validate(form, messages -> {}, () -> downloadpage(form.dictId));
214         verifyTokenKeep(() -> downloadpage(form.dictId));
215         return kuromojiService.getKuromojiFile(form.dictId).map(file -> {
216             return asStream(new File(file.getPath()).getName()).contentTypeOctetStream().stream(out -> {
217                 file.writeOut(out);
218             });
219         }).orElseGet(() -> {
220             throwValidationError(messages -> messages.addErrorsFailedToDownloadKuromojiFile(GLOBAL), () -> downloadpage(form.dictId));
221             return null;
222         });
223     }
224 
225     // -----------------------------------------------------
226     //                                                Upload
227     //                                               -------
228     @Execute
229     public HtmlResponse uploadpage(final String dictId) {
230         saveToken();
231         return asHtml(path_AdminDictKuromoji_AdminDictKuromojiUploadJsp).useForm(UploadForm.class, op -> {
232             op.setup(form -> {
233                 form.dictId = dictId;
234             });
235         }).renderWith(data -> {
236             kuromojiService.getKuromojiFile(dictId).ifPresent(file -> {
237                 RenderDataUtil.register(data, "path", file.getPath());
238             }).orElse(() -> {
239                 throwValidationError(messages -> messages.addErrorsFailedToDownloadKuromojiFile(GLOBAL), () -> asDictIndexHtml());
240             });
241         });
242     }
243 
244     @Execute
245     public HtmlResponse upload(final UploadForm form) {
246         validate(form, messages -> {}, () -> uploadpage(form.dictId));
247         verifyToken(() -> uploadpage(form.dictId));
248         return kuromojiService.getKuromojiFile(form.dictId).map(file -> {
249             try (InputStream inputStream = form.kuromojiFile.getInputStream()) {
250                 file.update(inputStream);
251             } catch (final IOException e) {
252                 throwValidationError(messages -> messages.addErrorsFailedToUploadKuromojiFile(GLOBAL), () -> {
253                     return redirectWith(getClass(), moreUrl("uploadpage/" + form.dictId));
254                 });
255             }
256             saveInfo(messages -> messages.addSuccessUploadKuromojiFile(GLOBAL));
257             return redirectWith(getClass(), moreUrl("uploadpage/" + form.dictId));
258         }).orElseGet(() -> {
259             throwValidationError(messages -> messages.addErrorsFailedToUploadKuromojiFile(GLOBAL), () -> uploadpage(form.dictId));
260             return null;
261         });
262 
263     }
264 
265     // -----------------------------------------------------
266     //                                         Actually Crud
267     //                                         -------------
268     @Execute
269     public HtmlResponse create(final CreateForm form) {
270         verifyCrudMode(form.crudMode, CrudMode.CREATE, form.dictId);
271         validate(form, messages -> {}, () -> asEditHtml());
272         verifyToken(() -> asEditHtml());
273         createKuromojiItem(form, () -> asEditHtml()).ifPresent(
274                 entity -> {
275                     try {
276                         kuromojiService.store(form.dictId, entity);
277                         saveInfo(messages -> messages.addSuccessCrudCreateCrudTable(GLOBAL));
278                     } catch (final Exception e) {
279                         throwValidationError(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)),
280                                 () -> asEditHtml());
281                     }
282                 }).orElse(() -> {
283             throwValidationError(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL), () -> asEditHtml());
284         });
285         return redirectWith(getClass(), moreUrl("list/1").params("dictId", form.dictId));
286     }
287 
288     @Execute
289     public HtmlResponse update(final EditForm form) {
290         verifyCrudMode(form.crudMode, CrudMode.EDIT, form.dictId);
291         validate(form, messages -> {}, () -> asEditHtml());
292         verifyToken(() -> asEditHtml());
293         createKuromojiItem(form, () -> asEditHtml()).ifPresent(
294                 entity -> {
295                     try {
296                         kuromojiService.store(form.dictId, entity);
297                         saveInfo(messages -> messages.addSuccessCrudUpdateCrudTable(GLOBAL));
298                     } catch (final Exception e) {
299                         throwValidationError(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)),
300                                 () -> asEditHtml());
301                     }
302                 }).orElse(() -> {
303             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.getDisplayId()), () -> asEditHtml());
304         });
305         return redirectWith(getClass(), moreUrl("list/1").params("dictId", form.dictId));
306     }
307 
308     @Execute
309     public HtmlResponse delete(final EditForm form) {
310         verifyCrudMode(form.crudMode, CrudMode.DETAILS, form.dictId);
311         validate(form, messages -> {}, () -> asDetailsHtml());
312         verifyToken(() -> asDetailsHtml());
313         kuromojiService
314                 .getKuromojiItem(form.dictId, form.id)
315                 .ifPresent(
316                         entity -> {
317                             try {
318                                 kuromojiService.delete(form.dictId, entity);
319                                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
320                             } catch (final Exception e) {
321                                 throwValidationError(
322                                         messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)),
323                                         () -> asEditHtml());
324                             }
325                         })
326                 .orElse(() -> {
327                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.getDisplayId()),
328                             () -> asDetailsHtml());
329                 });
330         return redirectWith(getClass(), moreUrl("list/1").params("dictId", form.dictId));
331     }
332 
333     //===================================================================================
334     //                                                                        Assist Logic
335     //                                                                        ============
336 
337     private static OptionalEntity<KuromojiItem> getEntity(final CreateForm form) {
338         switch (form.crudMode) {
339         case CrudMode.CREATE:
340             final KuromojiItem/kuromoji/KuromojiItem.html#KuromojiItem">KuromojiItem entity = new KuromojiItem(0, StringUtil.EMPTY, StringUtil.EMPTY, StringUtil.EMPTY, StringUtil.EMPTY);
341             return OptionalEntity.of(entity);
342         case CrudMode.EDIT:
343             if (form instanceof EditForm) {
344                 return ComponentUtil.getComponent(KuromojiService.class).getKuromojiItem(form.dictId, ((EditForm) form).id);
345             }
346             break;
347         default:
348             break;
349         }
350         return OptionalEntity.empty();
351     }
352 
353     protected OptionalEntity<KuromojiItem> createKuromojiItem(final CreateForm form, final VaErrorHook hook) {
354         try {
355             return createKuromojiItem(this, form, hook);
356         } catch (final ValidationErrorException e) {
357             saveToken();
358             throw e;
359         }
360     }
361 
362     public static OptionalEntity<KuromojiItem> createKuromojiItem(final FessBaseAction action, final CreateForm form, final VaErrorHook hook) {
363         return getEntity(form).map(entity -> {
364             entity.setNewToken(form.token);
365             entity.setNewSegmentation(form.segmentation);
366             entity.setNewReading(form.reading);
367             entity.setNewPos(form.pos);
368             return entity;
369         });
370     }
371 
372     // ===================================================================================
373     //                                                                        Small Helper
374     //                                                                        ============
375     protected void verifyCrudMode(final int crudMode, final int expectedMode, final String dictId) {
376         if (crudMode != expectedMode) {
377             throwValidationError(messages -> {
378                 messages.addErrorsCrudInvalidMode(GLOBAL, String.valueOf(expectedMode), String.valueOf(crudMode));
379             }, () -> asListHtml(dictId));
380         }
381     }
382 
383     // ===================================================================================
384     //                                                                              JSP
385     //                                                                           =========
386 
387     protected HtmlResponse asDictIndexHtml() {
388         return redirect(AdminDictAction.class);
389     }
390 
391     private HtmlResponse asListHtml(final String dictId) {
392         return asHtml(path_AdminDictKuromoji_AdminDictKuromojiJsp).renderWith(data -> {
393             RenderDataUtil.register(data, "kuromojiItemItems", kuromojiService.getKuromojiList(dictId, kuromojiPager));
394         }).useForm(SearchForm.class, setup -> {
395             setup.setup(form -> {
396                 copyBeanToBean(kuromojiPager, form, op -> op.include("id"));
397             });
398         });
399     }
400 
401     private HtmlResponse asEditHtml() {
402         return asHtml(path_AdminDictKuromoji_AdminDictKuromojiEditJsp);
403     }
404 
405     private HtmlResponse asDetailsHtml() {
406         return asHtml(path_AdminDictKuromoji_AdminDictKuromojiDetailsJsp);
407     }
408 
409 }