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.dict.protwords;
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.ProtwordsPager;
28  import org.codelibs.fess.app.service.ProtwordsService;
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.dict.protwords.ProtwordsItem;
33  import org.codelibs.fess.util.ComponentUtil;
34  import org.codelibs.fess.util.RenderDataUtil;
35  import org.dbflute.optional.OptionalEntity;
36  import org.dbflute.optional.OptionalThing;
37  import org.lastaflute.web.Execute;
38  import org.lastaflute.web.response.ActionResponse;
39  import org.lastaflute.web.response.HtmlResponse;
40  import org.lastaflute.web.response.render.RenderData;
41  import org.lastaflute.web.ruts.process.ActionRuntime;
42  import org.lastaflute.web.validation.VaErrorHook;
43  
44  /**
45   * @author ma2tani
46   */
47  public class AdminDictProtwordsAction extends FessAdminAction {
48  
49      // ===================================================================================
50      //                                                                           Attribute
51      //                                                                           =========
52      @Resource
53      private ProtwordsService protwordsService;
54      @Resource
55      private ProtwordsPager protwordsPager;
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.getOnlineHelpNameDictProtwords()));
64      }
65  
66      // ===================================================================================
67      //                                                                      Search Execute
68      //                                                                      ==============
69      @Execute
70      public HtmlResponse index(final SearchForm form) {
71          validate(form, messages -> {}, () -> asDictIndexHtml());
72          return asHtml(path_AdminDictProtwords_AdminDictProtwordsJsp).renderWith(data -> {
73              searchPaging(data, form);
74          });
75      }
76  
77      @Execute
78      public HtmlResponse list(final OptionalThing<Integer> pageNumber, final SearchForm form) {
79          validate(form, messages -> {}, () -> asDictIndexHtml());
80          pageNumber.ifPresent(num -> {
81              protwordsPager.setCurrentPageNumber(pageNumber.get());
82          }).orElse(() -> {
83              protwordsPager.setCurrentPageNumber(0);
84          });
85          return asHtml(path_AdminDictProtwords_AdminDictProtwordsJsp).renderWith(data -> {
86              searchPaging(data, form);
87          });
88      }
89  
90      @Execute
91      public HtmlResponse search(final SearchForm form) {
92          validate(form, messages -> {}, () -> asDictIndexHtml());
93          copyBeanToBean(form, protwordsPager, op -> op.exclude(Constants.PAGER_CONVERSION_RULE));
94          return asHtml(path_AdminDictProtwords_AdminDictProtwordsJsp).renderWith(data -> {
95              searchPaging(data, form);
96          });
97      }
98  
99      @Execute
100     public HtmlResponse reset(final SearchForm form) {
101         validate(form, messages -> {}, () -> asDictIndexHtml());
102         protwordsPager.clear();
103         return asHtml(path_AdminDictProtwords_AdminDictProtwordsJsp).renderWith(data -> {
104             searchPaging(data, form);
105         });
106     }
107 
108     protected void searchPaging(final RenderData data, final SearchForm form) {
109         // page navi
110         RenderDataUtil.register(data, "protwordsItemItems", protwordsService.getProtwordsList(form.dictId, protwordsPager));
111 
112         // restore from pager
113         BeanUtil.copyBeanToBean(protwordsPager, form, op -> {
114             op.exclude(Constants.PAGER_CONVERSION_RULE);
115         });
116     }
117 
118     // ===================================================================================
119     //                                                                        Edit Execute
120     //                                                                        ============
121     // -----------------------------------------------------
122     //                                            Entry Page
123     //                                            ----------
124     @Execute
125     public HtmlResponse createnew(final String dictId) {
126         saveToken();
127         return asHtml(path_AdminDictProtwords_AdminDictProtwordsEditJsp).useForm(CreateForm.class, op -> {
128             op.setup(form -> {
129                 form.initialize();
130                 form.crudMode = CrudMode.CREATE;
131                 form.dictId = dictId;
132             });
133         });
134     }
135 
136     @Execute
137     public HtmlResponse edit(final EditForm form) {
138         validate(form, messages -> {}, () -> asListHtml(form.dictId));
139         protwordsService
140                 .getProtwordsItem(form.dictId, form.id)
141                 .ifPresent(entity -> {
142                     form.input = entity.getInputValue();
143                 })
144                 .orElse(() -> {
145                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.getDisplayId()),
146                             () -> asListHtml(form.dictId));
147                 });
148         saveToken();
149         if (form.crudMode.intValue() == CrudMode.EDIT) {
150             // back
151             form.crudMode = CrudMode.DETAILS;
152             return asDetailsHtml();
153         } else {
154             form.crudMode = CrudMode.EDIT;
155             return asEditHtml();
156         }
157     }
158 
159     // -----------------------------------------------------
160     //                                               Details
161     //                                               -------
162     @Execute
163     public HtmlResponse details(final String dictId, final int crudMode, final long id) {
164         verifyCrudMode(crudMode, CrudMode.DETAILS, dictId);
165         saveToken();
166         return asDetailsHtml().useForm(
167                 EditForm.class,
168                 op -> {
169                     op.setup(form -> {
170                         protwordsService
171                                 .getProtwordsItem(dictId, id)
172                                 .ifPresent(entity -> {
173                                     form.input = entity.getInputValue();
174                                 })
175                                 .orElse(() -> {
176                                     throwValidationError(
177                                             messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, dictId + ":" + id),
178                                             () -> asListHtml(dictId));
179                                 });
180                         form.id = id;
181                         form.crudMode = crudMode;
182                         form.dictId = dictId;
183                     });
184                 });
185     }
186 
187     // -----------------------------------------------------
188     //                                              Download
189     //                                               -------
190     @Execute
191     public HtmlResponse downloadpage(final String dictId) {
192         saveToken();
193         return asHtml(path_AdminDictProtwords_AdminDictProtwordsDownloadJsp).useForm(DownloadForm.class, op -> {
194             op.setup(form -> {
195                 form.dictId = dictId;
196             });
197         }).renderWith(data -> {
198             protwordsService.getProtwordsFile(dictId).ifPresent(file -> {
199                 RenderDataUtil.register(data, "path", file.getPath());
200             }).orElse(() -> {
201                 throwValidationError(messages -> messages.addErrorsFailedToDownloadProtwordsFile(GLOBAL), () -> asDictIndexHtml());
202             });
203         });
204     }
205 
206     @Execute
207     public ActionResponse download(final DownloadForm form) {
208         validate(form, messages -> {}, () -> downloadpage(form.dictId));
209         verifyTokenKeep(() -> downloadpage(form.dictId));
210         return protwordsService.getProtwordsFile(form.dictId).map(file -> {
211             return asStream(new File(file.getPath()).getName()).contentTypeOctetStream().stream(out -> {
212                 try (InputStream inputStream = file.getInputStream()) {
213                     out.write(inputStream);
214                 }
215             });
216         }).orElseGet(() -> {
217             throwValidationError(messages -> messages.addErrorsFailedToDownloadProtwordsFile(GLOBAL), () -> downloadpage(form.dictId));
218             return null;
219         });
220     }
221 
222     // -----------------------------------------------------
223     //                                                Upload
224     //                                               -------
225     @Execute
226     public HtmlResponse uploadpage(final String dictId) {
227         saveToken();
228         return asHtml(path_AdminDictProtwords_AdminDictProtwordsUploadJsp).useForm(UploadForm.class, op -> {
229             op.setup(form -> {
230                 form.dictId = dictId;
231             });
232         }).renderWith(data -> {
233             protwordsService.getProtwordsFile(dictId).ifPresent(file -> {
234                 RenderDataUtil.register(data, "path", file.getPath());
235             }).orElse(() -> {
236                 throwValidationError(messages -> messages.addErrorsFailedToDownloadProtwordsFile(GLOBAL), () -> asDictIndexHtml());
237             });
238         });
239     }
240 
241     @Execute
242     public HtmlResponse upload(final UploadForm form) {
243         validate(form, messages -> {}, () -> uploadpage(form.dictId));
244         verifyToken(() -> uploadpage(form.dictId));
245         return protwordsService.getProtwordsFile(form.dictId).map(file -> {
246             try (InputStream inputStream = form.protwordsFile.getInputStream()) {
247                 file.update(inputStream);
248             } catch (final IOException e) {
249                 throwValidationError(messages -> messages.addErrorsFailedToUploadProtwordsFile(GLOBAL), () -> {
250                     return redirectWith(getClass(), moreUrl("uploadpage/" + form.dictId));
251                 });
252             }
253             saveInfo(messages -> messages.addSuccessUploadSynonymFile(GLOBAL));
254             return redirectWith(getClass(), moreUrl("uploadpage/" + form.dictId));
255         }).orElseGet(() -> {
256             throwValidationError(messages -> messages.addErrorsFailedToUploadProtwordsFile(GLOBAL), () -> uploadpage(form.dictId));
257             return null;
258         });
259 
260     }
261 
262     // -----------------------------------------------------
263     //                                         Actually Crud
264     //                                         -------------
265     @Execute
266     public HtmlResponse create(final CreateForm form) {
267         verifyCrudMode(form.crudMode, CrudMode.CREATE, form.dictId);
268         validate(form, messages -> {}, () -> asEditHtml());
269         verifyToken(() -> asEditHtml());
270         createProtwordsItem(form, () -> asEditHtml()).ifPresent(entity -> {
271             protwordsService.store(form.dictId, entity);
272             saveInfo(messages -> messages.addSuccessCrudCreateCrudTable(GLOBAL));
273         }).orElse(() -> throwValidationError(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL), () -> asEditHtml()));
274         return redirectWith(getClass(), moreUrl("list/1").params("dictId", form.dictId));
275     }
276 
277     @Execute
278     public HtmlResponse update(final EditForm form) {
279         verifyCrudMode(form.crudMode, CrudMode.EDIT, form.dictId);
280         validate(form, messages -> {}, () -> asEditHtml());
281         verifyToken(() -> asEditHtml());
282         createProtwordsItem(form, () -> asEditHtml()).ifPresent(entity -> {
283             protwordsService.store(form.dictId, entity);
284             saveInfo(messages -> messages.addSuccessCrudUpdateCrudTable(GLOBAL));
285         }).orElse(
286                 () -> throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.getDisplayId()),
287                         () -> asEditHtml()));
288         return redirectWith(getClass(), moreUrl("list/1").params("dictId", form.dictId));
289     }
290 
291     @Execute
292     public HtmlResponse delete(final EditForm form) {
293         verifyCrudMode(form.crudMode, CrudMode.DETAILS, form.dictId);
294         validate(form, messages -> {}, () -> asDetailsHtml());
295         verifyToken(() -> asDetailsHtml());
296         protwordsService
297                 .getProtwordsItem(form.dictId, form.id)
298                 .ifPresent(entity -> {
299                     protwordsService.delete(form.dictId, entity);
300                     saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
301                 })
302                 .orElse(() -> {
303                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, form.getDisplayId()),
304                             () -> asDetailsHtml());
305                 });
306         return redirectWith(getClass(), moreUrl("list/1").params("dictId", form.dictId));
307     }
308 
309     //===================================================================================
310     //                                                                        Assist Logic
311     //                                                                        ============
312 
313     private static OptionalEntity<ProtwordsItem> getEntity(final CreateForm form) {
314         switch (form.crudMode) {
315         case CrudMode.CREATE:
316             final ProtwordsItem entity = new ProtwordsItem(0, StringUtil.EMPTY);
317             return OptionalEntity.of(entity);
318         case CrudMode.EDIT:
319             if (form instanceof EditForm) {
320                 return ComponentUtil.getComponent(ProtwordsService.class).getProtwordsItem(form.dictId, ((EditForm) form).id);
321             }
322             break;
323         default:
324             break;
325         }
326         return OptionalEntity.empty();
327     }
328 
329     public static OptionalEntity<ProtwordsItem> createProtwordsItem(final CreateForm form, final VaErrorHook hook) {
330         return getEntity(form).map(entity -> {
331             final String newInput = form.input;
332             validateProtwordsString(newInput, "input", hook);
333             entity.setNewInput(newInput);
334             return entity;
335         });
336     }
337 
338     // ===================================================================================
339     //                                                                        Small Helper
340     //                                                                        ============
341     protected void verifyCrudMode(final int crudMode, final int expectedMode, final String dictId) {
342         if (crudMode != expectedMode) {
343             throwValidationError(messages -> {
344                 messages.addErrorsCrudInvalidMode(GLOBAL, String.valueOf(expectedMode), String.valueOf(crudMode));
345             }, () -> asListHtml(dictId));
346         }
347     }
348 
349     private static void validateProtwordsString(final String values, final String propertyName, final VaErrorHook hook) {
350         if (values.length() == 0) {
351             return;
352         }
353         // TODO validation
354     }
355 
356     // ===================================================================================
357     //                                                                              JSP
358     //                                                                           =========
359 
360     protected HtmlResponse asDictIndexHtml() {
361         return redirect(AdminDictAction.class);
362     }
363 
364     private HtmlResponse asListHtml(final String dictId) {
365         return asHtml(path_AdminDictProtwords_AdminDictProtwordsJsp).renderWith(data -> {
366             RenderDataUtil.register(data, "protwordsItemItems", protwordsService.getProtwordsList(dictId, protwordsPager));
367         }).useForm(SearchForm.class, setup -> {
368             setup.setup(form -> {
369                 copyBeanToBean(protwordsPager, form, op -> op.include("id"));
370             });
371         });
372     }
373 
374     private HtmlResponse asEditHtml() {
375         return asHtml(path_AdminDictProtwords_AdminDictProtwordsEditJsp);
376     }
377 
378     private HtmlResponse asDetailsHtml() {
379         return asHtml(path_AdminDictProtwords_AdminDictProtwordsDetailsJsp);
380     }
381 
382 }