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