KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > action > core > contentResource > document > UpdateDocumentAction


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
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 com.blandware.atleap.webapp.action.core.contentResource.document;
17
18 import com.blandware.atleap.common.Constants;
19 import com.blandware.atleap.common.util.ConvertUtil;
20 import com.blandware.atleap.model.core.*;
21 import com.blandware.atleap.search.SearchManager;
22 import com.blandware.atleap.service.core.ContentResourceManager;
23 import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
24 import com.blandware.atleap.webapp.action.core.BaseAction;
25 import com.blandware.atleap.webapp.form.ContentDocumentForm;
26 import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
27 import com.blandware.atleap.webapp.util.core.CacheUtil;
28 import com.blandware.atleap.webapp.util.core.ResourceTypesManager;
29 import com.blandware.atleap.webapp.util.core.WebappConstants;
30 import com.blandware.atleap.webapp.util.core.WebappUtil;
31 import org.apache.commons.validator.GenericValidator;
32 import org.apache.struts.action.ActionForm;
33 import org.apache.struts.action.ActionForward;
34 import org.apache.struts.action.ActionMapping;
35 import org.apache.struts.action.ActionMessage;
36 import org.apache.struts.action.ActionMessages;
37 import org.apache.struts.upload.FormFile;
38 import org.springframework.orm.ObjectOptimisticLockingFailureException;
39
40 import javax.servlet.http.HttpServletRequest JavaDoc;
41 import javax.servlet.http.HttpServletResponse JavaDoc;
42 import java.util.Iterator JavaDoc;
43 import java.util.List JavaDoc;
44 import java.util.Set JavaDoc;
45 import java.util.HashSet JavaDoc;
46
47 /**
48  * <p>Updates document
49  * </p>
50  * <p><a HREF="UpdateDocumentAction.java.htm"><i>View Source</i></a></p>
51  * <p/>
52  *
53  * @author Andrey Grebnev <a HREF="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
54  * @version $Revision: 1.17 $ $Date: 2006/03/22 11:22:03 $
55  * @struts.action path="/core/contentResource/document/update"
56  * name="contentDocumentForm"
57  * scope="request"
58  * input="inputForward"
59  * validate="true"
60  * roles="core-contentResource-update"
61  * @struts.action-forward name="inputForward"
62  * path=".core.contentResource.document.update"
63  * @struts.action-forward name="updateContentResource"
64  * path="/core/contentResource/callUpdate.do"
65  * @struts.action-forward name="listContentResources"
66  * path="/core/contentResource/list.do"
67  * redirect="true"
68  * @struts.action-forward name="callUpdateDocument"
69  * path="/core/contentResource/callUpdate.do"
70  * redirect="false"
71  * @struts.action-forward name="viewLinkedObjects"
72  * path="/core/linkedObjects/view.do"
73  * @struts.action-forward name="unsatisfiable"
74  * path="/core/contentResource/list.do"
75  */

76 public final class UpdateDocumentAction extends BaseAction {
77
78     /**
79      * @param mapping The ActionMapping used to select this instance
80      * @param form The optional ActionForm bean for this request (if any)
81      * @param request The HTTP request we are proceeding
82      * @param response The HTTP response we are creating
83      * @return an ActionForward instance describing where and how
84      * control should be forwarded, or null if response
85      * has already been completed
86      */

87     public ActionForward execute(ActionMapping mapping, ActionForm form,
88                                  HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
89         // flag shows whether to force changing of URI if there're some
90
// linked objects
91
boolean force = "true".equalsIgnoreCase(request.getParameter("force"));
92
93         ContentDocumentForm documentForm;
94         if (force) {
95             documentForm = (ContentDocumentForm) request.getSession().getAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY);
96         } else {
97             documentForm = (ContentDocumentForm) form;
98         }
99
100         UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) request.getSession().getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
101         FormFile formFile = null;
102         if ( uploadContentResourceForm != null ) {
103             formFile = uploadContentResourceForm.getFile();
104         }
105
106         Long JavaDoc documentId = null;
107         if ( !GenericValidator.isBlankOrNull(documentForm.getId()) ) {
108             documentId = Long.valueOf(documentForm.getId());
109         } else {
110             if ( log.isWarnEnabled() ) {
111                 log.warn("Missing document ID. Returning to list");
112             }
113             return mapping.findForward("listContentResources");
114         }
115
116
117         if (isBackPressed(request)) {
118             if ( formFile != null ) {
119                 formFile.destroy();
120             }
121             request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
122             request.setAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY, documentId);
123             return mapping.findForward("updateContentResource");
124         }
125
126         if ( isCancelled(request) ) {
127             if ( formFile != null ) {
128                 formFile.destroy();
129             }
130             request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
131             return mapping.findForward("listContentResources");
132         }
133
134         ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
135         ContentDocument document = contentResourceManager.retrieveContentDocument(documentId);
136
137         if ( document == null ) {
138             // document not found. it might be deleted by someone else
139
ActionMessages errors = new ActionMessages();
140             errors.add("documentNotFound", new ActionMessage("core.contentResource.document.errors.notFound"));
141             saveErrors(request, errors);
142             return mapping.findForward("listContentResources");
143         }
144
145         if ( !WebappUtil.isCharsetSupported(documentForm.getCharset()) ) {
146             // specified encoding in not supported
147
ActionMessages errors = new ActionMessages();
148             errors.add("notSupportedCharset", new ActionMessage("core.commons.errors.notSupportedCharset", documentForm.getCharset()));
149             saveErrors(request, errors);
150             saveToken(request);
151             return mapping.getInputForward();
152         }
153
154         String JavaDoc uri = Constants.RESOURCES_URI_PREFIX + documentForm.getUri();
155
156         String JavaDoc oldUri = document.getUri();
157
158         if (!oldUri.equals(uri)) {
159             // check whether there is already another content resource with this URI
160
ContentResource oldResource = contentResourceManager.findContentResourceByUri(uri);
161             if (oldResource != null) {
162                 // content resource already exists
163
ActionMessages errors = new ActionMessages();
164                 errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
165                 saveErrors(request, errors);
166                 saveToken(request);
167                 return mapping.getInputForward();
168             }
169         }
170
171         boolean uriChanged = !oldUri.equals(uri);
172         if (!force && document.isInUse() && uriChanged ) {
173             // trying to change URI of used content resource - display warning
174
String JavaDoc action = mapping.findForward("listContentResources").getPath();
175             String JavaDoc redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
176             request.getSession().setAttribute(WebappConstants.LINKED_OBJECTS_REDIRECT_URL_KEY, redirectUrl);
177             request.getSession().setAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY, documentForm);
178             request.getSession().setAttribute(WebappConstants.LINKED_OBJECT_NEW_URI_KEY, uri);
179             request.getSession().setAttribute(WebappConstants.LINKED_OBJECT_CONTENT_LOCALE_ID_KEY, documentForm.getContentLocaleId());
180             request.getSession().setAttribute(WebappConstants.LINKED_OBJECT_CHARSET_KEY, documentForm.getCharset());
181             ActionMessages messages = new ActionMessages();
182             messages.add("changeUriWarning", new ActionMessage("core.contentResource.messages.changeUriWarning"));
183             if (document.doUnmodifiableLinkedObjectsExist()) {
184                 messages.add("unmodifiableLinkedObjectsWarning", new ActionMessage("core.contentResource.messages.unmodifiableLinkedObjectsWarning"));
185             }
186             saveMessages(request, messages);
187             request.getSession().removeAttribute(WebappConstants.LINKED_OBJECTS_DELETE_ACTION_KEY);
188             request.getSession().setAttribute(WebappConstants.LINKED_OBJECTS_UPDATE_ACTION_KEY, "core/contentResource/document/update");
189             request.setAttribute(WebappConstants.LINKED_OBJECT_ID_KEY, document.getId());
190             request.setAttribute(WebappConstants.LINKED_OBJECT_TYPE_KEY, "resource");
191             return mapping.findForward("viewLinkedObjects");
192         }
193
194         WebappUtil.copyProperties(document, documentForm, request);
195
196         //setup uri
197
document.setUri(uri);
198
199         // remove links to this resource from unmodifiable menu items
200
if (uriChanged) {
201             for (Iterator JavaDoc i = document.getLinkedMenuItems().iterator(); i.hasNext();) {
202                 MenuItem menuItem = (MenuItem) i.next();
203                 if (!menuItem.isDynamic()) {
204                     i.remove();
205                 }
206             }
207         }
208
209         ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(request.getSession().getServletContext());
210         CacheUtil cacheUtil = CacheUtil.getInstance(request);
211
212         byte[] documentData;
213         String JavaDoc mimeType = null;
214
215         if ( formFile != null && formFile.getFileName() != null && formFile.getFileName().trim().length() > 0 ) {
216             //if document updated
217
documentData = formFile.getFileData();
218             mimeType = resourceTypesManager.getMimeTypeByFileName(formFile.getFileName());
219             document.setSize(new Long JavaDoc(documentData.length));
220         } else {
221             documentData = document.getResourceData().getData();
222             mimeType = document.getMimeType();
223         }
224
225         try {
226
227             ResourceData resourceData = document.getResourceData();
228             if ( resourceData != null ) {
229                 resourceData.setData(documentData);
230             } else {
231                 resourceData = new ResourceData(documentData);
232             }
233             document.setMimeType(mimeType);
234             contentResourceManager.updateContentDocument(document, resourceData, documentForm.getContentLocaleId());
235
236             //flush cache
237
cacheUtil.flushResourceCache(oldUri);
238
239             //put into cache
240
CacheUtil.ResourceData rd = new CacheUtil.ResourceData(documentData, mimeType, document.getCharset(), WebappUtil.rolesToString(document.getRoles()), document.getLastUpdatedDatetime().getTime());
241             cacheUtil.putResourceInCache(rd, uri);
242
243             //index
244
SearchManager searchManager = SearchManager.getInstance(servlet.getServletContext());
245             searchManager.unIndexDocument(oldUri, request);
246             searchManager.indexDocument(document, request);
247
248             if (force) {
249                 // reindex and update cache for linked objects, because they
250
// were changed
251

252                 // flush cache related to menu items
253
cacheUtil.flushMenuCache();
254
255                 // put linked values in cache and into search index
256
List JavaDoc linkedContentFieldValues = document.getLinkedContentFieldValues();
257                 Set JavaDoc owners = new HashSet JavaDoc();
258                 for (Iterator JavaDoc i = linkedContentFieldValues.iterator(); i.hasNext();) {
259                     ContentFieldValue fieldValue = (ContentFieldValue) i.next();
260                     ContentField field = fieldValue.getContentField();
261                     Localizable owner = field.getOwner();
262                     // put owner to set of owners to cache/reindex them later
263
owners.add(owner);
264
265                     String JavaDoc localeIdentifier = fieldValue.getContentLocale().getIdentifier();
266
267                     byte fieldType = field.getType();
268                     String JavaDoc content = null;
269
270                     if (fieldType == ContentField.LINE_TYPE) {
271                         content = fieldValue.getSimpleValue();
272                     } else {
273                         content = ConvertUtil.convertToString(fieldValue.getValue());
274                     }
275                     if ( owner instanceof Page ) {
276                         Page page = (Page) owner;
277                         CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId());
278                         cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), field.getIdentifier(), localeIdentifier);
279                     }
280                 }
281
282                 // process owners
283
for (Iterator JavaDoc i = owners.iterator(); i.hasNext();) {
284                     Localizable owner = (Localizable) i.next();
285                     if ( owner instanceof Layout ) {
286                         Layout layout = (Layout) owner;
287                         cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());
288
289                         //TODO: add into search index for every content page of the layout.
290
//TODO: add into index action pages
291
List JavaDoc contentPages = layout.getContentPages();
292                         for ( int j = 0; j < contentPages.size(); j++ ) {
293                             ContentPage cp = (ContentPage) contentPages.get(j);
294                             searchManager.reIndexPage(cp, request);
295                             cacheUtil.updateContentPageLastModifiedInCache(cp.getUri());
296                         }
297
298                     } else if ( owner instanceof Page ) {
299                         Page page = (Page) owner;
300                         searchManager.reIndexPage(page, request);
301                         if ( page instanceof ContentPage ) {
302                             cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
303                         }
304                     }
305                 }
306             }
307
308         } catch ( BeanAlreadyExistsException e ) {
309             ActionMessages errors = new ActionMessages();
310             errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
311             saveErrors(request, errors);
312             saveToken(request);
313             return mapping.getInputForward();
314         } catch ( ObjectOptimisticLockingFailureException e ) {
315             // document was updated or deleted by another transaction
316
ActionMessages errors = new ActionMessages();
317             errors.add("updateFailed", new ActionMessage("core.contentResource.document.errors.updateFailed"));
318             saveErrors(request, errors);
319             return mapping.findForward("callUpdateDocument");
320         }
321
322         if ( formFile != null ) {
323             formFile.destroy();
324         }
325         request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
326
327         return mapping.findForward("listContentResources");
328     }
329 }
Popular Tags