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