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