KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > frontend > CreateDocumentTaskApple


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;
17
18 import org.outerj.daisy.frontend.util.*;
19 import org.outerj.daisy.frontend.components.docbasket.DocumentBasketHelper;
20 import org.outerj.daisy.frontend.components.docbasket.DocumentBasket;
21 import org.outerj.daisy.frontend.components.docbasket.DocumentBasketEntry;
22 import org.outerj.daisy.repository.Repository;
23 import org.outerj.daisy.repository.RepositoryException;
24 import org.outerj.daisy.repository.VariantKey;
25 import org.outerj.daisy.repository.user.Role;
26 import org.outerj.daisy.repository.variant.*;
27 import org.outerj.daisy.doctaskrunner.DocumentTaskManager;
28 import org.outerj.daisy.doctaskrunner.DocumentSelection;
29 import org.outerj.daisy.doctaskrunner.TaskSpecification;
30 import org.outerj.daisy.doctaskrunner.SimpleActionsTaskSpecification;
31 import org.apache.cocoon.components.flow.apples.AppleRequest;
32 import org.apache.cocoon.components.flow.apples.AppleResponse;
33 import org.apache.cocoon.forms.formmodel.*;
34 import org.apache.cocoon.forms.FormContext;
35 import org.apache.cocoon.forms.util.I18nMessage;
36 import org.apache.cocoon.forms.datatype.StaticSelectionList;
37 import org.apache.cocoon.forms.event.ActionListener;
38 import org.apache.cocoon.forms.event.ActionEvent;
39 import org.apache.cocoon.forms.event.ValueChangedListener;
40 import org.apache.cocoon.forms.event.ValueChangedEvent;
41 import org.apache.cocoon.environment.Request;
42 import org.apache.cocoon.ResourceNotFoundException;
43 import org.apache.avalon.framework.service.Serviceable;
44 import org.apache.avalon.framework.service.ServiceManager;
45 import org.apache.avalon.framework.service.ServiceException;
46 import org.outerx.daisy.x10.SearchResultDocument;
47
48 import java.util.*;
49
50 public class CreateDocumentTaskApple extends AbstractDaisyApple implements Serviceable {
51     private ServiceManager serviceManager;
52     private boolean init = false;
53     private Form documentSelectionForm;
54     private boolean documentSelectionOk = false;
55     private Form taskSpecificationForm;
56     private Repository repository;
57     private Locale locale;
58     private Map taskSpecViewData;
59
60     public void service(ServiceManager serviceManager) throws ServiceException {
61         this.serviceManager = serviceManager;
62     }
63
64     protected void processInternal(AppleRequest appleRequest, AppleResponse appleResponse) throws Exception JavaDoc {
65         Request request = appleRequest.getCocoonRequest();
66
67         if (!init) {
68             locale = WikiHelper.getLocale(appleRequest.getCocoonRequest());
69             repository = WikiHelper.getRepository(request, serviceManager);
70
71             if (repository.isInRole("guest") && repository.getActiveRoleIds().length == 1)
72                 throw new Exception JavaDoc("The document task functionality is not available for guest users.");
73
74             // Prepare document selection form
75
documentSelectionForm = FormHelper.createForm(serviceManager, "resources/form/doctask_docselection_definition.xml");
76             documentSelectionForm.getChild("documents").addValidator(KeySetParser.getVariantKeysWidgetValidator(repository.getVariantManager(), false, true));
77             ((Action)documentSelectionForm.getChild("executeQuery")).addActionListener(new ExecuteQueryActionListener());
78
79             // Prepare task specification form
80
taskSpecificationForm = FormHelper.createForm(serviceManager, "resources/form/doctask_taskspec_definition.xml");
81             ((Field)taskSpecificationForm.getChild("tasktype")).addValueChangedListener(new TaskTypeChangedListener());
82             taskSpecificationForm.getChild("description").setValue("(no description)");
83             Field taskTypeField = (Field)taskSpecificationForm.getChild("tasktype");
84             StaticSelectionList taskTypes = new StaticSelectionList(taskTypeField.getDatatype());
85             if (repository.isInRole(Role.ADMINISTRATOR))
86                 taskTypes.addItem("javascript", new I18nMessage("createtaskspec.tasktype-javascript"));
87             taskTypes.addItem("simpleactions", new I18nMessage("createtaskspec.tasktype-simpleactions"));
88             taskTypeField.setSelectionList(taskTypes);
89             taskTypeField.setValue(repository.isInRole(Role.ADMINISTRATOR) ? "javascript" : "simpleactions");
90
91             // Prepare task specification view data
92
taskSpecViewData = new HashMap();
93             taskSpecViewData.put("CocoonFormsInstance", taskSpecificationForm);
94             taskSpecViewData.put("pageContext", new PageContext(getMountPoint(), repository, getLayoutType(), getSkin(), SkinConfHelper.getGlobalSkinConf(serviceManager), getContext()));
95             taskSpecViewData.put("locale", locale);
96             taskSpecViewData.put("collectionsArray", repository.getCollectionManager().getCollections(false).getArray());
97             taskSpecViewData.put("branchesArray", repository.getVariantManager().getAllBranches(false).getArray());
98             taskSpecViewData.put("languagesArray", repository.getVariantManager().getAllLanguages(false).getArray());
99
100             // Check if we should initialize from the document basket
101
String JavaDoc initFromDocBasket = request.getParameter("initFromDocumentBasket");
102             if (initFromDocBasket != null && initFromDocBasket.equalsIgnoreCase("true")) {
103                 DocumentBasket documentBasket = DocumentBasketHelper.getDocumentBasket(request, true);
104                 List entries = documentBasket.getEntries();
105
106                 StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(70 * entries.size());
107                 buffer.append("#\n# Entries added from your document basket.\n#");
108
109                 Iterator entriesIt = entries.iterator();
110                 while (entriesIt.hasNext()) {
111                     DocumentBasketEntry entry = (DocumentBasketEntry)entriesIt.next();
112                     buffer.append('\n').append(entry.getDocumentId()).append(',')
113                             .append(entry.getBranch()).append(',').append(entry.getLanguage())
114                             .append(" # ").append(entry.getDocumentName());
115                 }
116                 documentSelectionForm.getChild("documents").setValue(buffer.toString());
117             }
118
119
120             init = true;
121             appleResponse.redirectTo(getDocumentSelectionPath());
122             return;
123         }
124
125         String JavaDoc resource = appleRequest.getSitemapParameter("resource");
126         if (resource == null) {
127             throw new Exception JavaDoc("Missing 'resource' sitemap parameter.");
128         } else if (resource.equals("documentSelection")) {
129             if (request.getMethod().equals("GET")) {
130                 // display document selection form
131
showDocumentSelectionForm(appleResponse);
132             } else if (request.getMethod().equals("POST")) {
133                 boolean finished = documentSelectionForm.process(new FormContext(request, locale));
134                 if (finished) {
135                     documentSelectionOk = true;
136                     appleResponse.redirectTo(getTaskSpecificationPath());
137                 } else {
138                     documentSelectionOk = false;
139                     showDocumentSelectionForm(appleResponse);
140                 }
141             } else {
142                 throw new HttpMethodNotAllowedException(request.getMethod());
143             }
144         } else if (resource.equals("taskSpecification")) {
145             if (!documentSelectionOk) {
146                 appleResponse.redirectTo(getDocumentSelectionPath());
147             } else if (request.getMethod().equals("GET")) {
148                 showTaskSpecificationForm(appleResponse);
149             } else if (request.getMethod().equals("POST")) {
150                 boolean finished = taskSpecificationForm.process(new FormContext(request, locale));
151                 if (finished) {
152                     String JavaDoc documentKeys = (String JavaDoc)documentSelectionForm.getChild("documents").getValue();
153                     VariantKey[] variantKeys = KeySetParser.parseVariantKeys(documentKeys, repository.getVariantManager(), false, true);
154                     DocumentTaskManager taskManager = (DocumentTaskManager)repository.getExtension("DocumentTaskManager");
155                     DocumentSelection documentSelection = taskManager.createEnumerationDocumentSelection(variantKeys);
156                     TaskSpecification taskSpecification = createTaskSpecification();
157                     long taskId = taskManager.runTask(documentSelection, taskSpecification);
158
159                     Map viewData = new HashMap();
160                     viewData.put("taskId", String.valueOf(taskId));
161                     viewData.put("pageContext", new PageContext(getMountPoint(), repository, getLayoutType(), getSkin(), SkinConfHelper.getGlobalSkinConf(serviceManager), getContext()));
162                     appleResponse.sendPage("TaskCreatedPipe", viewData);
163                 } else if (taskSpecificationForm.getSubmitWidget() != null && taskSpecificationForm.getSubmitWidget().getId().equals("back")) {
164                     appleResponse.redirectTo(getDocumentSelectionPath());
165                 } else {
166                     showTaskSpecificationForm(appleResponse);
167                 }
168             } else {
169                 throw new HttpMethodNotAllowedException(request.getMethod());
170             }
171
172         } else {
173             throw new ResourceNotFoundException(resource);
174         }
175
176     }
177
178     private void showDocumentSelectionForm(AppleResponse appleResponse) throws Exception JavaDoc {
179         Map viewData = new HashMap();
180         viewData.put("CocoonFormsInstance", documentSelectionForm);
181         viewData.put("pageContext", new PageContext(getMountPoint(), repository, getLayoutType(), getSkin(), SkinConfHelper.getGlobalSkinConf(serviceManager), getContext()));
182         viewData.put("locale", locale);
183         appleResponse.sendPage("Form-doctask_docselection-Pipe", viewData);
184     }
185
186     private void showTaskSpecificationForm(AppleResponse appleResponse) {
187         appleResponse.sendPage("Form-doctask_taskspec-Pipe", taskSpecViewData);
188     }
189
190     private String JavaDoc getDocumentSelectionPath() {
191         return getMountPoint() + "/doctask/new/" + getContinuationId() + "/documentSelection";
192     }
193
194     private String JavaDoc getTaskSpecificationPath() {
195         return getMountPoint() + "/doctask/new/" + getContinuationId() + "/taskSpecification";
196     }
197
198     private TaskSpecification createTaskSpecification() throws Exception JavaDoc {
199         DocumentTaskManager taskManager = (DocumentTaskManager)repository.getExtension("DocumentTaskManager");
200         String JavaDoc description = (String JavaDoc)taskSpecificationForm.getChild("description").getValue();
201         boolean stopOnFirstError = ((Boolean JavaDoc)taskSpecificationForm.getChild("stopOnFirstError").getValue()).booleanValue();
202         String JavaDoc taskType = (String JavaDoc)taskSpecificationForm.getChild("tasktype").getValue();
203         if (taskType.equals("javascript")) {
204             String JavaDoc script = (String JavaDoc)taskSpecificationForm.lookupWidget("taskParamsUnion/javascript/script").getValue();
205             return taskManager.createTaskSpecification(description, script, "javascript", stopOnFirstError);
206         } else if (taskType.equals("simpleactions")) {
207             SimpleActionsTaskSpecification spec = taskManager.createSimpleActionsTaskSpecification(description, stopOnFirstError);
208             Repeater actionRepeater = (Repeater)taskSpecificationForm.lookupWidget("taskParamsUnion/simpleactions/actions");
209             for (int i = 0; i < actionRepeater.getSize(); i++) {
210                 Repeater.RepeaterRow row = actionRepeater.getRow(i);
211                 String JavaDoc actionType = (String JavaDoc)row.getChild("actiontype").getValue();
212                 Union actionUnion = (Union)row.getChild("actionsUnion");
213                 if (actionType.equals("createVariant")) {
214                     Group createVariantGroup = (Group)actionUnion.getChild("createVariant");
215                     String JavaDoc newBranch = createVariantGroup.getChild("newBranchId").getValue().toString();
216                     String JavaDoc newLanguage = createVariantGroup.getChild("newLanguageId").getValue().toString();
217                     String JavaDoc startVersion = (String JavaDoc)createVariantGroup.getChild("startVersion").getValue();
218                     spec.addCreateVariant(startVersion, newBranch, newLanguage);
219                 } else if (actionType.equals("deleteVariant")) {
220                     spec.addDeleteVariant();
221                 } else if (actionType.equals("addToCollection")) {
222                     Group addToCollectionGroup = (Group)actionUnion.getChild("addToCollection");
223                     String JavaDoc collection = addToCollectionGroup.getChild("collection").getValue().toString();
224                     spec.addAddToCollection(collection);
225                 } else if (actionType.equals("removeFromCollection")) {
226                     Group removeFromCollectionGroup = (Group)actionUnion.getChild("removeFromCollection");
227                     String JavaDoc collection = removeFromCollectionGroup.getChild("collection").getValue().toString();
228                     spec.addRemoveFromCollection(collection);
229                 } else {
230                     throw new Exception JavaDoc("Encountered unsupported simple action: " + actionType);
231                 }
232                 spec.setValidateOnSave(((Boolean JavaDoc)taskSpecificationForm.lookupWidget("taskParamsUnion/simpleactions/validateOnSave").getValue()).booleanValue());
233             }
234             return spec;
235         } else {
236             throw new Exception JavaDoc("Encountered unsupported task type: " + taskType);
237         }
238     }
239
240     class ExecuteQueryActionListener implements ActionListener {
241         public void actionPerformed(ActionEvent event) {
242             Field queryField = (Field)documentSelectionForm.getChild("query");
243             String JavaDoc query = (String JavaDoc)queryField.getValue();
244             if (query == null) {
245                 ((Messages)documentSelectionForm.getChild("messages")).addMessage(new I18nMessage("createdocsel.no-query-entered"));
246             } else {
247                 SearchResultDocument searchResultDocument;
248                 try {
249                     searchResultDocument = repository.getQueryManager().performQuery(query, locale);
250                 } catch (RepositoryException e) {
251                     ((Messages)documentSelectionForm.getChild("messages")).addMessage(new I18nMessage("createdocsel.error-performing-query"));
252                     return;
253                 }
254                 SearchResultDocument.SearchResult.Rows.Row[] rows = searchResultDocument.getSearchResult().getRows().getRowArray();
255                 if (rows.length > 0) {
256                     VariantManager variantManager = repository.getVariantManager();
257                     String JavaDoc currentValue = (String JavaDoc)documentSelectionForm.getChild("documents").getValue();
258                     StringBuffer JavaDoc newValue;
259                     if (currentValue != null) {
260                         newValue = new StringBuffer JavaDoc(currentValue);
261                         newValue.append('\n');
262                     } else {
263                         newValue = new StringBuffer JavaDoc();
264                     }
265
266                     newValue.append("#\n");
267                     newValue.append("# Documents added as result of the following query:\n");
268                     newValue.append("# ").append(query).append('\n');
269                     newValue.append("#\n");
270                     for (int i = 0; i < rows.length; i++) {
271                         newValue.append(rows[i].getDocumentId());
272                         newValue.append(',');
273                         String JavaDoc branchName;
274                         try {
275                             branchName = variantManager.getBranch(rows[i].getBranchId(), false).getName();
276                         } catch (RepositoryException e) {
277                             branchName = String.valueOf(rows[i].getBranchId());
278                         }
279                         newValue.append(branchName);
280                         newValue.append(',');
281                         String JavaDoc languageName;
282                         try {
283                             languageName = variantManager.getLanguage(rows[i].getLanguageId(), false).getName();
284                         } catch (RepositoryException e) {
285                             languageName = String.valueOf(rows[i].getLanguageId());
286                         }
287                         newValue.append(languageName);
288                         newValue.append(" # ");
289                         newValue.append(rows[i].getValueArray(0));
290                         newValue.append('\n');
291                     }
292                     documentSelectionForm.getChild("documents").setValue(newValue.toString());
293                     ((Messages)documentSelectionForm.getChild("messages")).addMessage(new I18nMessage("createdocsel.query-executed", new String JavaDoc[] {String.valueOf(rows.length)}));
294                 } else {
295                     ((Messages)documentSelectionForm.getChild("messages")).addMessage(new I18nMessage("createdocsel.query-no-result"));
296                 }
297             }
298         }
299     }
300
301     class TaskTypeChangedListener implements ValueChangedListener {
302         public void valueChanged(ValueChangedEvent event) {
303             String JavaDoc taskType = (String JavaDoc)event.getNewValue();
304             if ("javascript".equals(taskType)) {
305                 Field scriptField = (Field)taskSpecificationForm.lookupWidget("taskParamsUnion/javascript/script");
306                 if (scriptField.getValue() == null) {
307                     String JavaDoc sampleScript = "var document = repository.getDocument(variantKey, true);\n"
308                         + "document.setCustomField('myfield', 'myvalue');\n"
309                         + "document.save();";
310                     scriptField.setValue(sampleScript);
311                 }
312             }
313         }
314     }
315 }
316
Popular Tags