KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > action > core > contentResource > image > UpdateImageAction


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.image;
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.core.ImageForm;
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.ImageUtil;
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 com.blandware.atleap.search.SearchManager;
32 import org.apache.commons.validator.GenericValidator;
33 import org.apache.struts.action.ActionForm;
34 import org.apache.struts.action.ActionForward;
35 import org.apache.struts.action.ActionMapping;
36 import org.apache.struts.action.ActionMessage;
37 import org.apache.struts.action.ActionMessages;
38 import org.apache.struts.upload.FormFile;
39 import org.springframework.orm.ObjectOptimisticLockingFailureException;
40
41 import javax.imageio.IIOImage JavaDoc;
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43 import javax.servlet.http.HttpServletResponse JavaDoc;
44 import java.util.Iterator JavaDoc;
45 import java.util.List JavaDoc;
46 import java.util.Set JavaDoc;
47 import java.util.HashSet JavaDoc;
48
49 /**
50  * <p>Updates image
51  * </p>
52  * <p><a HREF="UpdateImageAction.java.htm"><i>View Source</i></a></p>
53  * <p/>
54  *
55  * @author Andrey Grebnev <a HREF="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
56  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
57  * @version $Revision: 1.21 $ $Date: 2006/03/22 11:22:05 $
58  * @struts.action path="/core/contentResource/image/update"
59  * name="imageForm"
60  * scope="request"
61  * input="inputForward"
62  * validate="true"
63  * roles="core-contentResource-update"
64  * @struts.action-forward name="inputForward"
65  * path=".core.contentResource.image.update"
66  * @struts.action-forward name="updateContentResource"
67  * path="/core/contentResource/callUpdate.do"
68  * @struts.action-forward name="listContentResources"
69  * path="/core/contentResource/list.do"
70  * redirect="true"
71  * @struts.action-forward name="callUpdateImage"
72  * path="/core/contentResource/callUpdate.do"
73  * redirect="false"
74  * @struts.action-forward name="viewLinkedObjects"
75  * path="/core/linkedObjects/view.do"
76  * @struts.action-forward name="unsatisfiable"
77  * path="/core/contentResource/list.do"
78  */

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

90     public ActionForward execute(ActionMapping mapping, ActionForm form,
91                                  HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
92         // flag shows whether to force changing of URI if there're some
93
// linked objects
94
boolean force = "true".equalsIgnoreCase(request.getParameter("force"));
95
96         ImageForm imageForm;
97         if (force) {
98             imageForm = (ImageForm) request.getSession().getAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY);
99         } else {
100             imageForm = (ImageForm) form;
101         }
102
103         UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) request.getSession().getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
104         FormFile formFile = null;
105         if ( uploadContentResourceForm != null ) {
106             formFile = uploadContentResourceForm.getFile();
107         }
108
109         Long JavaDoc imageId = null;
110         if ( !GenericValidator.isBlankOrNull(imageForm.getId()) ) {
111             imageId = Long.valueOf(imageForm.getId());
112         } else {
113             if ( log.isWarnEnabled() ) {
114                 log.warn("Missing image ID. Returning to list");
115             }
116             return mapping.findForward("listContentResources");
117         }
118
119
120         if (isBackPressed(request)) {
121             if ( formFile != null ) {
122                 formFile.destroy();
123             }
124             request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
125             request.setAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY, imageId);
126             return mapping.findForward("updateContentResource");
127         }
128
129         if ( isCancelled(request) ) {
130             if ( formFile != null ) {
131                 formFile.destroy();
132             }
133             request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
134             return mapping.findForward("listContentResources");
135         }
136
137         ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
138         ContentImage image = contentResourceManager.retrieveContentImage(imageId);
139
140         if ( image == null ) {
141             // image not found. it might be deleted by someone else
142
ActionMessages errors = new ActionMessages();
143             errors.add("imageNotFound", new ActionMessage("core.contentResource.image.errors.notFound"));
144             saveErrors(request, errors);
145             return mapping.findForward("listContentResources");
146         }
147
148         String JavaDoc uri = Constants.RESOURCES_URI_PREFIX + imageForm.getUri();
149
150         String JavaDoc oldUri = image.getUri();
151
152         if (!oldUri.equals(uri)) {
153             // check whether there is already another content resource with this URI
154
ContentResource oldResource = contentResourceManager.findContentResourceByUri(uri);
155             if (oldResource != null) {
156                 // content resource already exists
157
ActionMessages errors = new ActionMessages();
158                 errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
159                 saveErrors(request, errors);
160                 saveToken(request);
161                 return mapping.getInputForward();
162             }
163         }
164
165         boolean uriChanged = !oldUri.equals(uri);
166         if (!force && image.isInUse() && uriChanged ) {
167             // trying to change URI of used content resource - display warning
168
String JavaDoc action = mapping.findForward("listContentResources").getPath();
169             String JavaDoc redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
170             request.getSession().setAttribute(WebappConstants.LINKED_OBJECTS_REDIRECT_URL_KEY, redirectUrl);
171             request.getSession().setAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY, imageForm);
172             request.getSession().setAttribute(WebappConstants.LINKED_OBJECT_NEW_URI_KEY, uri);
173             request.getSession().setAttribute(WebappConstants.LINKED_OBJECT_WIDTH_KEY, imageForm.getWidth());
174             request.getSession().setAttribute(WebappConstants.LINKED_OBJECT_HEIGHT_KEY, imageForm.getHeight());
175             ActionMessages messages = new ActionMessages();
176             messages.add("changeUriWarning", new ActionMessage("core.contentResource.messages.changeUriWarning"));
177             if (image.doUnmodifiableLinkedObjectsExist()) {
178                 messages.add("unmodifiableLinkedObjectsWarning", new ActionMessage("core.contentResource.messages.unmodifiableLinkedObjectsWarning"));
179             }
180             saveMessages(request, messages);
181             request.getSession().removeAttribute(WebappConstants.LINKED_OBJECTS_DELETE_ACTION_KEY);
182             request.getSession().setAttribute(WebappConstants.LINKED_OBJECTS_UPDATE_ACTION_KEY, "core/contentResource/image/update");
183             request.setAttribute(WebappConstants.LINKED_OBJECT_ID_KEY, image.getId());
184             request.setAttribute(WebappConstants.LINKED_OBJECT_TYPE_KEY, "resource");
185             return mapping.findForward("viewLinkedObjects");
186         }
187
188         WebappUtil.copyProperties(image, imageForm, request);
189
190         //setup uri
191
image.setUri(uri);
192
193         // remove links to this resource from unmodifiable menu items
194
if (uriChanged) {
195             for (Iterator JavaDoc i = image.getLinkedMenuItems().iterator(); i.hasNext();) {
196                 MenuItem menuItem = (MenuItem) i.next();
197                 if (!menuItem.isDynamic()) {
198                     i.remove();
199                 }
200             }
201         }
202
203         ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(request.getSession().getServletContext());
204         CacheUtil cacheUtil = CacheUtil.getInstance(request);
205
206         byte[] imageData;
207         String JavaDoc mimeType = null;
208         int oldWidth = image.getWidth().intValue();
209         int oldHeight = image.getHeight().intValue();
210
211         if ( formFile != null && formFile.getFileName() != null && formFile.getFileName().trim().length() > 0 ) {
212             //if image updated
213
imageData = formFile.getFileData();
214             mimeType = resourceTypesManager.getMimeTypeByFileName(formFile.getFileName());
215             IIOImage JavaDoc source = ImageUtil.decodeImage(imageData, mimeType);
216             image.setWidth(new Integer JavaDoc(source.getRenderedImage().getWidth()));
217             image.setHeight(new Integer JavaDoc(source.getRenderedImage().getHeight()));
218             image.setSize(new Long JavaDoc(imageData.length));
219         } else {
220             imageData = image.getResourceData().getData();
221             mimeType = image.getMimeType();
222         }
223
224         try {
225             if ( imageForm.isScale() ) {
226                 IIOImage JavaDoc source = ImageUtil.decodeImage(imageData, mimeType);
227                 int maxWidth = Integer.parseInt(imageForm.getScaleWidth());
228                 int maxHeight = Integer.parseInt(imageForm.getScaleHeight());
229                 IIOImage JavaDoc scaled = ImageUtil.scaleToRectangle(source, maxWidth, maxHeight);
230                 try {
231                     imageData = ImageUtil.encodeImage(scaled, mimeType);
232                 } catch ( IllegalArgumentException JavaDoc ex ) {
233                     //cannot encode into original format, try to default
234
mimeType = resourceTypesManager.getDefaultMimeType(image.getType());
235                     imageData = ImageUtil.encodeImage(scaled, mimeType);
236                 }
237                 image.setWidth(new Integer JavaDoc(scaled.getRenderedImage().getWidth()));
238                 image.setHeight(new Integer JavaDoc(scaled.getRenderedImage().getHeight()));
239                 image.setSize(new Long JavaDoc(imageData.length));
240             }
241
242             int newWidth = image.getWidth().intValue();
243             int newHeight = image.getHeight().intValue();
244             // this flag is needed to determine whether to recache/reindex CFVs
245
// that are linked to this image because its sizes will be changed
246
// in <img> tags
247
boolean sizesChanged = oldWidth != newWidth || oldHeight != newHeight;
248
249             ResourceData resourceData = image.getResourceData();
250             if ( resourceData != null ) {
251                 resourceData.setData(imageData);
252             } else {
253                 resourceData = new ResourceData(imageData);
254             }
255             image.setMimeType(mimeType);
256             contentResourceManager.updateContentImage(image, resourceData);
257
258             //flush cache
259
cacheUtil.flushResourceCache(oldUri);
260
261             //put into cache
262
CacheUtil.ResourceData rd = new CacheUtil.ResourceData(imageData, mimeType, WebappUtil.rolesToString(image.getRoles()), image.getLastUpdatedDatetime().getTime());
263             cacheUtil.putResourceInCache(rd, uri);
264
265             if (force) {
266                 // flush cache related to menu items
267
cacheUtil.flushMenuCache();
268             }
269
270             if (force || sizesChanged) {
271                 // reindex and update cache for linked objects, because they
272
// were changed
273
SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
274
275                 // put linked values in cache and into search index
276
List JavaDoc linkedContentFieldValues = image.getLinkedContentFieldValues();
277                 Set JavaDoc owners = new HashSet JavaDoc();
278                 for (Iterator JavaDoc i = linkedContentFieldValues.iterator(); i.hasNext();) {
279                     ContentFieldValue fieldValue = (ContentFieldValue) i.next();
280                     ContentField field = fieldValue.getContentField();
281                     Localizable owner = field.getOwner();
282                     // put owner to set of owners to cache/reindex them later
283
owners.add(owner);
284
285                     String JavaDoc localeIdentifier = fieldValue.getContentLocale().getIdentifier();
286
287                     byte fieldType = field.getType();
288                     String JavaDoc content = null;
289
290                     if (fieldType == ContentField.LINE_TYPE) {
291                         content = fieldValue.getSimpleValue();
292                     } else {
293                         content = ConvertUtil.convertToString(fieldValue.getValue());
294                     }
295                     if ( owner instanceof Page ) {
296                         Page page = (Page) owner;
297                         CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId());
298                         cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), field.getIdentifier(), localeIdentifier);
299                     }
300                 }
301
302                 // process owners
303
for (Iterator JavaDoc i = owners.iterator(); i.hasNext();) {
304                     Localizable owner = (Localizable) i.next();
305                     if ( owner instanceof Layout ) {
306                         Layout layout = (Layout) owner;
307                         cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());
308
309                         //TODO: add into search index for every content page of the layout.
310
//TODO: add into index action pages
311
List JavaDoc contentPages = layout.getContentPages();
312                         for ( int j = 0; j < contentPages.size(); j++ ) {
313                             ContentPage cp = (ContentPage) contentPages.get(j);
314                             searchManager.reIndexPage(cp, request);
315                             cacheUtil.updateContentPageLastModifiedInCache(cp.getUri());
316                         }
317
318                     } else if ( owner instanceof Page ) {
319                         Page page = (Page) owner;
320                         searchManager.reIndexPage(page, request);
321                         if ( page instanceof ContentPage ) {
322                             cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
323                         }
324                     }
325                 }
326             }
327
328         } catch ( BeanAlreadyExistsException e ) {
329             ActionMessages errors = new ActionMessages();
330             errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
331             saveErrors(request, errors);
332             saveToken(request);
333             return mapping.getInputForward();
334         } catch ( ObjectOptimisticLockingFailureException e ) {
335             // image was updated or deleted by another transaction
336
ActionMessages errors = new ActionMessages();
337             errors.add("updateFailed", new ActionMessage("core.contentResource.image.errors.updateFailed"));
338             saveErrors(request, errors);
339             return mapping.findForward("callUpdateImage");
340         }
341
342         if ( formFile != null ) {
343             formFile.destroy();
344         }
345         request.getSession().removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
346
347         return mapping.findForward("listContentResources");
348     }
349 }
Popular Tags