KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > action > core > contentResource > file > UpdateFileAction


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.file;
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.service.core.ContentResourceManager;
22 import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
23 import com.blandware.atleap.webapp.action.core.BaseAction;
24 import com.blandware.atleap.webapp.form.ContentResourceForm;
25 import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
26 import com.blandware.atleap.webapp.util.core.CacheUtil;
27 import com.blandware.atleap.webapp.util.core.ResourceTypesManager;
28 import com.blandware.atleap.webapp.util.core.WebappConstants;
29 import com.blandware.atleap.webapp.util.core.WebappUtil;
30 import com.blandware.atleap.search.SearchManager;
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 file
49  * </p>
50  * <p><a HREF="UpdateFileAction.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  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
55  * @version $Revision: 1.21 $ $Date: 2006/03/22 11:22:04 $
56  * @struts.action path="/core/contentResource/file/update"
57  * name="contentResourceForm"
58  * scope="request"
59  * input="inputForward"
60  * validate="true"
61  * roles="core-contentResource-update"
62  * @struts.action-forward name="inputForward"
63  * path=".core.contentResource.file.update"
64  * @struts.action-forward name="updateContentResource"
65  * path="/core/contentResource/callUpdate.do"
66  * @struts.action-forward name="listContentResources"
67  * path="/core/contentResource/list.do"
68  * redirect="true"
69  * @struts.action-forward name="callUpdateFile"
70  * path="/core/contentResource/callUpdate.do"
71  * redirect="false"
72  * @struts.action-forward name="viewLinkedObjects"
73  * path="/core/linkedObjects/view.do"
74  * @struts.action-forward name="unsatisfiable"
75  * path="/core/contentResource/list.do"
76  */

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

88     public ActionForward execute(ActionMapping mapping, ActionForm form,
89                                  HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
90         // flag shows whether to force changing of URI if there're some
91
// linked objects
92
boolean force = "true".equalsIgnoreCase(request.getParameter("force"));
93
94         ContentResourceForm contentResourceForm;
95         if (force) {
96             contentResourceForm = (ContentResourceForm) request.getSession().getAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY);
97         } else {
98             contentResourceForm = (ContentResourceForm) form;
99         }
100
101         UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) request.getSession().getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
102         FormFile formFile = null;
103         if ( uploadContentResourceForm != null ) {
104             formFile = uploadContentResourceForm.getFile();
105         }
106
107         Long JavaDoc fileId = null;
108         if ( !GenericValidator.isBlankOrNull(contentResourceForm.getId()) ) {
109             fileId = Long.valueOf(contentResourceForm.getId());
110         } else {
111             if ( log.isWarnEnabled() ) {
112                 log.warn("Missing file ID. Returning to list");
113             }
114             return mapping.findForward("listContentResources");
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, fileId);
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         ContentResource file = contentResourceManager.retrieveContentResource(fileId);
136
137         if ( file == null ) {
138             // file not found. it might be deleted by someone else
139
ActionMessages errors = new ActionMessages();
140             errors.add("fileNotFound", new ActionMessage("core.contentResource.file.errors.notFound"));
141             saveErrors(request, errors);
142             return mapping.findForward("listContentResources");
143         }
144
145         if ( !file.getType().equalsIgnoreCase(Constants.RESOURCE_TYPE_FILE) ) {
146             throw new Exception JavaDoc("Resource must have " + Constants.RESOURCE_TYPE_FILE + " type");
147         }
148
149         String JavaDoc uri = Constants.RESOURCES_URI_PREFIX + contentResourceForm.getUri();
150
151         String JavaDoc oldUri = file.getUri();
152
153         if (!oldUri.equals(uri)) {
154             // check whether there is already another content resource with this URI
155
ContentResource oldResource = contentResourceManager.findContentResourceByUri(uri);
156             if (oldResource != null) {
157                 // content resource already exists
158
ActionMessages errors = new ActionMessages();
159                 errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
160                 saveErrors(request, errors);
161                 saveToken(request);
162                 return mapping.getInputForward();
163             }
164         }
165
166         boolean uriChanged = !oldUri.equals(uri);
167         if (!force && file.isInUse() && uriChanged ) {
168             // trying to change URI of used content resource - display warning
169
String JavaDoc action = mapping.findForward("listContentResources").getPath();
170             String JavaDoc redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
171             request.getSession().setAttribute(WebappConstants.LINKED_OBJECTS_REDIRECT_URL_KEY, redirectUrl);
172             request.getSession().setAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY, contentResourceForm);
173             request.getSession().setAttribute(WebappConstants.LINKED_OBJECT_NEW_URI_KEY, uri);
174             ActionMessages messages = new ActionMessages();
175             messages.add("changeUriWarning", new ActionMessage("core.contentResource.messages.changeUriWarning"));
176             if (file.doUnmodifiableLinkedObjectsExist()) {
177                 messages.add("unmodifiableLinkedObjectsWarning", new ActionMessage("core.contentResource.messages.unmodifiableLinkedObjectsWarning"));
178             }
179             saveMessages(request, messages);
180             request.getSession().removeAttribute(WebappConstants.LINKED_OBJECTS_DELETE_ACTION_KEY);
181             request.getSession().setAttribute(WebappConstants.LINKED_OBJECTS_UPDATE_ACTION_KEY, "core/contentResource/file/update");
182             request.setAttribute(WebappConstants.LINKED_OBJECT_ID_KEY, file.getId());
183             request.setAttribute(WebappConstants.LINKED_OBJECT_TYPE_KEY, "resource");
184             return mapping.findForward("viewLinkedObjects");
185         }
186
187         WebappUtil.copyProperties(file, contentResourceForm, request);
188
189         //setup uri
190
file.setUri(uri);
191
192         // remove links to this resource from unmodifiable menu items
193
if (uriChanged) {
194             for (Iterator JavaDoc i = file.getLinkedMenuItems().iterator(); i.hasNext();) {
195                 MenuItem menuItem = (MenuItem) i.next();
196                 if (!menuItem.isDynamic()) {
197                     i.remove();
198                 }
199             }
200         }
201
202         ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(request.getSession().getServletContext());
203
204         byte[] fileData;
205         String JavaDoc mimeType = null;
206
207         if ( formFile != null && formFile.getFileName() != null && formFile.getFileName().trim().length() > 0 && formFile.getFileSize() > 0 ) {
208             //if file updated
209
fileData = formFile.getFileData();
210             mimeType = resourceTypesManager.getMimeTypeByFileName(formFile.getFileName());
211
212             file.setSize(new Long JavaDoc(fileData.length));
213
214         } else {
215             fileData = file.getResourceData().getData();
216             mimeType = file.getMimeType();
217         }
218
219         CacheUtil cacheUtil = CacheUtil.getInstance(request);
220         try {
221             ResourceData resourceData = file.getResourceData();
222             if ( resourceData != null ) {
223                 resourceData.setData(fileData);
224             } else {
225                 resourceData = new ResourceData(fileData);
226             }
227             file.setMimeType(mimeType);
228             contentResourceManager.updateContentResource(file, resourceData);
229
230             //flush cache
231
cacheUtil.flushResourceCache(oldUri);
232
233             //put into cache
234
CacheUtil.ResourceData rd = new CacheUtil.ResourceData(fileData, mimeType, WebappUtil.rolesToString(file.getRoles()), file.getLastUpdatedDatetime().getTime());
235             cacheUtil.putResourceInCache(rd, uri);
236
237             if (force) {
238                 // reindex and update cache for linked objects, because they
239
// were changed
240
SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
241
242                 // flush cache related to menu items
243
cacheUtil.flushMenuCache();
244
245                 // put linked values in cache and into search index
246
List JavaDoc linkedContentFieldValues = file.getLinkedContentFieldValues();
247                 Set JavaDoc owners = new HashSet JavaDoc();
248                 for (Iterator JavaDoc i = linkedContentFieldValues.iterator(); i.hasNext();) {
249                     ContentFieldValue fieldValue = (ContentFieldValue) i.next();
250                     ContentField field = fieldValue.getContentField();
251                     Localizable owner = field.getOwner();
252                     // put owner to set of owners to cache/reindex them later
253
owners.add(owner);
254
255                     String JavaDoc localeIdentifier = fieldValue.getContentLocale().getIdentifier();
256
257                     byte fieldType = field.getType();
258                     String JavaDoc content = null;
259
260                     if (fieldType == ContentField.LINE_TYPE) {
261                         content = fieldValue.getSimpleValue();
262                     } else {
263                         content = ConvertUtil.convertToString(fieldValue.getValue());
264                     }
265                     if ( owner instanceof Page ) {
266                         Page page = (Page) owner;
267                         CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId());
268                         cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), field.getIdentifier(), localeIdentifier);
269                     }
270                 }
271
272                 // process owners
273
for (Iterator JavaDoc i = owners.iterator(); i.hasNext();) {
274                     Localizable owner = (Localizable) i.next();
275                     if ( owner instanceof Layout ) {
276                         Layout layout = (Layout) owner;
277                         cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());
278
279                         //TODO: add into search index for every content page of the layout.
280
//TODO: add into index action pages
281
List JavaDoc contentPages = layout.getContentPages();
282                         for ( int j = 0; j < contentPages.size(); j++ ) {
283                             ContentPage cp = (ContentPage) contentPages.get(j);
284                             searchManager.reIndexPage(cp, request);
285                             cacheUtil.updateContentPageLastModifiedInCache(cp.getUri());
286                         }
287
288                     } else if ( owner instanceof Page ) {
289                         Page page = (Page) owner;
290                         searchManager.reIndexPage(page, request);
291                         if ( page instanceof ContentPage ) {
292                             cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
293                         }
294                     }
295                 }
296             }
297
298         } catch ( BeanAlreadyExistsException e ) {
299             // file already exists
300
if ( formFile != null ) {
301                 formFile.destroy();
302             }
303             request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
304             ActionMessages errors = new ActionMessages();
305             errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
306             saveErrors(request, errors);
307             saveToken(request);
308             return mapping.getInputForward();
309         } catch ( ObjectOptimisticLockingFailureException e ) {
310             // file was updated or deleted by another transaction
311
ActionMessages errors = new ActionMessages();
312             errors.add("updateFailed", new ActionMessage("core.contentResource.file.errors.updateFailed"));
313             saveErrors(request, errors);
314             return mapping.findForward("callUpdateFile");
315         }
316
317         if ( formFile != null ) {
318             formFile.destroy();
319         }
320         request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
321
322         return mapping.findForward("listContentResources");
323     }
324 }
Popular Tags