KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > action > core > contentFieldValue > CreateOrUpdateContentFieldValueAction


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.contentFieldValue;
17
18 import com.blandware.atleap.common.Constants;
19 import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
20 import com.blandware.atleap.common.util.ConvertUtil;
21 import com.blandware.atleap.model.core.BaseObject;
22 import com.blandware.atleap.model.core.ContentField;
23 import com.blandware.atleap.model.core.ContentFieldValue;
24 import com.blandware.atleap.model.core.ContentPage;
25 import com.blandware.atleap.model.core.ContentResource;
26 import com.blandware.atleap.model.core.Layout;
27 import com.blandware.atleap.model.core.Localizable;
28 import com.blandware.atleap.model.core.Page;
29 import com.blandware.atleap.search.SearchManager;
30 import com.blandware.atleap.service.core.ContentFieldManager;
31 import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
32 import com.blandware.atleap.webapp.action.core.BaseAction;
33 import com.blandware.atleap.webapp.form.core.ContentFieldValueForm;
34 import com.blandware.atleap.webapp.util.core.CacheUtil;
35 import com.blandware.atleap.webapp.util.core.MergeUtil;
36 import com.blandware.atleap.webapp.util.core.WebappConstants;
37 import com.blandware.atleap.webapp.util.core.WebappUtil;
38 import org.apache.commons.validator.GenericValidator;
39 import org.apache.struts.action.ActionForm;
40 import org.apache.struts.action.ActionForward;
41 import org.apache.struts.action.ActionMapping;
42 import org.apache.struts.action.ActionMessage;
43 import org.apache.struts.action.ActionMessages;
44 import org.springframework.orm.ObjectOptimisticLockingFailureException;
45
46 import javax.servlet.http.HttpServletRequest JavaDoc;
47 import javax.servlet.http.HttpServletResponse JavaDoc;
48 import java.io.ByteArrayInputStream JavaDoc;
49 import java.util.ArrayList JavaDoc;
50 import java.util.HashMap JavaDoc;
51 import java.util.HashSet JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.List JavaDoc;
54 import java.util.Map JavaDoc;
55 import java.util.Set JavaDoc;
56
57 /**
58  * <p>Creates or updates content field value
59  * </p>
60  * <p><a HREF="UpdateContentFieldValueAction.java.htm"><i>View Source</i></a></p>
61  * <p/>
62  *
63  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
64  * @author Andrey Grebnev <a HREF="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
65  * @version $Revision: 1.13 $ $Date: 2006/03/10 17:10:18 $
66  * @struts.action path="/core/contentFieldValue/createOrUpdate"
67  * name="contentFieldValueForm"
68  * scope="request"
69  * input="inputForward"
70  * validate="true"
71  * roles="core-contentFieldValue-createOrUpdate"
72  * @struts.action-forward name="inputForward"
73  * path=".core.contentFieldValue.update"
74  * @struts.action-forward name="listContentFieldValues"
75  * path="/core/contentFieldValue/list.do"
76  * redirect="false"
77  * @struts.action-forward name="callCreateOrUpdateContentFieldValue"
78  * path="/core/contentFieldValue/callCreateOrUpdate.do"
79  * redirect="false"
80  * @struts.action-forward name="listContentFields"
81  * path="/core/contentField/list.do"
82  * redirect="false"
83  */

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

94     public ActionForward execute(ActionMapping mapping, ActionForm form,
95                                  HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
96
97         ContentFieldValueForm contentFieldValueForm = (ContentFieldValueForm) form;
98         Long JavaDoc contentFieldId = null;
99         if ( !GenericValidator.isBlankOrNull(contentFieldValueForm.getContentFieldId()) ) {
100             contentFieldId = Long.valueOf(contentFieldValueForm.getContentFieldId());
101         } else if ( request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY) != null ) {
102             contentFieldId = (Long JavaDoc) request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY);
103         } else {
104             if ( log.isWarnEnabled() ) {
105                 log.warn("Missing content field ID. Returning to index...");
106             }
107             return mapping.findForward("admin");
108         }
109
110         request.getSession().setAttribute(WebappConstants.CONTENT_FIELD_ID_KEY, contentFieldId);
111
112         if ( !isCancelled(request) && request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_VALUE_SUBMITTED_ACTION_KEY) == null ) {
113
114             if ( contentFieldValueForm.getIdMap() == null || contentFieldValueForm.getIdMap().isEmpty() ) {
115                 if ( log.isWarnEnabled() ) {
116                     log.warn("Missing content field value ID. Returning to list");
117                 }
118                 return mapping.findForward("listContentFieldValues");
119             }
120
121             request.getSession().setAttribute(WebappConstants.CONTENT_FIELD_VALUE_SUBMITTED_ACTION_KEY, "update");
122
123             ContentFieldManager contentFieldManager = (ContentFieldManager) getBean(Constants.CONTENT_FIELD_MANAGER_BEAN);
124             List JavaDoc existentCFVLocales = new ArrayList JavaDoc();
125             Map JavaDoc alreadyUpdatedValues = new HashMap JavaDoc();
126
127             ContentField contentField = contentFieldManager.retrieveContentField(contentFieldId);
128             if ( contentField == null ) {
129                 // content field not found. it might has already been deleted
130
ActionMessages errors = new ActionMessages();
131                 errors.add("contentFieldNotFound", new ActionMessage("core.contentField.errors.notFound"));
132                 saveErrors(request, errors);
133                 return mapping.findForward("listContentFields");
134             }
135
136             for ( Iterator JavaDoc i = contentFieldValueForm.getIdMap().keySet().iterator(); i.hasNext(); ) {
137                 String JavaDoc localeIdentifier = (String JavaDoc) i.next();
138                 Long JavaDoc cfvId = Long.valueOf((String JavaDoc) contentFieldValueForm.getId(localeIdentifier));
139
140                 // flag to determine what action to perform on CFV: create or update
141
boolean existentCFV = cfvId.longValue() != -1;
142                 ContentFieldValue contentFieldValue = null;
143
144                 if ( existentCFV ) {
145                     contentFieldValue = contentFieldManager.retrieveContentFieldValue(cfvId);
146                 }
147
148                 if ( contentFieldValue == null && !GenericValidator.isBlankOrNull((String JavaDoc) contentFieldValueForm.getValue(localeIdentifier)) ) {
149                     // CFV does not exist: it might has already been deleted or has not been created yet
150
// but value is specified so we must create new
151
contentFieldValue = new ContentFieldValue();
152                     existentCFV = false;
153                 }
154
155                 if ( contentFieldValue != null ) {
156                     String JavaDoc value = (String JavaDoc) contentFieldValueForm.getValue(localeIdentifier);
157                     String JavaDoc newValue = null;
158
159                     if ( contentField.getType() == ContentField.LINE_TYPE ) {
160                         newValue = contentFieldValue.getSimpleValue();
161                         contentFieldValue.setSimpleValue(value);
162                     } else {
163                         newValue = ConvertUtil.convertToString(contentFieldValue.getValue());
164                         contentFieldValue.setValue(ConvertUtil.convertToByteArray(value));
165                         if ( contentField.getType() == ContentField.HTML_TYPE ) {
166                             // get all refs
167
HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
168                             Set JavaDoc refs = new HashSet JavaDoc(extractor.extractAllRefs(new ByteArrayInputStream JavaDoc(ConvertUtil.convertToByteArray(value)), Constants.DEFAULT_ENCODING));
169
170                             List JavaDoc linkedPages = new ArrayList JavaDoc();
171                             List JavaDoc linkedResources = new ArrayList JavaDoc();
172                             for ( Iterator JavaDoc j = refs.iterator(); j.hasNext(); ) {
173                                 String JavaDoc ref = (String JavaDoc) j.next();
174                                 BaseObject refObj = WebappUtil.lookupObject(ref, request.getSession().getServletContext(), request.getContextPath(), request);
175                                 if ( refObj != null ) {
176                                     if ( refObj instanceof ContentResource ) {
177                                         linkedResources.add(refObj);
178                                     } else if ( refObj instanceof Page ) {
179                                         linkedPages.add(refObj);
180                                     }
181                                 }
182                             }
183
184                             contentFieldValue.setLinkedResources(linkedResources);
185                             contentFieldValue.setLinkedPages(linkedPages);
186                         }
187                     }
188
189                     contentFieldValue.setVersion(Long.valueOf((String JavaDoc) contentFieldValueForm.getVersion(localeIdentifier)));
190
191                     try {
192
193                         if ( existentCFV ) {
194                             contentFieldManager.updateContentFieldValue(contentFieldValue, contentFieldId, localeIdentifier);
195                         } else {
196                             contentFieldManager.createContentFieldValue(contentFieldValue, contentFieldId, localeIdentifier);
197                         }
198
199                         // put value in cache and into search index
200
CacheUtil cacheUtil = CacheUtil.getInstance(request);
201                         cacheUtil.flushFieldIndices();
202                         SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
203
204                         Localizable owner = contentField.getOwner();
205                         if ( owner instanceof Layout ) {
206                             Layout layout = (Layout) owner;
207                             cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());
208
209                             //TODO: add into search index for every content page of the layout.
210
//TODO: add into index action pages
211
List JavaDoc contentPages = layout.getContentPages();
212                             for ( int j = 0; j < contentPages.size(); j++ ) {
213                                 ContentPage contentPage = (ContentPage) contentPages.get(j);
214                                 searchManager.reIndexPage(contentPage, request);
215                                 cacheUtil.updateContentPageLastModifiedInCache(contentPage.getUri());
216                             }
217
218                         } else if ( owner instanceof Page ) {
219                             Page page = (Page) owner;
220                             CacheUtil.CFVData cfvData = new CacheUtil.CFVData(value, contentFieldId, contentField.getType(), contentFieldValue.getId());
221                             cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), contentField.getIdentifier(), localeIdentifier);
222                             searchManager.reIndexPage(page, request);
223                             if ( page instanceof ContentPage ) {
224                                 cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
225                             }
226                         }
227
228                     } catch ( BeanAlreadyExistsException e ) {
229                         existentCFVLocales.add(localeIdentifier);
230                     } catch ( ObjectOptimisticLockingFailureException e ) {
231                         String JavaDoc mergedValue = null;
232                         if ( contentField.getType() == ContentField.HTML_TYPE ) {
233                             mergedValue = MergeUtil.mergeHtml(value, newValue);
234                         } else if ( contentField.getType() == ContentField.MULTILINE_TYPE ) {
235                             mergedValue = MergeUtil.mergeText(value, newValue);
236                         } else {
237                             mergedValue = newValue;
238                         }
239
240                         alreadyUpdatedValues.put(localeIdentifier, mergedValue);
241                     }
242                 }
243             }
244
245             request.getSession().removeAttribute(WebappConstants.CONTENT_FIELD_VALUE_SUBMITTED_ACTION_KEY);
246
247             if ( !existentCFVLocales.isEmpty() || !alreadyUpdatedValues.isEmpty() ) {
248                 ActionMessages errors = new ActionMessages();
249                 if ( !existentCFVLocales.isEmpty() ) {
250                     errors.add("existentCFV", new ActionMessage("core.contentFieldValue.errors.alreadyExists", ConvertUtil.convertListToString(existentCFVLocales, ", ")));
251                 }
252                 if ( !alreadyUpdatedValues.isEmpty() ) {
253                     errors.add("alreadyUpdatedCFV", new ActionMessage("core.contentFieldValue.errors.updateFailed", ConvertUtil.convertListToString(new ArrayList JavaDoc(alreadyUpdatedValues.keySet()), ", ")));
254                 }
255                 saveErrors(request, errors);
256                 request.setAttribute(WebappConstants.REDIRECT_URL_KEY, request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY));
257                 if ( !alreadyUpdatedValues.isEmpty() ) {
258                     List JavaDoc selectedLocales = new ArrayList JavaDoc(alreadyUpdatedValues.keySet());
259                     request.setAttribute(WebappConstants.CONTENT_FIELD_VALUE_SELECTED_LOCALES_KEY, selectedLocales);
260                     request.setAttribute(WebappConstants.CONTENT_FIELD_VALUES_MERGED_KEY, alreadyUpdatedValues);
261                     return mapping.findForward("callCreateOrUpdateContentFieldValue");
262                 } else {
263                     return mapping.findForward("listContentFieldValues");
264                 }
265             }
266
267         }
268
269         String JavaDoc requestUrl = (String JavaDoc) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
270         if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
271             request.getSession().removeAttribute(WebappConstants.REDIRECT_URL_KEY);
272             return new ActionForward(requestUrl, true);
273         }
274
275         return mapping.findForward("listContentFieldValues");
276
277     }
278 }
279
Popular Tags