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.role;
17  
18  import java.util.Base64;
19  
20  import javax.annotation.Resource;
21  
22  import org.codelibs.fess.Constants;
23  import org.codelibs.fess.app.pager.RolePager;
24  import org.codelibs.fess.app.service.RoleService;
25  import org.codelibs.fess.app.web.CrudMode;
26  import org.codelibs.fess.app.web.base.FessAdminAction;
27  import org.codelibs.fess.es.user.exentity.Role;
28  import org.codelibs.fess.util.ComponentUtil;
29  import org.codelibs.fess.util.RenderDataUtil;
30  import org.dbflute.optional.OptionalEntity;
31  import org.dbflute.optional.OptionalThing;
32  import org.lastaflute.web.Execute;
33  import org.lastaflute.web.response.HtmlResponse;
34  import org.lastaflute.web.response.render.RenderData;
35  import org.lastaflute.web.ruts.process.ActionRuntime;
36  import org.slf4j.Logger;
37  import org.slf4j.LoggerFactory;
38  
39  /**
40   * @author shinsuke
41   * @author Keiichi Watanabe
42   */
43  public class AdminRoleAction extends FessAdminAction {
44  
45      private static final Logger logger = LoggerFactory.getLogger(AdminRoleAction.class);
46  
47      // ===================================================================================
48      //                                                                           Attribute
49      //                                                                           =========
50      @Resource
51      private RoleService roleService;
52      @Resource
53      private RolePager rolePager;
54  
55      // ===================================================================================
56      //                                                                               Hook
57      //                                                                              ======
58      @Override
59      protected void setupHtmlData(final ActionRuntime runtime) {
60          super.setupHtmlData(runtime);
61          runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameRole()));
62      }
63  
64      // ===================================================================================
65      //                                                                      Search Execute
66      //                                                                      ==============
67      @Execute
68      public HtmlResponse index(final SearchForm form) {
69          return asListHtml();
70      }
71  
72      @Execute
73      public HtmlResponse list(final OptionalThing<Integer> pageNumber, final SearchForm form) {
74          pageNumber.ifPresent(num -> {
75              rolePager.setCurrentPageNumber(pageNumber.get());
76          }).orElse(() -> {
77              rolePager.setCurrentPageNumber(0);
78          });
79          return asHtml(path_AdminRole_AdminRoleJsp).renderWith(data -> {
80              searchPaging(data, form);
81          });
82      }
83  
84      @Execute
85      public HtmlResponse search(final SearchForm form) {
86          copyBeanToBean(form, rolePager, op -> op.exclude(Constants.PAGER_CONVERSION_RULE));
87          return asHtml(path_AdminRole_AdminRoleJsp).renderWith(data -> {
88              searchPaging(data, form);
89          });
90      }
91  
92      @Execute
93      public HtmlResponse reset(final SearchForm form) {
94          rolePager.clear();
95          return asHtml(path_AdminRole_AdminRoleJsp).renderWith(data -> {
96              searchPaging(data, form);
97          });
98      }
99  
100     protected void searchPaging(final RenderData data, final SearchForm form) {
101         RenderDataUtil.register(data, "roleItems", roleService.getRoleList(rolePager)); // page navi
102 
103         // restore from pager
104         copyBeanToBean(rolePager, form, op -> op.include("id"));
105     }
106 
107     // ===================================================================================
108     //                                                                        Edit Execute
109     //                                                                        ============
110     // -----------------------------------------------------
111     //                                            Entry Page
112     //                                            ----------
113     @Execute
114     public HtmlResponse createnew() {
115         saveToken();
116         return asHtml(path_AdminRole_AdminRoleEditJsp).useForm(CreateForm.class, op -> {
117             op.setup(form -> {
118                 form.initialize();
119                 form.crudMode = CrudMode.CREATE;
120             });
121         });
122     }
123 
124     // -----------------------------------------------------
125     //                                               Details
126     //                                               -------
127     @Execute
128     public HtmlResponse details(final int crudMode, final String id) {
129         verifyCrudMode(crudMode, CrudMode.DETAILS);
130         saveToken();
131         return asHtml(path_AdminRole_AdminRoleDetailsJsp).useForm(EditForm.class, op -> {
132             op.setup(form -> {
133                 roleService.getRole(id).ifPresent(entity -> {
134                     copyBeanToBean(entity, form, copyOp -> {
135                         copyOp.excludeNull();
136                     });
137                     form.crudMode = crudMode;
138                 }).orElse(() -> {
139                     throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), () -> asListHtml());
140                 });
141             });
142         });
143     }
144 
145     // -----------------------------------------------------
146     //                                         Actually Crud
147     //                                         -------------
148     @Execute
149     public HtmlResponse create(final CreateForm form) {
150         verifyCrudMode(form.crudMode, CrudMode.CREATE);
151         validate(form, messages -> {}, () -> asEditHtml());
152         verifyToken(() -> asEditHtml());
153         getRole(form).ifPresent(
154                 entity -> {
155                     try {
156                         roleService.store(entity);
157                         saveInfo(messages -> messages.addSuccessCrudCreateCrudTable(GLOBAL));
158                     } catch (final Exception e) {
159                         logger.error("Failed to add " + entity, e);
160                         throwValidationError(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)),
161                                 () -> asEditHtml());
162                     }
163                 }).orElse(() -> {
164             throwValidationError(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL), () -> asEditHtml());
165         });
166         return redirect(getClass());
167     }
168 
169     @Execute
170     public HtmlResponse delete(final EditForm form) {
171         verifyCrudMode(form.crudMode, CrudMode.DETAILS);
172         validate(form, messages -> {}, () -> asDetailsHtml());
173         verifyToken(() -> asDetailsHtml());
174         final String id = form.id;
175         roleService.getRole(id).ifPresent(entity -> {
176             try {
177                 roleService.delete(entity);
178                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
179             } catch (final Exception e) {
180                 logger.error("Failed to delete " + entity, e);
181                 throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), () -> asDetailsHtml());
182             }
183         }).orElse(() -> {
184             throwValidationError(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id), () -> asDetailsHtml());
185         });
186         return redirect(getClass());
187     }
188 
189     // ===================================================================================
190     //                                                                        Assist Logic
191     //                                                                        ============
192     private static OptionalEntity<Role> getEntity(final CreateForm form) {
193         switch (form.crudMode) {
194         case CrudMode.CREATE:
195             return OptionalEntity.of(new Role()).map(entity -> {
196                 entity.setId(Base64.getUrlEncoder().encodeToString(form.name.getBytes(Constants.CHARSET_UTF_8)));
197                 return entity;
198             });
199         case CrudMode.EDIT:
200             if (form instanceof EditForm) {
201                 return ComponentUtil.getComponent(RoleService.class).getRole(((EditForm) form).id);
202             }
203             break;
204         default:
205             break;
206         }
207         return OptionalEntity.empty();
208     }
209 
210     public static OptionalEntity<Role> getRole(final CreateForm form) {
211         return getEntity(form).map(entity -> {
212             copyBeanToBean(form, entity, op -> op.exclude(Constants.COMMON_CONVERSION_RULE));
213             return entity;
214         });
215     }
216 
217     // ===================================================================================
218     //                                                                        Small Helper
219     //                                                                        ============
220     protected void verifyCrudMode(final int crudMode, final int expectedMode) {
221         if (crudMode != expectedMode) {
222             throwValidationError(messages -> {
223                 messages.addErrorsCrudInvalidMode(GLOBAL, String.valueOf(expectedMode), String.valueOf(crudMode));
224             }, () -> asListHtml());
225         }
226     }
227 
228     // ===================================================================================
229     //                                                                              JSP
230     //                                                                           =========
231 
232     private HtmlResponse asListHtml() {
233         return asHtml(path_AdminRole_AdminRoleJsp).renderWith(data -> {
234             RenderDataUtil.register(data, "roleItems", roleService.getRoleList(rolePager)); // page navi
235             }).useForm(SearchForm.class, setup -> {
236             setup.setup(form -> {
237                 copyBeanToBean(rolePager, form, op -> op.include("id"));
238             });
239         });
240     }
241 
242     private HtmlResponse asEditHtml() {
243         return asHtml(path_AdminRole_AdminRoleEditJsp);
244     }
245 
246     private HtmlResponse asDetailsHtml() {
247         return asHtml(path_AdminRole_AdminRoleDetailsJsp);
248     }
249 }