KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > action > news > UpdateNewsItemAction


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.news;
17
18 import com.blandware.atleap.common.Constants;
19 import com.blandware.atleap.common.NewsModuleConstants;
20 import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
21 import com.blandware.atleap.common.util.ConvertUtil;
22 import com.blandware.atleap.model.news.NewsItem;
23 import com.blandware.atleap.search.SearchManager;
24 import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
25 import com.blandware.atleap.service.news.NewsManager;
26 import com.blandware.atleap.webapp.action.core.BaseAction;
27 import com.blandware.atleap.webapp.form.NewsItemForm;
28 import com.blandware.atleap.webapp.util.core.*;
29 import com.blandware.atleap.webapp.util.news.NewsModuleWebConstants;
30 import org.apache.commons.validator.GenericValidator;
31 import org.apache.struts.action.*;
32 import org.springframework.orm.ObjectOptimisticLockingFailureException;
33
34 import javax.servlet.http.HttpServletRequest JavaDoc;
35 import javax.servlet.http.HttpServletResponse JavaDoc;
36 import java.io.ByteArrayInputStream JavaDoc;
37 import java.io.InputStream JavaDoc;
38 import java.util.*;
39
40 /**
41  * <p>Updates news item
42  * </p>
43  * <p><a HREF="UpdateNewsItemAction.java.htm"><i>View Source</i></a></p>
44  * <p/>
45  *
46  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
47  * @author Andrey Grebnev <a HREF="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
48  * @version $Revision: 1.30 $ $Date: 2006/03/16 11:09:42 $
49  * @struts.action path="/news/updateItem"
50  * name="newsItemForm"
51  * scope="request"
52  * input="inputForward"
53  * validate="true"
54  * roles="news-item-update"
55  * @struts.action-forward name="inputForward"
56  * path=".news.updateItemAnnotation"
57  * @struts.action-forward name="listNewsItems"
58  * path="/news/listItems.do"
59  * redirect="true"
60  * @struts.action-forward name="callUpdateItem"
61  * path=".news.updateItem"
62  * @struts.action-forward name="callUpdateNewsItem"
63  * path="/news/callUpdateItem.do"
64  * redirect="false"
65  */

66 public final class UpdateNewsItemAction extends BaseAction {
67     /**
68      * @param mapping The ActionMapping used to select this instance
69      * @param form The optional ActionForm bean for this request (if any)
70      * @param request The HTTP request we are proceeding
71      * @param response The HTTP response we are creating
72      * @return an ActionForward instance describing where and how
73      * control should be forwarded, or null if response
74      * has already been completed
75      */

76     public ActionForward execute(ActionMapping mapping, ActionForm form,
77                                  HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
78
79         NewsItemForm newsItemForm = (NewsItemForm) form;
80         String JavaDoc localesMode = newsItemForm.getLocalesMode();
81
82         if ( isBackPressed(request) ) {
83             // First check, may be session has been invalidated and we need to
84
// fill content locales again
85
if (request.getSession().getAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY) == null) {
86                 List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getAvailableLocales();
87                 request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);
88             }
89
90             // check 'check all' ckeckbox if needed
91
newsItemForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);
92
93             return mapping.findForward("inputForward");
94         }
95
96         if ( isCancelled(request) ) {
97             if ( request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
98                 String JavaDoc redirectUrl = (String JavaDoc) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
99                 ActionForward redirect = new ActionForward(redirectUrl, true);
100                 return redirect;
101             }
102             return mapping.findForward("listNewsItems");
103         }
104
105         if ( request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY) == null ) {
106             request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY, "update");
107
108             Long JavaDoc newsItemId = null;
109             if ( !GenericValidator.isBlankOrNull(newsItemForm.getId()) ) {
110                 newsItemId = Long.valueOf(newsItemForm.getId());
111             } else {
112                 if ( log.isWarnEnabled() ) {
113                     log.warn("Missing news item ID. Returning to list...");
114                 }
115                 return mapping.findForward("listNewsItems");
116             }
117
118             request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY, newsItemId);
119
120             NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);
121             NewsItem newsItem = newsManager.retrieveNewsItem(newsItemId);
122
123             if ( newsItem == null ) {
124                 // newsItem not found. it might be deleted by someone else
125
ActionMessages errors = new ActionMessages();
126                 errors.add("newsItemNotFound", new ActionMessage("news.errors.notFound"));
127                 saveErrors(request, errors);
128                 return mapping.findForward("listNewsItems");
129             }
130
131             Map newAnnotation = newsItem.getAnnotation();
132             Map newBody = newsItem.getBody();
133
134             WebappUtil.copyProperties(newsItem, newsItemForm, request);
135
136             Date publicationDate = newsItem.getPublicationDate();
137
138             // set activity
139
Date today = new Date();
140             if ( publicationDate.compareTo(today) <= 0 ) {
141                 newsItem.setActive(Boolean.TRUE);
142             } else {
143                 newsItem.setActive(Boolean.FALSE);
144             }
145
146 // String localesMode = request.getParameter("localesMode");
147
if (!"current".equalsIgnoreCase(localesMode) && !"all".equalsIgnoreCase(localesMode)) {
148                 localesMode = "selected";
149             }
150
151             Map annotationMap = newsItemForm.getAnnotationMap();
152             Map bodyMap = newsItemForm.getBodyMap();
153             Map annotationCheckedBoxes = newsItemForm.getAnnotationCheckedBoxes();
154             Map bodyCheckedBoxes = newsItemForm.getBodyCheckedBoxes();
155             if ("selected".equalsIgnoreCase(localesMode)) {
156                 for (Iterator i = annotationMap.entrySet().iterator(); i.hasNext();) {
157                     Map.Entry entry = (Map.Entry) i.next();
158                     String JavaDoc localeIdentifier = (String JavaDoc) entry.getKey();
159                     if (annotationCheckedBoxes.get(localeIdentifier) == null) {
160                         // if this locale is not checked, replace annotation with old one
161
annotationMap.put(localeIdentifier, newAnnotation.get(localeIdentifier));
162                     }
163                 }
164                 for (Iterator i = bodyMap.entrySet().iterator(); i.hasNext();) {
165                     Map.Entry entry = (Map.Entry) i.next();
166                     String JavaDoc localeIdentifier = (String JavaDoc) entry.getKey();
167                     if (bodyCheckedBoxes.get(localeIdentifier) == null) {
168                         // if this locale is not checked, replace body with old one
169
bodyMap.put(localeIdentifier, newBody.get(localeIdentifier));
170                     }
171                 }
172             }
173
174             newsItem.setTitle(newsItemForm.getTitleMap());
175             newsItem.setAnnotation(annotationMap);
176             newsItem.setBody(bodyMap);
177             String JavaDoc uri = NewsModuleWebConstants.NEWS_ITEM_URI_PREFIX + "/item" + newsItemForm.getId();
178             newsItem.setUri(uri);
179
180             // get all refs
181
HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
182             Set refs = new HashSet();
183             for ( Iterator i = annotationMap.entrySet().iterator(); i.hasNext(); ) {
184                 Map.Entry entry = (Map.Entry) i.next();
185                 String JavaDoc locale = (String JavaDoc) entry.getKey();
186                 String JavaDoc annotation = (String JavaDoc) entry.getValue();
187                 String JavaDoc body = (String JavaDoc) bodyMap.get(locale);
188                 InputStream JavaDoc annotationIS = new ByteArrayInputStream JavaDoc(ConvertUtil.convertToByteArray(annotation));
189                 refs.addAll(extractor.extractAllRefs(annotationIS, Constants.DEFAULT_ENCODING));
190                 if ( !GenericValidator.isBlankOrNull(body) ) {
191                     InputStream JavaDoc bodyIS = new ByteArrayInputStream JavaDoc(ConvertUtil.convertToByteArray(body));
192                     refs.addAll(extractor.extractAllRefs(bodyIS, Constants.DEFAULT_ENCODING));
193                 }
194             }
195
196             Map linkedObjects = WebappUtil.mapObjectsToRefs(refs, request.getSession().getServletContext(), request.getContextPath());
197
198             try {
199                 newsManager.updateNewsItem(newsItem, linkedObjects);
200
201                 // index news item
202
SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
203                 searchManager.unIndexPage(newsItem.getUri(), request);
204                 if ( newsItem.getActive().booleanValue() ) {
205                     searchManager.indexPage(newsItem, request);
206                 }
207
208                 CacheUtil cacheUtil = CacheUtil.getInstance(request);
209                 cacheUtil.flushLocalizableFieldValueCache(newsItemId);
210
211             } catch ( BeanAlreadyExistsException e ) {
212                 // newsItem already exists
213

214                 // check 'check all' ckeckbox if needed
215
newsItemForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);
216
217                 ActionMessages errors = new ActionMessages();
218                 errors.add("newsItemAlreadyExists", new ActionMessage("errors.newsItemAlreadyExists", uri));
219                 saveErrors(request, errors);
220                 return mapping.getInputForward();
221             } catch ( ObjectOptimisticLockingFailureException e ) {
222                 // news item was updated or deleted by another transaction
223
ActionMessages errors = new ActionMessages();
224                 errors.add("updateFailed", new ActionMessage("news.errors.updateFailed"));
225                 saveErrors(request, errors);
226
227                 // merge annotation
228
Map oldAnnotation = annotationMap;
229                 Map mergedAnnotation = new HashMap();
230                 for ( Iterator i = oldAnnotation.entrySet().iterator(); i.hasNext(); ) {
231                     Map.Entry entry = (Map.Entry) i.next();
232                     String JavaDoc locale = (String JavaDoc) entry.getKey();
233                     String JavaDoc oldValue = (String JavaDoc) entry.getValue();
234                     String JavaDoc newValue = (String JavaDoc) newAnnotation.get(locale);
235                     String JavaDoc mergedValue = MergeUtil.mergeHtml(oldValue, newValue);
236                     mergedAnnotation.put(locale, mergedValue);
237                 }
238                 request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY, mergedAnnotation);
239
240                 // merge body
241
Map oldBody = bodyMap;
242                 Map mergedBody = new HashMap();
243                 for ( Iterator i = oldBody.entrySet().iterator(); i.hasNext(); ) {
244                     Map.Entry entry = (Map.Entry) i.next();
245                     String JavaDoc locale = (String JavaDoc) entry.getKey();
246                     String JavaDoc oldValue = (String JavaDoc) entry.getValue();
247                     String JavaDoc newValue = (String JavaDoc) newBody.get(locale);
248                     String JavaDoc mergedValue = MergeUtil.mergeHtml(oldValue, newValue);
249                     mergedBody.put(locale, mergedValue);
250                 }
251                 request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_BODY_KEY, mergedBody);
252
253                 // check 'check all' ckeckbox if needed
254
newsItemForm.setAllCheckedFlagForAnnotationCheckboxes(request, localesMode);
255
256                 return mapping.findForward("callUpdateNewsItem");
257             }
258         }
259
260         if ( request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
261             String JavaDoc redirectUrl = (String JavaDoc) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
262             ActionForward redirect = new ActionForward(redirectUrl, true);
263             return redirect;
264         }
265
266         return mapping.findForward("listNewsItems");
267     }
268 }
Popular Tags