KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > frontend > admin > AdminEntityEditorApple


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
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, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.outerj.daisy.frontend.admin;
17
18 import org.outerj.daisy.frontend.util.AbstractDaisyApple;
19 import org.outerj.daisy.frontend.util.FormHelper;
20 import org.outerj.daisy.frontend.util.EncodingUtil;
21 import org.outerj.daisy.frontend.PageContext;
22 import org.outerj.daisy.frontend.SkinConfHelper;
23 import org.outerj.daisy.frontend.WikiHelper;
24 import org.outerj.daisy.repository.Repository;
25 import org.outerj.daisy.repository.DocumentCollection;
26 import org.outerj.daisy.repository.RepositoryException;
27 import org.outerj.daisy.repository.LinkExtractorInfo;
28 import org.outerj.daisy.repository.schema.PartType;
29 import org.outerj.daisy.repository.user.Role;
30 import org.outerj.daisy.repository.user.User;
31 import org.outerj.daisy.repository.user.AuthenticationSchemeInfo;
32 import org.outerj.daisy.repository.variant.Branch;
33 import org.outerj.daisy.repository.variant.Language;
34 import org.apache.avalon.framework.service.Serviceable;
35 import org.apache.avalon.framework.service.ServiceManager;
36 import org.apache.avalon.framework.service.ServiceException;
37 import org.apache.cocoon.forms.formmodel.*;
38 import org.apache.cocoon.forms.binding.Binding;
39 import org.apache.cocoon.forms.FormContext;
40 import org.apache.cocoon.forms.validation.WidgetValidator;
41 import org.apache.cocoon.forms.validation.ValidationError;
42 import org.apache.cocoon.forms.util.StringMessage;
43 import org.apache.cocoon.forms.datatype.SelectionList;
44 import org.apache.cocoon.forms.datatype.Datatype;
45 import org.apache.cocoon.forms.datatype.StaticSelectionList;
46 import org.apache.cocoon.components.flow.apples.AppleRequest;
47 import org.apache.cocoon.components.flow.apples.AppleResponse;
48
49 import java.util.Locale JavaDoc;
50 import java.util.Map JavaDoc;
51 import java.util.HashMap JavaDoc;
52 import java.lang.reflect.Constructor JavaDoc;
53
54 /**
55  * Generic editor apple for similar entities.
56  */

57 public class AdminEntityEditorApple extends AbstractDaisyApple implements Serviceable {
58     private ServiceManager serviceManager;
59     private AdminLocales adminLocales;
60     private EntityEditor entityEditor;
61     private Repository repository;
62     private Form form;
63     private Binding binding;
64     private Object JavaDoc entity;
65     private boolean init = false;
66     private Locale JavaDoc locale;
67     private Map JavaDoc viewData;
68     private static Map JavaDoc ENTITY_EDITORS;
69     static {
70         ENTITY_EDITORS = new HashMap JavaDoc();
71         try {
72             ENTITY_EDITORS.put("branch", BranchEntityEditor.class.getConstructor(new Class JavaDoc[] { AdminEntityEditorApple.class }));
73             ENTITY_EDITORS.put("language", LanguageEntityEditor.class.getConstructor(new Class JavaDoc[] { AdminEntityEditorApple.class }));
74             ENTITY_EDITORS.put("role", RoleEntityEditor.class.getConstructor(new Class JavaDoc[] { AdminEntityEditorApple.class }));
75             ENTITY_EDITORS.put("user", UserEntityEditor.class.getConstructor(new Class JavaDoc[] { AdminEntityEditorApple.class }));
76             ENTITY_EDITORS.put("collection", CollectionEntityEditor.class.getConstructor(new Class JavaDoc[] { AdminEntityEditorApple.class }));
77             ENTITY_EDITORS.put("partType", PartTypeEntityEditor.class.getConstructor(new Class JavaDoc[] { AdminEntityEditorApple.class }));
78         } catch (Exception JavaDoc e) {
79             throw new RuntimeException JavaDoc("Error initializing entity editor map.", e);
80         }
81     }
82
83     public void service(ServiceManager serviceManager) throws ServiceException {
84         this.serviceManager = serviceManager;
85         adminLocales = (AdminLocales)serviceManager.lookup(AdminLocales.ROLE);
86     }
87
88     protected void processInternal(AppleRequest appleRequest, AppleResponse appleResponse) throws Exception JavaDoc {
89         if (!init) {
90             String JavaDoc resource = appleRequest.getSitemapParameter("resource");
91             Constructor JavaDoc entityEditorConstructor = (Constructor JavaDoc)ENTITY_EDITORS.get(resource);
92             if (entityEditorConstructor == null)
93                 throw new Exception JavaDoc("No editor available for this type of resource: " + resource);
94             else
95                 entityEditor = (EntityEditor)entityEditorConstructor.newInstance(new Object JavaDoc[] { this });
96
97             locale = WikiHelper.getLocale(appleRequest.getCocoonRequest());
98             String JavaDoc lowerCaseEntityName = entityEditor.getEntityName().toLowerCase();
99             form = FormHelper.createForm(serviceManager, "resources/form/" + lowerCaseEntityName + "_definition.xml");
100             binding = FormHelper.createBinding(serviceManager, "resources/form/" + lowerCaseEntityName + "_binding.xml");
101
102             repository = WikiHelper.getRepository(appleRequest.getCocoonRequest(), serviceManager);
103             String JavaDoc entityId = appleRequest.getSitemapParameter("id");
104
105             entityEditor.prepareForm();
106
107             if (entityId != null) {
108                 entity = entityEditor.getEntity(Long.parseLong(entityId));
109                 binding.loadFormFromModel(form, entity);
110             } else {
111                 entityId = "new";
112             }
113
114             String JavaDoc path = getMountPoint() + "/admin/" + entityEditor.getEntityName() + "/" + entityId + "/edit/" + getContinuationId();
115
116             viewData = new HashMap JavaDoc();
117             entityEditor.addViewData(viewData);
118             viewData.put("submitPath", path);
119             if (entity != null)
120                 viewData.put(entityEditor.getEntityName(), entity);
121             viewData.put("locale", locale);
122             viewData.put("pageContext", new PageContext(getMountPoint(), repository, getLayoutType(), getSkin(), SkinConfHelper.getGlobalSkinConf(serviceManager), getContext()));
123             viewData.put("CocoonFormsInstance", form);
124             viewData.put("entityName", lowerCaseEntityName);
125
126             init = true;
127
128             appleResponse.redirectTo(EncodingUtil.encodePath(path));
129         } else {
130             String JavaDoc methodName = appleRequest.getCocoonRequest().getMethod();
131             if (methodName.equals("GET")) {
132                 // display the form
133
appleResponse.sendPage("Form-" + entityEditor.getEntityName().toLowerCase() + "-Pipe", viewData);
134             } else if (methodName.equals("POST")) {
135                 // handle a form submit
136
boolean endProcessing = form.process(new FormContext(appleRequest.getCocoonRequest(), locale));
137
138                 if (!endProcessing) {
139                     appleResponse.sendPage("Form-" + entityEditor.getEntityName().toLowerCase() + "-Pipe", viewData);
140                 } else {
141                     if (entity == null) {
142                         entity = entityEditor.createEntity();
143                         viewData.put(entityEditor.getEntityName(), entity);
144                     }
145
146                     binding.saveFormToModel(form, entity);
147                     entityEditor.saveEntity();
148                     appleResponse.redirectTo(getMountPoint() + "/admin/" + entityEditor.getEntityName());
149                 }
150             } else {
151                 throw new Exception JavaDoc("Unspported HTTP method: " + methodName);
152             }
153         }
154     }
155
156     interface EntityEditor {
157         String JavaDoc getEntityName();
158
159         void prepareForm() throws Exception JavaDoc;
160
161         void addViewData(Map JavaDoc viewData) throws RepositoryException;
162
163         Object JavaDoc getEntity(long id) throws Exception JavaDoc;
164
165         Object JavaDoc createEntity() throws Exception JavaDoc;
166
167         void saveEntity() throws Exception JavaDoc;
168     }
169
170     public class BranchEntityEditor implements EntityEditor {
171         public String JavaDoc getEntityName() {
172             return "branch";
173         }
174
175         public void prepareForm() {
176         }
177
178         public void addViewData(Map JavaDoc viewData) {
179         }
180
181         public Object JavaDoc getEntity(long id) throws Exception JavaDoc {
182             return repository.getVariantManager().getBranch(id, true);
183         }
184
185         public Object JavaDoc createEntity() throws Exception JavaDoc {
186             return repository.getVariantManager().createBranch((String JavaDoc)form.getChild("name").getValue());
187         }
188
189         public void saveEntity() throws Exception JavaDoc {
190             ((Branch)entity).save();
191         }
192     }
193
194     public class LanguageEntityEditor implements EntityEditor {
195         public String JavaDoc getEntityName() {
196             return "language";
197         }
198
199         public void prepareForm() {
200         }
201
202         public void addViewData(Map JavaDoc viewData) {
203         }
204
205         public Object JavaDoc getEntity(long id) throws Exception JavaDoc {
206             return repository.getVariantManager().getLanguage(id, true);
207         }
208
209         public Object JavaDoc createEntity() throws Exception JavaDoc {
210             return repository.getVariantManager().createLanguage((String JavaDoc)form.getChild("name").getValue());
211         }
212
213         public void saveEntity() throws Exception JavaDoc {
214             ((Language)entity).save();
215         }
216     }
217
218     public class RoleEntityEditor implements EntityEditor {
219         public String JavaDoc getEntityName() {
220             return "role";
221         }
222
223         public void prepareForm() {
224         }
225
226         public void addViewData(Map JavaDoc viewData) {
227         }
228
229         public Object JavaDoc getEntity(long id) throws Exception JavaDoc {
230             return repository.getUserManager().getRole(id, true);
231         }
232
233         public Object JavaDoc createEntity() throws Exception JavaDoc {
234             return repository.getUserManager().createRole((String JavaDoc)form.getChild("name").getValue());
235         }
236
237         public void saveEntity() throws Exception JavaDoc {
238             ((Role)entity).save();
239         }
240     }
241
242     public class UserEntityEditor implements EntityEditor {
243         public String JavaDoc getEntityName() {
244             return "user";
245         }
246
247         public Object JavaDoc getEntity(long id) throws Exception JavaDoc {
248             return repository.getUserManager().getUser(id, true);
249         }
250
251         public Object JavaDoc createEntity() throws Exception JavaDoc {
252             return repository.getUserManager().createUser((String JavaDoc)form.getChild("login").getValue());
253         }
254
255         public void saveEntity() throws Exception JavaDoc {
256             ((User)entity).save();
257         }
258
259         public void prepareForm() throws Exception JavaDoc {
260             Role[] roles = repository.getUserManager().getRoles().getArray();
261             ((MultiValueField)form.getChild("roles")).setSelectionList(roles, "id", "name");
262             Field defaultRoleField = (Field)form.getChild("defaultRole");
263             defaultRoleField.setSelectionList(buildRolesSelectionList(roles, defaultRoleField.getDatatype()));
264             Field authSchemeField = (Field)form.getChild("authenticationScheme");
265             authSchemeField.setSelectionList(buildAuthSchemesSelectionList(repository.getUserManager().getAuthenticationSchemes().getArray(), authSchemeField.getDatatype()));
266             authSchemeField.setValue("daisy");
267             form.getChild("password").addValidator(new PasswordRequiredValidator());
268
269             // set UserManager is a form attribute so that the binding can access it
270
form.setAttribute("UserManager", repository.getUserManager());
271
272             if (entity == null) {
273                 form.getChild("confirmed").setValue(Boolean.TRUE);
274             }
275         }
276
277         public void addViewData(Map JavaDoc viewData) throws RepositoryException {
278        }
279
280         SelectionList buildRolesSelectionList(Role[] roles, Datatype dataType) {
281             StaticSelectionList selectionList = new StaticSelectionList(dataType);
282             selectionList.addItem(null, new StringMessage("None (= all)"));
283             for (int i = 0; i < roles.length; i++) {
284                 selectionList.addItem(new Long JavaDoc(roles[i].getId()), new StringMessage(roles[i].getName()));
285             }
286             return selectionList;
287         }
288
289         SelectionList buildAuthSchemesSelectionList(AuthenticationSchemeInfo[] schemes, Datatype dataType) {
290             StaticSelectionList selectionList = new StaticSelectionList(dataType);
291             selectionList.addItem(null, new StringMessage("(select a scheme)"));
292             for (int i = 0; i < schemes.length; i++) {
293                 selectionList.addItem(schemes[i].getName(), new StringMessage(schemes[i].getName() + " -- " + schemes[i].getDescription()));
294             }
295             return selectionList;
296         }
297
298         class PasswordRequiredValidator implements WidgetValidator {
299             public boolean validate(Widget widget) {
300                 Field authSchemeField = (Field)widget.getForm().getChild("authenticationScheme");
301                 if ("daisy".equals(authSchemeField.getValue()) && entity == null && widget.getValue() == null)
302                     ((Field)widget).setValidationError(new ValidationError("Password is required", false));
303                 return false;
304             }
305         }
306     }
307
308     public class CollectionEntityEditor implements EntityEditor {
309         public String JavaDoc getEntityName() {
310             return "collection";
311         }
312
313         public void prepareForm() {
314         }
315
316         public void addViewData(Map JavaDoc viewData) throws RepositoryException {
317         }
318
319         public Object JavaDoc getEntity(long id) throws Exception JavaDoc {
320             return repository.getCollectionManager().getCollection(id, true);
321         }
322
323         public Object JavaDoc createEntity() throws Exception JavaDoc {
324             return repository.getCollectionManager().createCollection((String JavaDoc)form.getChild("name").getValue());
325         }
326
327         public void saveEntity() throws Exception JavaDoc {
328             ((DocumentCollection)entity).save();
329         }
330     }
331
332     public class PartTypeEntityEditor implements EntityEditor {
333         public String JavaDoc getEntityName() {
334             return "partType";
335         }
336
337         public void prepareForm() throws RepositoryException {
338             // initialiaze repeater for displaydata with the locales we allow to be edited
339
String JavaDoc[] supportedLocales = adminLocales.getLocales().getAsStrings();
340             Repeater repeater = (Repeater)form.getChild("displaydata");
341             for (int i = 0; i < supportedLocales.length; i++) {
342                 Repeater.RepeaterRow row = repeater.addRow();
343                 row.getChild("locale").setValue(supportedLocales[i]);
344             }
345
346             // Supply link extractor selection
347
Field linkExtractorField = (Field)form.getChild("linkExtractor");
348             StaticSelectionList selectionList = new StaticSelectionList(linkExtractorField.getDatatype());
349             selectionList.addItem("");
350             LinkExtractorInfo[] extractorInfos = repository.getRepositorySchema().getLinkExtractors().getArray();
351             for (int i = 0; i < extractorInfos.length; i++) {
352                 selectionList.addItem(extractorInfos[i].getName(), new StringMessage(extractorInfos[i].getName() + " -- " + extractorInfos[i].getDescription()));
353             }
354             linkExtractorField.setSelectionList(selectionList);
355         }
356
357         public void addViewData(Map JavaDoc viewData) throws RepositoryException {
358         }
359
360         public Object JavaDoc getEntity(long id) throws Exception JavaDoc {
361             return repository.getRepositorySchema().getPartTypeById(id, true);
362         }
363
364         public Object JavaDoc createEntity() throws Exception JavaDoc {
365             String JavaDoc mimeTypes = (String JavaDoc)form.getChild("mimetypes").getValue();
366             if (mimeTypes == null)
367                 mimeTypes = "";
368             return repository.getRepositorySchema().createPartType((String JavaDoc)form.getChild("name").getValue(), mimeTypes);
369         }
370
371         public void saveEntity() throws Exception JavaDoc {
372             ((PartType)entity).save();
373         }
374     }
375 }
Popular Tags