KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > content > ContentManagementServices


1 /*
2  * $Id: ContentManagementServices.java 7074 2006-03-25 00:04:33Z jonesde $
3  *
4  * Copyright (c) 2003-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.content;
25
26 import java.sql.Timestamp JavaDoc;
27 import java.util.Calendar JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.HashSet JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37 import javax.servlet.http.HttpSession JavaDoc;
38
39 import org.ofbiz.base.util.Debug;
40 import org.ofbiz.base.util.UtilDateTime;
41 import org.ofbiz.base.util.UtilMisc;
42 import org.ofbiz.base.util.UtilValidate;
43 import org.ofbiz.base.util.StringUtil;
44 import org.ofbiz.base.util.cache.UtilCache;
45 import org.ofbiz.content.content.ContentServices;
46 import org.ofbiz.content.content.ContentWorker;
47 import org.ofbiz.entity.GenericDelegator;
48 import org.ofbiz.entity.GenericEntityException;
49 import org.ofbiz.entity.GenericPK;
50 import org.ofbiz.entity.GenericValue;
51 import org.ofbiz.entity.condition.EntityCondition;
52 import org.ofbiz.entity.condition.EntityConditionList;
53 import org.ofbiz.entity.condition.EntityExpr;
54 import org.ofbiz.entity.condition.EntityOperator;
55 import org.ofbiz.entity.model.ModelUtil;
56 import org.ofbiz.entity.util.ByteWrapper;
57 import org.ofbiz.entity.util.EntityUtil;
58 import org.ofbiz.security.Security;
59 import org.ofbiz.service.DispatchContext;
60 import org.ofbiz.service.GenericServiceException;
61 import org.ofbiz.service.LocalDispatcher;
62 import org.ofbiz.service.ModelService;
63 import org.ofbiz.service.ServiceAuthException;
64 import org.ofbiz.service.ServiceUtil;
65
66 /**
67  * ContentManagementServices Class
68  *
69  * @author <a HREF="mailto:byersa@automationgroups.com">Al Byers</a>
70  * @version $Rev: 7074 $
71  * @since 3.0
72  */

73 public class ContentManagementServices {
74
75     public static final String JavaDoc module = ContentManagementServices.class.getName();
76
77     /**
78      * getSubContent
79      * Finds the related subContent given the template Content and the mapKey.
80      * This service calls a same-named method in ContentWorker to do the work.
81      */

82     public static Map JavaDoc getSubContent(DispatchContext dctx, Map JavaDoc context) {
83         //Security security = dctx.getSecurity();
84
GenericDelegator delegator = dctx.getDelegator();
85         //LocalDispatcher dispatcher = dctx.getDispatcher();
86
String JavaDoc contentId = (String JavaDoc) context.get("contentId");
87         String JavaDoc subContentId = (String JavaDoc) context.get("subContentId");
88         String JavaDoc mapKey = (String JavaDoc) context.get("mapKey");
89         GenericValue userLogin = (GenericValue)context.get("userLogin");
90         Timestamp JavaDoc fromDate = (Timestamp JavaDoc)context.get("fromDate");
91         List JavaDoc assocTypes = (List JavaDoc) context.get("assocTypes");
92         String JavaDoc assocTypesString = (String JavaDoc)context.get("assocTypesString");
93         if (UtilValidate.isNotEmpty(assocTypesString)) {
94             List JavaDoc lst = StringUtil.split(assocTypesString, "|");
95             if (assocTypes == null) {
96                 assocTypes = new ArrayList JavaDoc();
97             }
98             assocTypes.addAll(lst);
99         }
100         GenericValue content = null;
101         GenericValue view = null;
102
103         try {
104             view = ContentWorker.getSubContentCache( delegator, contentId, mapKey, subContentId, userLogin, assocTypes, fromDate, new Boolean JavaDoc(false), null);
105             content = ContentWorker.getContentFromView(view);
106         } catch(GenericEntityException e) {
107             return ServiceUtil.returnError(e.getMessage());
108         }
109
110         Map JavaDoc results = ServiceUtil.returnSuccess();
111         results.put("view", view);
112         results.put("content", content);
113         return results;
114     }
115
116     /**
117      * getContent
118      * This service calls a same-named method in ContentWorker to do the work.
119      */

120     public static Map JavaDoc getContent(DispatchContext dctx, Map JavaDoc context) {
121         //Security security = dctx.getSecurity();
122
GenericDelegator delegator = dctx.getDelegator();
123         String JavaDoc contentId = (String JavaDoc) context.get("contentId");
124         //GenericValue userLogin = (GenericValue)context.get("userLogin");
125
GenericValue view = null;
126
127         try {
128             view = ContentWorker.getContentCache( delegator, contentId);
129         } catch(GenericEntityException e) {
130             return ServiceUtil.returnError(e.getMessage());
131         }
132
133         Map JavaDoc results = ServiceUtil.returnSuccess();
134         results.put("view", view);
135         return results;
136     }
137
138     /**
139      * addMostRecent
140      * A service for adding the most recently used of an entity class to the cache.
141      * Entities make it to the most recently used list primarily by being selected for editing,
142      * either by being created or being selected from a list.
143      */

144     public static Map JavaDoc addMostRecent(DispatchContext dctx, Map JavaDoc context) {
145         //Security security = dctx.getSecurity();
146
//GenericDelegator delegator = dctx.getDelegator();
147
//LocalDispatcher dispatcher = dctx.getDispatcher();
148
//HttpServletRequest request = (HttpServletRequest)context.get("request");
149
//String suffix = (String) context.get("suffix");
150
GenericValue val = (GenericValue)context.get("pk");
151         GenericPK pk = val.getPrimaryKey();
152         HttpSession JavaDoc session = (HttpSession JavaDoc)context.get("session");
153
154         ContentManagementWorker.mruAdd(session, pk);
155         return ServiceUtil.returnSuccess();
156     }
157
158
159     /**
160      * persistContentAndAssoc
161      * A combination method that will create or update all or one of the following
162      * a Content entity, a ContentAssoc related to the Content and
163      * the ElectronicText that may be associated with the Content.
164      * The keys for determining if each entity is created is the presence
165      * of the contentTypeId, contentAssocTypeId and dataResourceTypeId.
166      * This service tries to handle DataResource and ContentAssoc fields with and
167      * without "dr" and "ca" prefixes.
168      * Assumes binary data is always in field, "imageData".
169      */

170     public static Map JavaDoc persistContentAndAssoc(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException {
171         GenericDelegator delegator = dctx.getDelegator();
172         LocalDispatcher dispatcher = dctx.getDispatcher();
173         
174         // Knowing why a request fails permission check is one of the more difficult
175
// aspects of content management. Setting "displayFailCond" to true will
176
// put an html table in result.errorMessage that will show what tests were performed
177
Boolean JavaDoc bDisplayFailCond = (Boolean JavaDoc)context.get("displayFailCond");
178         String JavaDoc mapKey = (String JavaDoc) context.get("mapKey");
179         
180         // If "deactivateExisting" is set, other Contents that are tied to the same
181
// contentIdTo will be deactivated (thruDate set to now)
182
String JavaDoc deactivateExisting = (String JavaDoc) context.get("deactivateExisting");
183         if (UtilValidate.isEmpty(deactivateExisting)) {
184             if (UtilValidate.isEmpty(mapKey))
185                 deactivateExisting = "false";
186             else
187                 deactivateExisting = "true";
188         }
189         if (Debug.infoOn()) Debug.logInfo("in persist... mapKey(0):" + mapKey, null);
190
191         // ContentPurposes can get passed in as a delimited string or a list. Combine.
192
List JavaDoc contentPurposeList = (List JavaDoc)context.get("contentPurposeList");
193         if (contentPurposeList == null)
194             contentPurposeList = new ArrayList JavaDoc();
195         String JavaDoc contentPurposeString = (String JavaDoc) context.get("contentPurposeString");
196         if (UtilValidate.isNotEmpty(contentPurposeString)) {
197             List JavaDoc tmpPurposes = StringUtil.split(contentPurposeString, "|");
198             contentPurposeList.addAll(tmpPurposes);
199         }
200         if (contentPurposeList != null ) {
201             context.put("contentPurposeList", contentPurposeList);
202             context.put("contentPurposeString", null);
203         }
204         if (Debug.infoOn()) Debug.logInfo("in persist... contentPurposeList(0):" + contentPurposeList, null);
205         if (Debug.infoOn()) Debug.logInfo("in persist... textData(0):" + context.get("textData"), null);
206         
207
208         GenericValue content = delegator.makeValue("Content", null);
209         content.setPKFields(context);
210         content.setNonPKFields(context);
211         String JavaDoc contentId = (String JavaDoc) content.get("contentId");
212         String JavaDoc contentTypeId = (String JavaDoc) content.get("contentTypeId");
213         String JavaDoc origContentId = (String JavaDoc) content.get("contentId");
214         String JavaDoc origDataResourceId = (String JavaDoc) content.get("dataResourceId");
215         if (Debug.infoOn()) Debug.logInfo("in persist... contentId(0):" + contentId, null);
216
217         GenericValue dataResource = delegator.makeValue("DataResource", null);
218         dataResource.setPKFields(context);
219         dataResource.setNonPKFields(context);
220         dataResource.setAllFields(context, false, "dr", null);
221         context.putAll(dataResource);
222         String JavaDoc dataResourceId = (String JavaDoc) dataResource.get("dataResourceId");
223         String JavaDoc dataResourceTypeId = (String JavaDoc) dataResource.get("dataResourceTypeId");
224         if (Debug.infoOn()) Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, null);
225
226         GenericValue contentAssoc = delegator.makeValue("ContentAssoc", null);
227         contentAssoc.setPKFields(context);
228         contentAssoc.setNonPKFields(context);
229         contentAssoc.setAllFields(context, false, "ca", null);
230         context.putAll(contentAssoc);
231
232         GenericValue electronicText = delegator.makeValue("ElectronicText", null);
233         electronicText.setPKFields(context);
234         electronicText.setNonPKFields(context);
235         
236         // save expected primary keys on result now in case there is no operation that uses them
237
Map JavaDoc results = ServiceUtil.returnSuccess();
238         results.put("contentId", content.get("contentId"));
239         results.put("dataResourceId", dataResource.get("dataResourceId"));
240         results.put("contentIdTo", contentAssoc.get("contentIdTo"));
241         results.put("fromDate", contentAssoc.get("fromDate"));
242         results.put("contentAssocTypeId", contentAssoc.get("contentAssocTypeId"));
243         results.put("drDataResourceId", dataResource.get("dataResourceId"));
244         results.put("caContentIdTo", contentAssoc.get("contentIdTo"));
245         results.put("caFromDate", contentAssoc.get("fromDate"));
246         results.put("caContentAssocTypeId", contentAssoc.get("contentAssocTypeId"));
247         
248         // get user info for multiple use
249
GenericValue userLogin = (GenericValue) context.get("userLogin");
250
251         // TODO: DEJ20060221 Should these be used somewhere?
252
//String textData = (String)electronicText.get("textData");
253

254         //String userLoginId = (String)userLogin.get("userLoginId");
255

256         //String createdByUserLogin = userLoginId;
257
//String lastModifiedByUserLogin = userLoginId;
258
//Timestamp createdDate = UtilDateTime.nowTimestamp();
259
//Timestamp lastModifiedDate = UtilDateTime.nowTimestamp();
260

261         // Do update and create permission checks on DataResource if warranted.
262
//boolean updatePermOK = false;
263
//boolean createPermOK = false;
264

265
266         boolean dataResourceExists = true;
267         if (Debug.infoOn()) Debug.logInfo("in persist... dataResourceTypeId(0):" + dataResourceTypeId, null);
268         if (UtilValidate.isNotEmpty(dataResourceTypeId) ) {
269             Map JavaDoc dataResourceResult = new HashMap JavaDoc();
270             try {
271                 dataResourceResult = persistDataResourceAndDataMethod(dctx, context);
272             } catch (GenericServiceException e) {
273                 return ServiceUtil.returnError(e.getMessage());
274             } catch (GenericEntityException e) {
275                 return ServiceUtil.returnError(e.getMessage());
276             } catch (Exception JavaDoc e) {
277                 return ServiceUtil.returnError(e.getMessage());
278             }
279             String JavaDoc errorMsg = ServiceUtil.getErrorMessage(dataResourceResult);
280             if (UtilValidate.isNotEmpty(errorMsg)) {
281                 return ServiceUtil.returnError(errorMsg);
282             }
283             dataResourceId = (String JavaDoc)dataResourceResult.get("dataResourceId");
284             results.put("dataResourceId", dataResourceId);
285             results.put("drDataResourceId", dataResourceId);
286             context.put("dataResourceId", dataResourceId);
287             content.put("dataResourceId", dataResourceId);
288             context.put("drDataResourceId", dataResourceId);
289         }
290         // Do update and create permission checks on Content if warranted.
291

292         context.put("skipPermissionCheck", null); // Force check here
293
boolean contentExists = true;
294         if (Debug.infoOn()) Debug.logInfo("in persist... contentTypeId" + contentTypeId + " dataResourceTypeId:" + dataResourceTypeId + " contentId:" + contentId + " dataResourceId:" + dataResourceId, null);
295         if (UtilValidate.isNotEmpty(contentTypeId) ) {
296             if (UtilValidate.isEmpty(contentId)) {
297                 contentExists = false;
298             } else {
299                 try {
300                     GenericValue val = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
301                     if (val == null) contentExists = false;
302                 } catch(GenericEntityException e) {
303                     return ServiceUtil.returnError(e.getMessage());
304                 }
305             }
306             //List targetOperations = new ArrayList();
307
//context.put("targetOperations", targetOperations);
308
context.putAll(content);
309             if (contentExists) {
310                 //targetOperations.add("CONTENT_UPDATE");
311
Map JavaDoc contentContext = new HashMap JavaDoc();
312                 ModelService contentModel = dispatcher.getDispatchContext().getModelService("updateContent");
313                 contentContext.putAll(contentModel.makeValid(context, "IN"));
314                 contentContext.put("userLogin", userLogin);
315                 contentContext.put("displayFailCond", bDisplayFailCond);
316                 contentContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
317                 Map JavaDoc thisResult = dispatcher.runSync("updateContent", contentContext);
318                 if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
319                     return ServiceUtil.returnError("Error updating content (updateContent) in persistContentAndAssoc", null, null, thisResult);
320                 }
321                 //Map thisResult = ContentServices.updateContentMethod(dctx, context);
322
} else {
323                 //targetOperations.add("CONTENT_CREATE");
324
Map JavaDoc contentContext = new HashMap JavaDoc();
325                 ModelService contentModel = dispatcher.getDispatchContext().getModelService("createContent");
326                 contentContext.putAll(contentModel.makeValid(context, "IN"));
327                 contentContext.put("userLogin", userLogin);
328                 contentContext.put("displayFailCond", bDisplayFailCond);
329                 contentContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
330                 Debug.logInfo("In persistContentAndAssoc calling createContent with content: " + contentContext, module);
331                 Map JavaDoc thisResult = dispatcher.runSync("createContent", contentContext);
332                 if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
333                     return ServiceUtil.returnError("Error creating content (createContent) in persistContentAndAssoc", null, null, thisResult);
334                 }
335                 //Map thisResult = ContentServices.createContentMethod(dctx, context);
336

337                 contentId = (String JavaDoc) thisResult.get("contentId");
338             }
339             results.put("contentId", contentId);
340             context.put("contentId", contentId);
341             context.put("caContentId", contentId);
342
343         
344
345             // Add ContentPurposes if this is a create operation
346
if (contentId != null && !contentExists) {
347                 try {
348                     if (contentPurposeList != null) {
349                         for (int i=0; i < contentPurposeList.size(); i++) {
350                             String JavaDoc contentPurposeTypeId = (String JavaDoc)contentPurposeList.get(i);
351                             GenericValue contentPurpose = delegator.makeValue("ContentPurpose",
352                                    UtilMisc.toMap("contentId", contentId,
353                                                   "contentPurposeTypeId", contentPurposeTypeId) );
354                             contentPurpose.create();
355                         }
356                     }
357                 } catch(GenericEntityException e) {
358                     return ServiceUtil.returnError(e.getMessage());
359                 }
360             }
361
362         } else if (UtilValidate.isNotEmpty(dataResourceTypeId) && UtilValidate.isNotEmpty(contentId)) {
363             // If dataResource was not previously existing, then update the associated content with its id
364
if (UtilValidate.isNotEmpty(dataResourceId) && !dataResourceExists) {
365                 Map JavaDoc map = new HashMap JavaDoc();
366                 map.put("userLogin", userLogin);
367                 map.put("dataResourceId", dataResourceId);
368                 map.put("contentId", contentId);
369                 if (Debug.infoOn()) Debug.logInfo("in persist... context:" + context, module);
370                 Map JavaDoc r = ContentServices.updateContentMethod(dctx, map);
371                 boolean isError = ModelService.RESPOND_ERROR.equals(r.get(ModelService.RESPONSE_MESSAGE));
372                 if (isError)
373                     return ServiceUtil.returnError( (String JavaDoc)r.get(ModelService.ERROR_MESSAGE));
374             }
375         }
376
377         // If parentContentIdTo or parentContentIdFrom exists, create association with newly created content
378
String JavaDoc contentAssocTypeId = (String JavaDoc)context.get("contentAssocTypeId");
379         if (UtilValidate.isEmpty(contentAssocTypeId))
380             contentAssocTypeId = (String JavaDoc)context.get("caContentAssocTypeId");
381
382         if (Debug.infoOn()) Debug.logInfo("CREATING contentASSOC contentAssocTypeId:" + contentAssocTypeId, null);
383         if (contentAssocTypeId != null && contentAssocTypeId.length() > 0 ) {
384             if (Debug.infoOn()) Debug.logInfo("in persistContentAndAssoc, deactivateExistin:" + deactivateExisting, null);
385             Map JavaDoc contentAssocContext = new HashMap JavaDoc();
386             contentAssocContext.put("userLogin", userLogin);
387             contentAssocContext.put("displayFailCond", bDisplayFailCond);
388             contentAssocContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
389             Map JavaDoc thisResult = null;
390             try {
391                 contentAssoc.setPKFields(context);
392                 contentAssoc.setNonPKFields(context);
393                 GenericValue contentAssocPK = (GenericValue)contentAssoc.clone();
394                 GenericValue contentAssocExisting = null;
395                 if (contentAssocPK.isPrimaryKey())
396                     contentAssocExisting = delegator.findByPrimaryKeyCache("ContentAssoc", contentAssocPK);
397                     
398                 if (contentAssocExisting == null) {
399                     ModelService contentAssocModel = dispatcher.getDispatchContext().getModelService("createContentAssoc");
400                     Map JavaDoc ctx = contentAssocModel.makeValid(contentAssoc, "IN");
401                     contentAssocContext.putAll(ctx);
402                     thisResult = dispatcher.runSync("createContentAssoc", contentAssocContext);
403                     String JavaDoc errMsg = ServiceUtil.getErrorMessage(thisResult);
404                     if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult) || UtilValidate.isNotEmpty(errMsg)) {
405                         return ServiceUtil.returnError(errMsg);
406                     }
407                     results.put("contentIdTo", thisResult.get("contentIdTo"));
408                     results.put("contentIdFrom", thisResult.get("contentIdFrom"));
409                     //results.put("contentId", thisResult.get("contentIdFrom"));
410
results.put("contentAssocTypeId", thisResult.get("contentAssocTypeId"));
411                     results.put("fromDate", thisResult.get("fromDate"));
412                     results.put("sequenceNum", thisResult.get("sequenceNum"));
413                     
414                     results.put("caContentIdTo", thisResult.get("contentIdTo"));
415                     results.put("caContentAssocTypeId", thisResult.get("contentAssocTypeId"));
416                     results.put("caFromDate", thisResult.get("fromDate"));
417                     results.put("caSequenceNum", thisResult.get("sequenceNum"));
418                 } else {
419                     if ("true".equalsIgnoreCase(deactivateExisting)) {
420                         // TODO: DEJ20060221 Does something need to be done here?
421
//Map deactivateContext = UtilMisc.toMap("contentId", contentId, "contentAssocTypeId", contentAssocTypeId );
422
}
423                     ModelService contentAssocModel = dispatcher.getDispatchContext().getModelService("updateContentAssoc");
424                     Map JavaDoc ctx = contentAssocModel.makeValid(contentAssoc, "IN");
425                     contentAssocContext.putAll(ctx);
426                     thisResult = dispatcher.runSync("updateContentAssoc", contentAssocContext);
427                     String JavaDoc errMsg = ServiceUtil.getErrorMessage(thisResult);
428                     if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult) || UtilValidate.isNotEmpty(errMsg)) {
429                         return ServiceUtil.returnError(errMsg);
430                     }
431                 }
432             } catch (GenericEntityException e) {
433                 throw new GenericServiceException(e.getMessage());
434             } catch (Exception JavaDoc e2) {
435                 throw new GenericServiceException(e2.getMessage());
436             }
437             String JavaDoc errMsg = ServiceUtil.getErrorMessage(thisResult);
438            if (UtilValidate.isNotEmpty(errMsg)) {
439                return ServiceUtil.returnError(errMsg);
440            }
441        }
442        context.remove("skipPermissionCheck");
443        context.put("contentId", origContentId);
444        context.put("dataResourceId", origDataResourceId);
445        context.remove("dataResource");
446        Debug.logInfo("results:" + results, module);
447        return results;
448     }
449
450     /**
451     Service for update publish sites with a ContentRole that will tie them to the passed
452     in party.
453    */

454     public static Map JavaDoc updateSiteRoles(DispatchContext dctx, Map JavaDoc context) {
455         LocalDispatcher dispatcher = dctx.getDispatcher();
456         GenericDelegator delegator = dctx.getDelegator();
457         GenericValue userLogin = (GenericValue)context.get("userLogin");
458         //String userLoginPartyId = userLogin.getString("partyId");
459
Map JavaDoc results = new HashMap JavaDoc();
460       // siteContentId will equal "ADMIN_MASTER", "AGINC_MASTER", etc.
461
// Remember that this service is called in the "multi" mode,
462
// with a new siteContentId each time.
463
// siteContentId could also have been name deptContentId, since this same
464
// service is used for updating department roles, too.
465
String JavaDoc siteContentId = (String JavaDoc)context.get("contentId");
466       String JavaDoc partyId = (String JavaDoc)context.get("partyId");
467
468       if (UtilValidate.isEmpty(siteContentId) || UtilValidate.isEmpty(partyId))
469           return results;
470
471       //Debug.logInfo("updateSiteRoles, context(0):" + context, module);
472

473       List JavaDoc siteRoles = null;
474       try {
475           siteRoles = delegator.findByAndCache("RoleType", UtilMisc.toMap("parentTypeId", "BLOG"));
476       } catch(GenericEntityException e) {
477           return ServiceUtil.returnError( e.getMessage());
478       }
479         
480       Iterator JavaDoc siteRoleIter = siteRoles.iterator();
481       while (siteRoleIter.hasNext()) {
482           Map JavaDoc serviceContext = new HashMap JavaDoc();
483           serviceContext.put("partyId", partyId);
484           serviceContext.put("contentId", siteContentId);
485           serviceContext.put("userLogin", userLogin);
486           Debug.logInfo("updateSiteRoles, serviceContext(0):" + serviceContext, module);
487             GenericValue roleType = (GenericValue)siteRoleIter.next();
488           String JavaDoc siteRole = (String JavaDoc)roleType.get("roleTypeId"); // BLOG_EDITOR, BLOG_ADMIN, etc.
489
String JavaDoc cappedSiteRole = ModelUtil.dbNameToVarName(siteRole);
490           if (Debug.infoOn()) Debug.logInfo("updateSiteRoles, cappediteRole(1):" + cappedSiteRole, module);
491
492           String JavaDoc siteRoleVal = (String JavaDoc)context.get(cappedSiteRole);
493           if (Debug.infoOn()) Debug.logInfo("updateSiteRoles, siteRoleVal(1):" + siteRoleVal, module);
494           if (Debug.infoOn()) Debug.logInfo("updateSiteRoles, context(1):" + context, module);
495           Object JavaDoc fromDate = context.get(cappedSiteRole + "FromDate");
496           if (Debug.infoOn()) Debug.logInfo("updateSiteRoles, fromDate(1):" + fromDate, module);
497           serviceContext.put("roleTypeId", siteRole);
498           if (siteRoleVal != null && siteRoleVal.equalsIgnoreCase("Y")) {
499                   // for now, will assume that any error is due to duplicates - ignore
500
//return ServiceUtil.returnError(e.getMessage());
501
if (fromDate == null ) {
502                   try {
503                       Map JavaDoc newContext = new HashMap JavaDoc();
504                       newContext.put("contentId", serviceContext.get("contentId"));
505                       newContext.put("partyId", serviceContext.get("partyId"));
506                       newContext.put("roleTypeId", serviceContext.get("roleTypeId"));
507                       newContext.put("userLogin", userLogin);
508                       Map JavaDoc permResults = dispatcher.runSync("deactivateAllContentRoles", newContext);
509                       serviceContext.put("fromDate", UtilDateTime.nowTimestamp());
510                       if (Debug.infoOn()) Debug.logInfo("updateSiteRoles, serviceContext(1):" + serviceContext, module);
511                       permResults = dispatcher.runSync("createContentRole", serviceContext);
512                       String JavaDoc errMsg = ServiceUtil.getErrorMessage(permResults);
513                       if (UtilValidate.isNotEmpty(errMsg))
514                         return ServiceUtil.returnError(errMsg);
515                       //addRoleToUser(delegator, dispatcher, serviceContext);
516
} catch (GenericServiceException e) {
517                       Debug.logError(e, e.getMessage(), module);
518                       return ServiceUtil.returnError( e.getMessage());
519                   } catch (Exception JavaDoc e2) {
520                       Debug.logError(e2, e2.getMessage(), module);
521                       return ServiceUtil.returnError( e2.getMessage());
522                   }
523               }
524           } else {
525               if (fromDate != null ) {
526                       // for now, will assume that any error is due to non-existence - ignore
527
//return ServiceUtil.returnError(e.getMessage());
528
try {
529 Debug.logInfo("updateSiteRoles, serviceContext(2):" + serviceContext, module);
530                       //Timestamp thruDate = UtilDateTime.nowTimestamp();
531
//serviceContext.put("thruDate", thruDate);
532
//serviceContext.put("fromDate", fromDate);
533
Map JavaDoc newContext = new HashMap JavaDoc();
534                       newContext.put("contentId", serviceContext.get("contentId"));
535                       newContext.put("partyId", serviceContext.get("partyId"));
536                       newContext.put("roleTypeId", serviceContext.get("roleTypeId"));
537                       newContext.put("userLogin", userLogin);
538                       Map JavaDoc permResults = dispatcher.runSync("deactivateAllContentRoles", newContext);
539                       String JavaDoc errMsg = ServiceUtil.getErrorMessage(permResults);
540                       if (UtilValidate.isNotEmpty(errMsg))
541                         return ServiceUtil.returnError(errMsg);
542                   } catch (GenericServiceException e) {
543                       Debug.logError(e, e.getMessage(), module);
544                       return ServiceUtil.returnError( e.getMessage());
545                   } catch (Exception JavaDoc e2) {
546                       Debug.logError(e2, e2.getMessage(), module);
547                       return ServiceUtil.returnError( e2.getMessage());
548                   }
549               }
550           }
551       }
552       return results;
553   }
554   
555     public static Map JavaDoc persistDataResourceAndData(DispatchContext dctx, Map JavaDoc context) {
556       //GenericDelegator delegator = dctx.getDelegator();
557
LocalDispatcher dispatcher = dctx.getDispatcher();
558       //String contentId = (String)context.get("contentId");
559
Map JavaDoc result = new HashMap JavaDoc();
560       try {
561           //GenericValue content = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
562
ModelService checkPermModel = dispatcher.getDispatchContext().getModelService("checkContentPermission");
563           Map JavaDoc ctx = checkPermModel.makeValid(context, "IN");
564           Map JavaDoc thisResult = dispatcher.runSync("checkContentPermission", ctx);
565           String JavaDoc permissionStatus = (String JavaDoc)thisResult.get("permissionStatus");
566           if (UtilValidate.isNotEmpty(permissionStatus) && permissionStatus.equalsIgnoreCase("granted")) {
567               result = persistDataResourceAndDataMethod(dctx, context);
568           }
569       } catch (GenericServiceException e) {
570           return ServiceUtil.returnError(e.getMessage());
571       } catch (GenericEntityException e) {
572           return ServiceUtil.returnError(e.getMessage());
573       } catch (Exception JavaDoc e) {
574           return ServiceUtil.returnError(e.getMessage());
575       }
576       String JavaDoc errorMsg = ServiceUtil.getErrorMessage(result);
577       if (UtilValidate.isNotEmpty(errorMsg)) {
578           return ServiceUtil.returnError(errorMsg);
579       }
580       return result;
581     }
582   
583     public static Map JavaDoc persistDataResourceAndDataMethod(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException, GenericEntityException, Exception JavaDoc {
584       GenericDelegator delegator = dctx.getDelegator();
585       LocalDispatcher dispatcher = dctx.getDispatcher();
586       Map JavaDoc result = new HashMap JavaDoc();
587       Map JavaDoc newDrContext = new HashMap JavaDoc();
588       GenericValue dataResource = delegator.makeValue("DataResource", null);
589       dataResource.setPKFields(context);
590       dataResource.setNonPKFields(context);
591       dataResource.setAllFields(context, false, "dr", null);
592       context.putAll(dataResource);
593       
594       GenericValue electronicText = delegator.makeValue("ElectronicText", null);
595       electronicText.setPKFields(context);
596       electronicText.setNonPKFields(context);
597       String JavaDoc textData = (String JavaDoc)electronicText.get("textData");
598
599       
600       String JavaDoc dataResourceId = (String JavaDoc)dataResource.get("dataResourceId");
601       String JavaDoc dataResourceTypeId = (String JavaDoc)dataResource.get("dataResourceTypeId");
602       if (Debug.infoOn()) Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, null);
603       context.put("skipPermissionCheck", "granted"); // TODO: a temp hack because I don't want to bother with DataResource permissions at this time.
604
boolean dataResourceExists = true;
605       if (UtilValidate.isEmpty(dataResourceId)) {
606           dataResourceExists = false;
607       } else {
608           try {
609               GenericValue val = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
610               if (val == null)
611                   dataResourceExists = false;
612           } catch(GenericEntityException e) {
613               return ServiceUtil.returnError(e.getMessage());
614           }
615       }
616       GenericValue userLogin = (GenericValue) context.get("userLogin");
617       //String userLoginId = (String)userLogin.get("userLoginId");
618
ModelService dataResourceModel = dispatcher.getDispatchContext().getModelService("updateDataResource");
619       Map JavaDoc ctx = dataResourceModel.makeValid(dataResource, "IN");
620       newDrContext.putAll(ctx);
621       newDrContext.put("userLogin", userLogin);
622       newDrContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
623       ByteWrapper byteWrapper = (ByteWrapper)context.get("imageData");
624       String JavaDoc mimeTypeId = (String JavaDoc) newDrContext.get("mimeTypeId");
625       if (byteWrapper != null && (mimeTypeId == null || (mimeTypeId.indexOf("image") >= 0) || (mimeTypeId.indexOf("application") >= 0))) {
626           mimeTypeId = (String JavaDoc) context.get("_imageData_contentType");
627           String JavaDoc fileName = (String JavaDoc) context.get("_imageData_fileName");
628           newDrContext.put("objectInfo", fileName);
629           newDrContext.put("mimeTypeId", mimeTypeId);
630       }
631       
632       if (!dataResourceExists) {
633           Map JavaDoc thisResult = dispatcher.runSync("createDataResource", newDrContext);
634       String JavaDoc errorMsg = ServiceUtil.getErrorMessage(thisResult);
635       if (UtilValidate.isNotEmpty(errorMsg)) {
636           throw(new Exception JavaDoc(errorMsg));
637       }
638       dataResourceId = (String JavaDoc)thisResult.get("dataResourceId");
639       if (Debug.infoOn()) Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, null);
640       dataResource = (GenericValue)thisResult.get("dataResource");
641       Map JavaDoc fileContext = new HashMap JavaDoc();
642       fileContext.put("userLogin", userLogin);
643       if ( dataResourceTypeId.indexOf("_FILE") >=0) {
644           boolean hasData = false;
645           if (textData != null) {
646               fileContext.put("textData", textData);
647               hasData = true;
648           }
649           if (byteWrapper != null) {
650               fileContext.put("binData", byteWrapper);
651               hasData = true;
652           }
653           if (hasData) {
654               fileContext.put("rootDir", context.get("rootDir"));
655               fileContext.put("dataResourceTypeId", dataResourceTypeId);
656               fileContext.put("objectInfo", dataResource.get("objectInfo"));
657               thisResult = dispatcher.runSync("createFile", fileContext);
658               errorMsg = ServiceUtil.getErrorMessage(thisResult);
659               if (UtilValidate.isNotEmpty(errorMsg)) {
660                   return ServiceUtil.returnError(errorMsg);
661               }
662           }
663       } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
664           if (byteWrapper != null) {
665               fileContext.put("dataResourceId", dataResourceId);
666               fileContext.put("imageData", byteWrapper);
667               thisResult = dispatcher.runSync("createImage", fileContext);
668               errorMsg = ServiceUtil.getErrorMessage(thisResult);
669               if (UtilValidate.isNotEmpty(errorMsg)) {
670                   return ServiceUtil.returnError(errorMsg);
671               }
672           } else {
673               //return ServiceUtil.returnError("'byteWrapper' empty when trying to create database image.");
674
}
675       } else if (dataResourceTypeId.equals("SHORT_TEXT")) {
676       } else if (dataResourceTypeId.startsWith("SURVEY")) {
677       } else {
678           // assume ELECTRONIC_TEXT
679
if (UtilValidate.isNotEmpty(textData)) {
680               fileContext.put("dataResourceId", dataResourceId);
681               fileContext.put("textData", textData);
682               thisResult = dispatcher.runSync("createElectronicText", fileContext);
683               errorMsg = ServiceUtil.getErrorMessage(thisResult);
684               if (UtilValidate.isNotEmpty(errorMsg)) {
685                   return ServiceUtil.returnError(errorMsg);
686               }
687           }
688       }
689     } else {
690       Map JavaDoc thisResult = dispatcher.runSync("updateDataResource", newDrContext);
691       String JavaDoc errorMsg = ServiceUtil.getErrorMessage(thisResult);
692       if (UtilValidate.isNotEmpty(errorMsg)) {
693           return ServiceUtil.returnError(errorMsg);
694       }
695       //Map thisResult = DataServices.updateDataResourceMethod(dctx, context);
696
if (Debug.infoOn()) Debug.logInfo("in persist... thisResult.permissionStatus(0):" + thisResult.get("permissionStatus"), null);
697           //thisResult = DataServices.updateElectronicTextMethod(dctx, context);
698
Map JavaDoc fileContext = new HashMap JavaDoc();
699       fileContext.put("userLogin", userLogin);
700       String JavaDoc forceElectronicText = (String JavaDoc)context.get("forceElectronicText");
701       if (dataResourceTypeId.indexOf("_FILE") >=0) {
702           boolean hasData = false;
703           if (textData != null) {
704               fileContext.put("textData", textData);
705               hasData = true;
706           }
707           if (byteWrapper != null) {
708               fileContext.put("binData", byteWrapper);
709               hasData = true;
710           }
711           if (hasData || "true".equalsIgnoreCase(forceElectronicText)) {
712               fileContext.put("rootDir", context.get("rootDir"));
713               fileContext.put("dataResourcetype", dataResourceTypeId);
714               fileContext.put("objectInfo", dataResource.get("objectInfo"));
715               thisResult = dispatcher.runSync("updateFile", fileContext);
716               errorMsg = ServiceUtil.getErrorMessage(thisResult);
717               if (UtilValidate.isNotEmpty(errorMsg)) {
718                   return ServiceUtil.returnError(errorMsg);
719               }
720           }
721       } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
722           if (byteWrapper != null || "true".equalsIgnoreCase(forceElectronicText)) {
723               fileContext.put("dataResourceId", dataResourceId);
724               fileContext.put("imageData", byteWrapper);
725               thisResult = dispatcher.runSync("updateImage", fileContext);
726               errorMsg = ServiceUtil.getErrorMessage(thisResult);
727               if (UtilValidate.isNotEmpty(errorMsg)) {
728                   return ServiceUtil.returnError(errorMsg);
729               }
730           } else {
731               //return ServiceUtil.returnError("'byteWrapper' empty when trying to create database image.");
732
}
733       } else if (dataResourceTypeId.equals("SHORT_TEXT")) {
734       } else if (dataResourceTypeId.startsWith("SURVEY")) {
735       } else {
736           if (UtilValidate.isNotEmpty(textData) || "true".equalsIgnoreCase(forceElectronicText)) {
737               fileContext.put("dataResourceId", dataResourceId);
738               fileContext.put("textData", textData);
739               thisResult = dispatcher.runSync("updateElectronicText", fileContext);
740               errorMsg = ServiceUtil.getErrorMessage(thisResult);
741               if (UtilValidate.isNotEmpty(errorMsg)) {
742                   return ServiceUtil.returnError(errorMsg);
743               }
744           }
745       }
746     }
747     
748     result.put("dataResourceId", dataResourceId);
749     result.put("drDataResourceId", dataResourceId);
750     context.put("dataResourceId", dataResourceId);
751     return result;
752   }
753   
754     public static void addRoleToUser(GenericDelegator delegator, LocalDispatcher dispatcher, Map JavaDoc serviceContext) throws GenericServiceException, GenericEntityException {
755     String JavaDoc partyId = (String JavaDoc)serviceContext.get("partyId");
756     Map JavaDoc findMap = UtilMisc.toMap("partyId", partyId);
757         List JavaDoc userLoginList = delegator.findByAnd("UserLogin", findMap);
758         Iterator JavaDoc iter = userLoginList.iterator();
759         while (iter.hasNext()) {
760             GenericValue partyUserLogin = (GenericValue)iter.next();
761             String JavaDoc partyUserLoginId = partyUserLogin.getString("userLoginId");
762             serviceContext.put("contentId", partyUserLoginId); // author contentId
763
dispatcher.runSync("createContentRole", serviceContext);
764         }
765 }
766
767     public static Map JavaDoc updateSiteRolesDyn(DispatchContext dctx, Map JavaDoc context) {
768
769       LocalDispatcher dispatcher = dctx.getDispatcher();
770       GenericDelegator delegator = dctx.getDelegator();
771       Map JavaDoc results = new HashMap JavaDoc();
772       Map JavaDoc serviceContext = new HashMap JavaDoc();
773       // siteContentId will equal "ADMIN_MASTER", "AGINC_MASTER", etc.
774
// Remember that this service is called in the "multi" mode,
775
// with a new siteContentId each time.
776
// siteContentId could also have been name deptContentId, since this same
777
// service is used for updating department roles, too.
778
String JavaDoc siteContentId = (String JavaDoc)context.get("contentId");
779       String JavaDoc partyId = (String JavaDoc)context.get("partyId");
780       serviceContext.put("partyId", partyId);
781       serviceContext.put("contentId", siteContentId);
782       //Debug.logInfo("updateSiteRoles, serviceContext(0):" + serviceContext, module);
783
//Debug.logInfo("updateSiteRoles, context(0):" + context, module);
784

785       List JavaDoc siteRoles = null;
786       try {
787             siteRoles = delegator.findByAndCache("RoleType", UtilMisc.toMap("parentTypeId", "BLOG"));
788       } catch(GenericEntityException e) {
789           return ServiceUtil.returnError( e.getMessage());
790       }
791       Iterator JavaDoc siteRoleIter = siteRoles.iterator();
792       while (siteRoleIter.hasNext()) {
793             GenericValue roleType = (GenericValue)siteRoleIter.next();
794           String JavaDoc siteRole = (String JavaDoc)roleType.get("roleTypeId"); // BLOG_EDITOR, BLOG_ADMIN, etc.
795
String JavaDoc cappedSiteRole = ModelUtil.dbNameToVarName(siteRole);
796           //if (Debug.infoOn()) Debug.logInfo("updateSiteRoles, cappediteRole(1):" + cappedSiteRole, module);
797

798           String JavaDoc siteRoleVal = (String JavaDoc)context.get(cappedSiteRole);
799           Object JavaDoc fromDate = context.get(cappedSiteRole + "FromDate");
800           serviceContext.put("roleTypeId", siteRole);
801           if (siteRoleVal != null && siteRoleVal.equalsIgnoreCase("Y")) {
802                   // for now, will assume that any error is due to duplicates - ignore
803
//return ServiceUtil.returnError(e.getMessage());
804
if (fromDate == null ) {
805                   try {
806                       serviceContext.put("fromDate", UtilDateTime.nowTimestamp());
807                       if (Debug.infoOn()) Debug.logInfo("updateSiteRoles, serviceContext(1):" + serviceContext, module);
808                       addRoleToUser(delegator, dispatcher, serviceContext);
809                       Map JavaDoc permResults = dispatcher.runSync("createContentRole", serviceContext);
810                   } catch (GenericServiceException e) {
811                       Debug.logError(e, e.getMessage(), module);
812                   } catch (Exception JavaDoc e2) {
813                       Debug.logError(e2, e2.getMessage(), module);
814                   }
815               }
816           } else {
817               if (fromDate != null ) {
818                       // for now, will assume that any error is due to non-existence - ignore
819
//return ServiceUtil.returnError(e.getMessage());
820
try {
821 Debug.logInfo("updateSiteRoles, serviceContext(2):" + serviceContext, module);
822                       //Timestamp thruDate = UtilDateTime.nowTimestamp();
823
//serviceContext.put("thruDate", thruDate);
824
//serviceContext.put("fromDate", fromDate);
825
Map JavaDoc newContext = new HashMap JavaDoc();
826                       newContext.put("contentId", serviceContext.get("contentId"));
827                       newContext.put("partyId", serviceContext.get("partyId"));
828                       newContext.put("roleTypeId", serviceContext.get("roleTypeId"));
829                       Map JavaDoc permResults = dispatcher.runSync("deactivateAllContentRoles", newContext);
830                   } catch (GenericServiceException e) {
831                       Debug.logError(e, e.getMessage(), module);
832                   } catch (Exception JavaDoc e2) {
833                       Debug.logError(e2, e2.getMessage(), module);
834                   }
835               }
836           }
837       }
838       return results;
839   }
840
841     public static Map JavaDoc updateOrRemove(DispatchContext dctx, Map JavaDoc context) {
842
843         Map JavaDoc results = new HashMap JavaDoc();
844         GenericDelegator delegator = dctx.getDelegator();
845         String JavaDoc entityName = (String JavaDoc)context.get("entityName");
846         String JavaDoc action = (String JavaDoc)context.get("action");
847         String JavaDoc pkFieldCount = (String JavaDoc)context.get("pkFieldCount");
848         Map JavaDoc pkFields = new HashMap JavaDoc();
849         int fieldCount = Integer.parseInt(pkFieldCount);
850         for (int i=0; i<fieldCount; i++) {
851             String JavaDoc fieldName = (String JavaDoc)context.get("fieldName" + i);
852             String JavaDoc fieldValue = (String JavaDoc)context.get("fieldValue" + i);
853             if (UtilValidate.isEmpty(fieldValue)) {
854                 // It may be the case that the last row in a form is "empty" waiting for
855
// someone to enter a value, in which case we do not want to throw an
856
// error, we just want to ignore it.
857
return results;
858             }
859             pkFields.put(fieldName, fieldValue);
860         }
861         boolean doLink = (action != null && action.equalsIgnoreCase("Y")) ? true : false;
862         if (Debug.infoOn()) Debug.logInfo("in updateOrRemove, context:" + context, module);
863         try {
864             GenericValue entityValuePK = delegator.makeValue(entityName, pkFields);
865             if (Debug.infoOn()) Debug.logInfo("in updateOrRemove, entityValuePK:" + entityValuePK, module);
866             GenericValue entityValueExisting = delegator.findByPrimaryKeyCache(entityName, entityValuePK);
867             if (Debug.infoOn()) Debug.logInfo("in updateOrRemove, entityValueExisting:" + entityValueExisting, module);
868             if (entityValueExisting == null) {
869                 if (doLink) {
870                     entityValuePK.create();
871                     if (Debug.infoOn()) Debug.logInfo("in updateOrRemove, entityValuePK: CREATED", module);
872                 }
873             } else {
874                 if (!doLink) {
875                     entityValueExisting.remove();
876                     if (Debug.infoOn()) Debug.logInfo("in updateOrRemove, entityValueExisting: REMOVED", module);
877                 }
878             }
879             
880         } catch (GenericEntityException e) {
881             Debug.logError(e, module);
882             return ServiceUtil.returnError(e.getMessage());
883         }
884         return results;
885     }
886     
887     public static Map JavaDoc resequence(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
888
889         HashMap JavaDoc result = new HashMap JavaDoc();
890         GenericDelegator delegator = dctx.getDelegator();
891         String JavaDoc contentIdTo = (String JavaDoc)context.get("contentIdTo");
892         Integer JavaDoc seqInc = (Integer JavaDoc)context.get("seqInc");
893         if (seqInc == null)
894             seqInc = new Integer JavaDoc(100);
895         int seqIncrement = seqInc.intValue();
896         List JavaDoc typeList = (List JavaDoc)context.get("typeList");
897         if (typeList == null) typeList = new ArrayList JavaDoc();
898         String JavaDoc contentAssocTypeId = (String JavaDoc)context.get("contentAssocTypeId");
899         if (UtilValidate.isNotEmpty(contentAssocTypeId)) typeList.add(contentAssocTypeId);
900         if (UtilValidate.isEmpty(typeList)) typeList = UtilMisc.toList("PUBLISH_LINK", "SUB_CONTENT");
901         List JavaDoc condList = new ArrayList JavaDoc();
902         Iterator JavaDoc iterType = typeList.iterator();
903         while (iterType.hasNext()) {
904             String JavaDoc type = (String JavaDoc)iterType.next();
905             condList.add(new EntityExpr("contentAssocTypeId", EntityOperator.EQUALS, type));
906         }
907         
908         EntityCondition conditionType = new EntityConditionList(condList, EntityOperator.OR);
909         EntityCondition conditionMain = new EntityConditionList(UtilMisc.toList( new EntityExpr("contentIdTo", EntityOperator.EQUALS, contentIdTo), conditionType), EntityOperator.AND);
910          try {
911              List JavaDoc listAll = delegator.findByCondition("ContentAssoc", conditionMain, null, UtilMisc.toList("sequenceNum", "fromDate", "createdDate"));
912              List JavaDoc listFiltered = EntityUtil.filterByDate(listAll);
913              String JavaDoc contentId = (String JavaDoc)context.get("contentId");
914              String JavaDoc dir = (String JavaDoc)context.get("dir");
915              int seqNum = seqIncrement;
916              String JavaDoc thisContentId = null;
917              for (int i=0; i < listFiltered.size(); i++) {
918                  GenericValue contentAssoc = (GenericValue)listFiltered.get(i);
919                  if (UtilValidate.isNotEmpty(contentId) && UtilValidate.isNotEmpty(dir)) {
920                      // move targeted entry up or down
921
thisContentId = contentAssoc.getString("contentId");
922                      if (contentId.equals(thisContentId)) {
923                          if (dir.startsWith("up")) {
924                              if (i > 0) {
925                                  // Swap with previous entry
926
try {
927                                      GenericValue prevValue = (GenericValue)listFiltered.get(i-1);
928                                      Long JavaDoc prevSeqNum = (Long JavaDoc)prevValue.get("sequenceNum");
929                                      prevValue.put("sequenceNum", new Long JavaDoc(seqNum));
930                                      prevValue.store();
931                                      contentAssoc.put("sequenceNum", prevSeqNum);
932                                      contentAssoc.store();
933                                  } catch (Exception JavaDoc e) {
934                                      return ServiceUtil.returnError(e.getMessage());
935                                  }
936                              }
937                          } else {
938                              if (i < listFiltered.size()) {
939                                  // Swap with next entry
940
GenericValue nextValue = (GenericValue)listFiltered.get(i+1);
941                                  nextValue.put("sequenceNum", new Long JavaDoc(seqNum));
942                                  nextValue.store();
943                                  seqNum += seqIncrement;
944                                  contentAssoc.put("sequenceNum", new Long JavaDoc(seqNum));
945                                  contentAssoc.store();
946                                  i++; // skip next one
947
}
948                          }
949                      } else {
950                          contentAssoc.put("sequenceNum", new Long JavaDoc(seqNum));
951                          contentAssoc.store();
952                      }
953                  } else {
954                      contentAssoc.put("sequenceNum", new Long JavaDoc(seqNum));
955                      contentAssoc.store();
956                  }
957                  seqNum += seqIncrement;
958              }
959         } catch(GenericEntityException e) {
960             Debug.logError(e, module);
961             return ServiceUtil.returnError(e.getMessage());
962          }
963          
964        
965         return result;
966     }
967     
968     public static Map JavaDoc changeLeafToNode(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
969         Map JavaDoc result = new HashMap JavaDoc();
970         GenericDelegator delegator = dctx.getDelegator();
971         LocalDispatcher dispatcher = dctx.getDispatcher();
972         String JavaDoc contentId = (String JavaDoc)context.get("contentId");
973         GenericValue userLogin = (GenericValue)context.get("userLogin");
974         String JavaDoc userLoginId = userLogin.getString("userLoginId");
975         //int seqNum = 9999;
976
try {
977             GenericValue content = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
978             if (content == null) {
979                 Debug.logError("content was null", module);
980                 return ServiceUtil.returnError("content was null");
981             }
982             String JavaDoc dataResourceId = content.getString("dataResourceId");
983             //String contentTypeIdTo = content.getString("contentTypeId");
984
/* this does not seem to be correct or needed
985             if (UtilValidate.isNotEmpty(contentTypeIdTo)) {
986                 if (contentTypeIdTo.equals("OUTLINE_NODE")) {
987                     content.put("contentTypeId", "OUTLINE_NODE");
988                 } else if (contentTypeIdTo.equals("PAGE_NODE")) {
989                     content.put("contentTypeId", "SUBPAGE_NODE");
990                 } else
991                     content.put("contentTypeId", "PAGE_NODE");
992             }
993             */

994
995             content.set("dataResourceId", null);
996             content.set("lastModifiedDate", UtilDateTime.nowTimestamp());
997             content.set("lastModifiedByUserLogin", userLoginId);
998             content.store();
999             
1000            if (UtilValidate.isNotEmpty(dataResourceId)) {
1001                // add previous DataResource as part of new subcontent
1002
GenericValue contentClone = (GenericValue)content.clone();
1003                contentClone.set("dataResourceId", dataResourceId);
1004                content.set("lastModifiedDate", UtilDateTime.nowTimestamp());
1005                content.set("lastModifiedByUserLogin", userLoginId);
1006                content.set("createdDate", UtilDateTime.nowTimestamp());
1007                content.set("createdByUserLogin", userLoginId);
1008                
1009                contentClone.set("contentId", null);
1010                ModelService modelService = dctx.getModelService("persistContentAndAssoc");
1011                Map JavaDoc serviceIn = modelService.makeValid(contentClone, "IN");
1012                serviceIn.put("userLogin", userLogin);
1013                serviceIn.put("contentIdTo", contentId);
1014                serviceIn.put("contentAssocTypeId", "SUB_CONTENT");
1015                serviceIn.put("sequenceNum", new Long JavaDoc(50));
1016                try {
1017                    Map JavaDoc thisResult = dispatcher.runSync("persistContentAndAssoc", serviceIn);
1018                } catch(ServiceAuthException e) {
1019                    return ServiceUtil.returnError(e.getMessage());
1020                }
1021                
1022                List JavaDoc typeList = UtilMisc.toList("SUB_CONTENT");
1023                int leafCount = ContentManagementWorker.updateStatsTopDown(delegator, contentId, typeList);
1024            }
1025            
1026        } catch(GenericEntityException e) {
1027            Debug.logError(e, module);
1028            return ServiceUtil.returnError(e.getMessage());
1029        }
1030         
1031       
1032        return result;
1033    }
1034    
1035    public static Map JavaDoc updateLeafCount(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1036
1037        Map JavaDoc result = new HashMap JavaDoc();
1038        GenericDelegator delegator = dctx.getDelegator();
1039        List JavaDoc typeList = (List JavaDoc)context.get("typeList");
1040        if (typeList == null)
1041            typeList = UtilMisc.toList("PUBLISH_LINK", "SUB_CONTENT");
1042        String JavaDoc startContentId = (String JavaDoc)context.get("contentId");
1043        try {
1044            int leafCount = ContentManagementWorker.updateStatsTopDown(delegator, startContentId, typeList);
1045            result.put("leafCount", new Integer JavaDoc(leafCount));
1046        } catch(GenericEntityException e) {
1047            Debug.logError(e, module);
1048            return ServiceUtil.returnError(e.getMessage());
1049        }
1050        return result;
1051    }
1052    
1053/*
1054    public static Map updateLeafChange(DispatchContext dctx, Map context) throws GenericServiceException{
1055
1056        Map result = new HashMap();
1057        GenericDelegator delegator = dctx.getDelegator();
1058        List typeList = (List)context.get("typeList");
1059        if (typeList == null)
1060            typeList = UtilMisc.toList("PUBLISH_LINK", "SUB_CONTENT");
1061        String contentId = (String)context.get("contentId");
1062        
1063        try {
1064            GenericValue thisContent = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
1065            if (thisContent == null)
1066                throw new RuntimeException("No entity found for id=" + contentId);
1067            
1068            String thisContentId = thisContent.getString("contentId");
1069            Long leafCount = (Long)thisContent.get("nodeLeafCount");
1070            int subLeafCount = (leafCount == null) ? 1 : leafCount.intValue();
1071            String mode = (String)context.get("mode");
1072            if (mode != null && mode.equalsIgnoreCase("remove")) {
1073                subLeafCount *= -1;
1074            } else {
1075                // TODO: ??? what is this supposed to do:
1076                //subLeafCount = subLeafCount;
1077            }
1078            
1079           List condList = new ArrayList();
1080           Iterator iterType = typeList.iterator();
1081           while (iterType.hasNext()) {
1082               String type = (String)iterType.next();
1083               condList.add(new EntityExpr("contentAssocTypeId", EntityOperator.EQUALS, type));
1084           }
1085           
1086           EntityCondition conditionType = new EntityConditionList(condList, EntityOperator.OR);
1087           EntityCondition conditionMain = new EntityConditionList(UtilMisc.toList( new EntityExpr("contentId", EntityOperator.EQUALS, thisContentId), conditionType), EntityOperator.AND);
1088            List listAll = delegator.findByConditionCache("ContentAssoc", conditionMain, null, null);
1089            List listFiltered = EntityUtil.filterByDate(listAll);
1090            Iterator iter = listFiltered.iterator();
1091            while (iter.hasNext()) {
1092                GenericValue contentAssoc = (GenericValue)iter.next();
1093                String subContentId = contentAssoc.getString("contentId");
1094                GenericValue contentTo = delegator.findByPrimaryKeyCache("Content", UtilMisc.toMap("contentId", subContentId));
1095                Integer childBranchCount = (Integer)contentTo.get("childBranchCount");
1096                int branchCount = (childBranchCount == null) ? 1 : childBranchCount.intValue();
1097                if (mode != null && mode.equalsIgnoreCase("remove"))
1098                    branchCount += -1;
1099                else
1100                    branchCount += 1;
1101                // For the level just above only, update the branch count
1102                contentTo.put("childBranchCount", new Integer(branchCount));
1103                
1104                // Start the updating of leaf counts above
1105                ContentManagementWorker.updateStatsBottomUp(delegator, subContentId, typeList, subLeafCount);
1106            }
1107        
1108        
1109        } catch(GenericEntityException e) {
1110            Debug.logError(e, module);
1111            return ServiceUtil.returnError(e.getMessage());
1112        }
1113        return result;
1114    }
1115    */

1116    
1117    /**
1118     * This service changes the contentTypeId of the current content and its children depending on the pageMode.
1119     * if pageMode == "outline" then if the contentTypeId of children is not "OUTLINE_NODE" or "PAGE_NODE"
1120     * (it could be DOCUMENT or SUBPAGE_NODE) then it will get changed to PAGE_NODE.`
1121     * if pageMode == "page" then if the contentTypeId of children is not "PAGE_NODE" or "SUBPAGE_NODE"
1122     * (it could be DOCUMENT or OUTLINE_NODE) then it will get changed to SUBPAGE_NODE.`
1123     * @param delegator
1124     * @param contentId
1125     * @param pageMode
1126     */

1127    public static Map JavaDoc updatePageType(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1128        
1129        GenericDelegator delegator = dctx.getDelegator();
1130        Map JavaDoc results = new HashMap JavaDoc();
1131        Set JavaDoc visitedSet = (Set JavaDoc)context.get("visitedSet");
1132        if (visitedSet == null) {
1133            visitedSet = new HashSet JavaDoc();
1134            context.put("visitedSet", visitedSet);
1135        }
1136        String JavaDoc pageMode = (String JavaDoc)context.get("pageMode");
1137        String JavaDoc contentId = (String JavaDoc)context.get("contentId");
1138        visitedSet.add(contentId);
1139        String JavaDoc contentTypeId = "PAGE_NODE";
1140        if (pageMode != null && pageMode.toLowerCase().indexOf("outline") >= 0)
1141            contentTypeId = "OUTLINE_NODE";
1142        GenericValue thisContent = null;
1143        try {
1144            thisContent = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
1145            if (thisContent == null)
1146                ServiceUtil.returnError("No entity found for id=" + contentId);
1147            thisContent.set("contentTypeId", contentTypeId);
1148            thisContent.store();
1149            List JavaDoc kids = ContentWorker.getAssociatedContent(thisContent, "from", UtilMisc.toList("SUB_CONTENT"), null, null, null);
1150            Iterator JavaDoc iter = kids.iterator();
1151            while (iter.hasNext()) {
1152                GenericValue kidContent = (GenericValue)iter.next();
1153                if (contentTypeId.equals("OUTLINE_NODE")) {
1154                    updateOutlineNodeChildren(kidContent, false, context);
1155                } else {
1156                    updatePageNodeChildren(kidContent, context);
1157                }
1158            }
1159        } catch(GenericEntityException e) {
1160            Debug.logError(e, module);
1161            return ServiceUtil.returnError(e.getMessage());
1162        }
1163            
1164        return results;
1165    }
1166    
1167    public static Map JavaDoc resetToOutlineMode(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1168        
1169        GenericDelegator delegator = dctx.getDelegator();
1170        Map JavaDoc results = new HashMap JavaDoc();
1171        Set JavaDoc visitedSet = (Set JavaDoc)context.get("visitedSet");
1172        if (visitedSet == null) {
1173            visitedSet = new HashSet JavaDoc();
1174            context.put("visitedSet", visitedSet);
1175        }
1176        String JavaDoc contentId = (String JavaDoc)context.get("contentId");
1177        String JavaDoc pageMode = (String JavaDoc)context.get("pageMode");
1178        String JavaDoc contentTypeId = "OUTLINE_NODE";
1179        if (pageMode != null && pageMode.toLowerCase().indexOf("page") >= 0)
1180            contentTypeId = "PAGE_NODE";
1181        GenericValue thisContent = null;
1182        try {
1183            thisContent = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
1184            if (thisContent == null)
1185                ServiceUtil.returnError("No entity found for id=" + contentId);
1186            thisContent.set("contentTypeId", "OUTLINE_NODE");
1187            thisContent.store();
1188            List JavaDoc kids = ContentWorker.getAssociatedContent(thisContent, "from", UtilMisc.toList("SUB_CONTENT"), null, null, null);
1189            Iterator JavaDoc iter = kids.iterator();
1190            while (iter.hasNext()) {
1191                GenericValue kidContent = (GenericValue)iter.next();
1192                   if (contentTypeId.equals("OUTLINE_NODE")) {
1193                      updateOutlineNodeChildren(kidContent, true, context);
1194                   } else {
1195                       kidContent.put("contentTypeId", "PAGE_NODE");
1196                       kidContent.store();
1197                       List JavaDoc kids2 = ContentWorker.getAssociatedContent(kidContent, "from", UtilMisc.toList("SUB_CONTENT"), null, null, null);
1198                    Iterator JavaDoc iter2 = kids.iterator();
1199                    while (iter2.hasNext()) {
1200                        GenericValue kidContent2 = (GenericValue)iter2.next();
1201                           updatePageNodeChildren(kidContent2, context);
1202                    }
1203                }
1204            }
1205        } catch(GenericEntityException e) {
1206            Debug.logError(e, module);
1207            return ServiceUtil.returnError(e.getMessage());
1208        }
1209            
1210        return results;
1211    }
1212    
1213    public static Map JavaDoc clearContentAssocViewCache(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1214        Map JavaDoc results = new HashMap JavaDoc();
1215
1216        UtilCache utilCache = (UtilCache) UtilCache.utilCacheTable.get("entitycache.entity-list.default.ContentAssocViewFrom");
1217
1218        if (utilCache != null) {
1219            utilCache.clear();
1220        }
1221        
1222        utilCache = (UtilCache) UtilCache.utilCacheTable.get("entitycache.entity-list.default.ContentAssocViewTo");
1223        if (utilCache != null) {
1224            utilCache.clear();
1225        }
1226
1227        return results;
1228    }
1229    
1230    public static Map JavaDoc clearContentAssocDataResourceViewCache(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1231    
1232        Map JavaDoc results = new HashMap JavaDoc();
1233
1234        UtilCache utilCache = (UtilCache) UtilCache.utilCacheTable.get("entitycache.entity-list.default.ContentAssocViewDataResourceFrom");
1235        if (utilCache != null) {
1236            utilCache.clear();
1237        }
1238        
1239        utilCache = (UtilCache) UtilCache.utilCacheTable.get("entitycache.entity-list.default.ContentAssocViewDataResourceTo");
1240        if (utilCache != null) {
1241            utilCache.clear();
1242        }
1243
1244        return results;
1245    }
1246    
1247    public static void updatePageNodeChildren(GenericValue content, Map JavaDoc context) throws GenericEntityException {
1248        
1249        String JavaDoc contentId = content.getString("contentId");
1250        Set JavaDoc visitedSet = (Set JavaDoc)context.get("visitedSet");
1251        if (visitedSet == null) {
1252            visitedSet = new HashSet JavaDoc();
1253            context.put("visitedSet", visitedSet);
1254        } else {
1255            if (visitedSet.contains(contentId)) {
1256                Debug.logWarning("visitedSet already contains:" + contentId, module);
1257                return;
1258            } else {
1259                visitedSet.add(contentId);
1260            }
1261        }
1262        String JavaDoc contentTypeId = content.getString("contentTypeId");
1263        String JavaDoc newContentTypeId = "SUBPAGE_NODE";
1264// if (contentTypeId == null || contentTypeId.equals("DOCUMENT")) {
1265
// newContentTypeId = "SUBPAGE_NODE";
1266
// } else if (contentTypeId.equals("OUTLINE_NODE")) {
1267
// newContentTypeId = "PAGE_NODE";
1268
// }
1269

1270        content.put("contentTypeId", newContentTypeId);
1271        content.store();
1272        
1273        //if (contentTypeId == null || contentTypeId.equals("OUTLINE_DOCUMENT") || contentTypeId.equals("DOCUMENT")) {
1274
List JavaDoc kids = ContentWorker.getAssociatedContent(content, "from", UtilMisc.toList("SUB_CONTENT"), null, null, null);
1275            Iterator JavaDoc iter = kids.iterator();
1276            while (iter.hasNext()) {
1277                GenericValue kidContent = (GenericValue)iter.next();
1278                updatePageNodeChildren(kidContent, context);
1279            }
1280        //}
1281
return;
1282    }
1283
1284    public static void updateOutlineNodeChildren(GenericValue content, boolean forceOutline, Map JavaDoc context) throws GenericEntityException {
1285        
1286        String JavaDoc contentId = content.getString("contentId");
1287        Set JavaDoc visitedSet = (Set JavaDoc)context.get("visitedSet");
1288        if (visitedSet == null) {
1289            visitedSet = new HashSet JavaDoc();
1290            context.put("visitedSet", visitedSet);
1291        } else {
1292            if (visitedSet.contains(contentId)) {
1293                Debug.logWarning("visitedSet already contains:" + contentId, module);
1294                return;
1295            } else {
1296                visitedSet.add(contentId);
1297            }
1298        }
1299        String JavaDoc contentTypeId = content.getString("contentTypeId");
1300        String JavaDoc newContentTypeId = contentTypeId;
1301        String JavaDoc dataResourceId = content.getString("dataResourceId");
1302        Long JavaDoc branchCount = (Long JavaDoc)content.get("childBranchCount");
1303        if (forceOutline) {
1304            newContentTypeId = "OUTLINE_NODE";
1305        } else if (contentTypeId == null || contentTypeId.equals("DOCUMENT")) {
1306            if (UtilValidate.isEmpty(dataResourceId) || (branchCount != null && branchCount.intValue() > 0))
1307                newContentTypeId = "OUTLINE_NODE";
1308               else
1309                newContentTypeId = "PAGE_NODE";
1310        } else if (contentTypeId.equals("SUBPAGE_NODE")) {
1311            newContentTypeId = "PAGE_NODE";
1312        }
1313            
1314        content.put("contentTypeId", newContentTypeId);
1315        content.store();
1316        
1317        if (contentTypeId == null || contentTypeId.equals("DOCUMENT") || contentTypeId.equals("OUTLINE_NODE")) {
1318        //if (contentTypeId == null || contentTypeId.equals("DOCUMENT")) {
1319
List JavaDoc kids = ContentWorker.getAssociatedContent(content, "from", UtilMisc.toList("SUB_CONTENT"), null, null, null);
1320            Iterator JavaDoc iter = kids.iterator();
1321            while (iter.hasNext()) {
1322                GenericValue kidContent = (GenericValue)iter.next();
1323                updateOutlineNodeChildren(kidContent, forceOutline, context);
1324            }
1325        }
1326        return;
1327    }
1328
1329    public static Map JavaDoc findSubNodes(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1330        Map JavaDoc results = null;
1331        GenericDelegator delegator = dctx.getDelegator();
1332        String JavaDoc contentIdTo = (String JavaDoc)context.get("contentId");
1333        List JavaDoc condList = new ArrayList JavaDoc();
1334        EntityExpr expr = new EntityExpr("caContentIdTo", EntityOperator.EQUALS, contentIdTo);
1335        condList.add(expr);
1336        expr = new EntityExpr("caContentAssocTypeId", EntityOperator.EQUALS, "SUB_CONTENT");
1337        condList.add(expr);
1338        expr = new EntityExpr("caThruDate", EntityOperator.EQUALS, null);
1339        condList.add(expr);
1340        EntityConditionList entityCondList = new EntityConditionList(condList, EntityOperator.AND);
1341         try {
1342             List JavaDoc lst = delegator.findByCondition("ContentAssocDataResourceViewFrom", entityCondList, null, UtilMisc.toList("caSequenceNum", "caFromDate", "createdDate"));
1343             results.put("_LIST_", lst);
1344        } catch(GenericEntityException e) {
1345            Debug.logError(e, module);
1346            return ServiceUtil.returnError(e.getMessage());
1347        }
1348        return results;
1349    }
1350    
1351    public static String JavaDoc updateTypeAndFile(GenericValue dataResource, Map JavaDoc context) {
1352        String JavaDoc retVal = null;
1353        String JavaDoc mimeTypeId = (String JavaDoc) context.get("_imageData_contentType");
1354        String JavaDoc fileName = (String JavaDoc) context.get("_imageData_fileName");
1355        try {
1356            if (UtilValidate.isNotEmpty(fileName))
1357                dataResource.set("objectInfo", fileName);
1358            if (UtilValidate.isNotEmpty(mimeTypeId))
1359                dataResource.set("mimeTypeId", mimeTypeId);
1360            dataResource.store();
1361        } catch (GenericEntityException e) {
1362            retVal = "Unable to update the DataResource record";
1363        }
1364        return retVal;
1365    }
1366
1367    public static Map JavaDoc initContentChildCounts(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1368        Map JavaDoc result = new HashMap JavaDoc();
1369        GenericDelegator delegator = dctx.getDelegator();
1370        
1371            GenericValue content = (GenericValue)context.get("content");
1372            if (content == null) {
1373                    return ServiceUtil.returnError("No Content found.");
1374            }
1375            Long JavaDoc leafCount = (Long JavaDoc)content.get("childLeafCount");
1376            if (leafCount == null) {
1377                content.set("childLeafCount", new Long JavaDoc(0));
1378            }
1379            Long JavaDoc branchCount = (Long JavaDoc)content.get("childBranchCount");
1380            if (branchCount == null) {
1381                content.set("childBranchCount", new Long JavaDoc(0));
1382            }
1383            
1384            //content.store();
1385

1386        return result;
1387    }
1388
1389    public static Map JavaDoc incrementContentChildStats(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1390        Map JavaDoc result = new HashMap JavaDoc();
1391        GenericDelegator delegator = dctx.getDelegator();
1392        
1393            String JavaDoc contentId = (String JavaDoc)context.get("contentId");
1394            String JavaDoc contentAssocTypeId = (String JavaDoc)context.get("contentAssocTypeId");
1395            
1396            try {
1397                    GenericValue content = delegator.findByPrimaryKeyCache("Content", UtilMisc.toMap("contentId", contentId));
1398                if (content == null) {
1399                        return ServiceUtil.returnError("No Content found.");
1400                }
1401                Long JavaDoc leafCount = (Long JavaDoc)content.get("childLeafCount");
1402                if (leafCount == null) {
1403                    leafCount = new Long JavaDoc(0);
1404                }
1405                int changeLeafCount = leafCount.intValue() + 1;
1406                int changeBranchCount = 1;
1407                
1408                ContentManagementWorker.updateStatsBottomUp(delegator, contentId, UtilMisc.toList(contentAssocTypeId), changeBranchCount, changeLeafCount);
1409            } catch(GenericEntityException e) {
1410                    return ServiceUtil.returnError(e.getMessage());
1411            }
1412        return result;
1413    }
1414    
1415    public static Map JavaDoc decrementContentChildStats(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1416        Map JavaDoc result = new HashMap JavaDoc();
1417        GenericDelegator delegator = dctx.getDelegator();
1418        
1419            String JavaDoc contentId = (String JavaDoc)context.get("contentId");
1420            String JavaDoc contentAssocTypeId = (String JavaDoc)context.get("contentAssocTypeId");
1421            
1422            try {
1423                    GenericValue content = delegator.findByPrimaryKeyCache("Content", UtilMisc.toMap("contentId", contentId));
1424                if (content == null) {
1425                        return ServiceUtil.returnError("No Content found.");
1426                }
1427                Long JavaDoc leafCount = (Long JavaDoc)content.get("childLeafCount");
1428                if (leafCount == null) {
1429                    leafCount = new Long JavaDoc(0);
1430                }
1431                int changeLeafCount = -1 * leafCount.intValue() - 1;
1432                int changeBranchCount = -1;
1433                
1434                ContentManagementWorker.updateStatsBottomUp(delegator, contentId, UtilMisc.toList(contentAssocTypeId), changeBranchCount, changeLeafCount);
1435            } catch(GenericEntityException e) {
1436                    return ServiceUtil.returnError(e.getMessage());
1437            }
1438        return result;
1439    }
1440
1441    public static Map JavaDoc updateContentChildStats(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1442        Map JavaDoc result = new HashMap JavaDoc();
1443        GenericDelegator delegator = dctx.getDelegator();
1444    
1445        String JavaDoc contentId = (String JavaDoc)context.get("contentId");
1446        String JavaDoc contentAssocTypeId = (String JavaDoc)context.get("contentAssocTypeId");
1447        List JavaDoc typeList = new ArrayList JavaDoc();
1448        if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
1449            typeList.add(contentAssocTypeId);
1450        } else {
1451            typeList = UtilMisc.toList("PUBLISH_LINK", "SUB_CONTENT");
1452        }
1453        
1454        try {
1455            ContentManagementWorker.updateStatsTopDown(delegator, contentId, typeList);
1456        } catch(GenericEntityException e) {
1457                return ServiceUtil.returnError(e.getMessage());
1458        }
1459        return result;
1460    }
1461    
1462    public static Map JavaDoc updateSubscription(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1463        Map JavaDoc result = new HashMap JavaDoc();
1464        GenericDelegator delegator = dctx.getDelegator();
1465        LocalDispatcher dispatcher = dctx.getDispatcher();
1466        Timestamp JavaDoc nowTimestamp = UtilDateTime.nowTimestamp();
1467        
1468        String JavaDoc partyId = (String JavaDoc) context.get("partyId");
1469        String JavaDoc webPubPt = (String JavaDoc) context.get("contentId");
1470        String JavaDoc roleTypeId = (String JavaDoc) context.get("useRoleTypeId");
1471        GenericValue userLogin = (GenericValue) context.get("userLogin");
1472        Integer JavaDoc useTime = (Integer JavaDoc) context.get("useTime");
1473        String JavaDoc useTimeUomId = (String JavaDoc) context.get("useTimeUomId");
1474        boolean hasExistingContentRole = false;
1475        GenericValue contentRole = null;
1476        try {
1477            List JavaDoc contentRoleList = delegator.findByAndCache("ContentRole", UtilMisc.toMap("partyId", partyId, "contentId", webPubPt, "roleTypeId", roleTypeId));
1478            List JavaDoc listFiltered = EntityUtil.filterByDate(contentRoleList, true);
1479            List JavaDoc listOrdered = EntityUtil.orderBy(listFiltered, UtilMisc.toList("fromDate DESC"));
1480            if (listOrdered.size() > 0) {
1481                contentRole = (GenericValue) listOrdered.get(0);
1482                hasExistingContentRole = true;
1483            }
1484        } catch (GenericEntityException e) {
1485            return ServiceUtil.returnError(e.getMessage());
1486        }
1487        
1488        if (contentRole == null) {
1489            contentRole = delegator.makeValue("ContentRole", null);
1490            contentRole.set("contentId", webPubPt);
1491            contentRole.set("partyId", partyId);
1492            contentRole.set("roleTypeId", roleTypeId);
1493            contentRole.set("fromDate", nowTimestamp);
1494        }
1495        
1496        Timestamp JavaDoc thruDate = (Timestamp JavaDoc) contentRole.get("thruDate");
1497        if (thruDate == null) {
1498            // no thruDate? start with NOW
1499
thruDate = nowTimestamp;
1500        } else {
1501            // there is a thru date... if it is in the past, bring it up to NOW before adding on the time period
1502
//don't want to penalize for skipping time, in other words if they had a subscription last year for a month and buy another month, we want that second month to start now and not last year
1503
if (thruDate.before(nowTimestamp)) {
1504                thruDate = nowTimestamp;
1505            }
1506        }
1507        Calendar JavaDoc calendar = Calendar.getInstance();
1508        calendar.setTime(thruDate);
1509        int field = Calendar.MONTH;
1510        if ("TF_day".equals(useTimeUomId)) {
1511            field = Calendar.DAY_OF_YEAR;
1512        } else if ("TF_wk".equals(useTimeUomId)) {
1513            field = Calendar.WEEK_OF_YEAR;
1514        } else if ("TF_mon".equals(useTimeUomId)) {
1515            field = Calendar.MONTH;
1516        } else if ("TF_yr".equals(useTimeUomId)) {
1517            field = Calendar.YEAR;
1518        } else {
1519            Debug.logWarning("Don't know anything about useTimeUomId [" + useTimeUomId + "], defaulting to month", module);
1520        }
1521        calendar.add(field, useTime.intValue());
1522        thruDate = new Timestamp JavaDoc(calendar.getTimeInMillis());
1523        contentRole.set("thruDate", thruDate);
1524        try {
1525            if (hasExistingContentRole) {
1526                contentRole.store();
1527            } else {
1528                Map JavaDoc map = new HashMap JavaDoc();
1529                map.put("partyId", partyId);
1530                map.put("roleTypeId", roleTypeId);
1531                map.put("userLogin", userLogin);
1532                Map JavaDoc thisResult = dispatcher.runSync("createPartyRole", map);
1533                contentRole.create();
1534            }
1535        } catch (GenericEntityException e) {
1536            return ServiceUtil.returnError(e.getMessage());
1537        }
1538        return result;
1539    }
1540    
1541    public static Map JavaDoc updateSubscriptionByProduct(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1542        Map JavaDoc result = new HashMap JavaDoc();
1543        GenericDelegator delegator = dctx.getDelegator();
1544        LocalDispatcher dispatcher = dctx.getDispatcher();
1545        String JavaDoc productId = (String JavaDoc) context.get("productId");
1546        Integer JavaDoc qty = (Integer JavaDoc) context.get("quantity");
1547        if (qty == null) {
1548            qty = new Integer JavaDoc(1);
1549        }
1550        
1551        Timestamp JavaDoc orderCreatedDate = (Timestamp JavaDoc) context.get("orderCreatedDate");
1552        if (orderCreatedDate == null) {
1553            orderCreatedDate = UtilDateTime.nowTimestamp();
1554        }
1555        GenericValue productContent = null;
1556           try {
1557            List JavaDoc lst = delegator.findByAndCache("ProductContent", UtilMisc.toMap("productId", productId, "productContentTypeId", "ONLINE_ACCESS"));
1558            List JavaDoc listFiltered = EntityUtil.filterByDate(lst, orderCreatedDate, "purchaseFromDate", "purchaseThruDate", true);
1559            List JavaDoc listOrdered = EntityUtil.orderBy(listFiltered, UtilMisc.toList("purchaseFromDate", "purchaseThruDate"));
1560            List JavaDoc listThrusOnly = EntityUtil.filterOutByCondition(listOrdered, new EntityExpr("purchaseThruDate", EntityOperator.EQUALS, null));
1561            if (listThrusOnly.size() > 0) {
1562                productContent = (GenericValue) listThrusOnly.get(0);
1563            } else {
1564                productContent = (GenericValue) listOrdered.get(0);
1565            }
1566        } catch(GenericEntityException e) {
1567            Debug.logError(e.getMessage(), module);
1568            return ServiceUtil.returnError(e.getMessage());
1569        }
1570        if (productContent == null) {
1571            String JavaDoc msg = "No ProductContent found for productId:" + productId;
1572            Debug.logError(msg, module);
1573            return ServiceUtil.returnError(msg);
1574        }
1575        Long JavaDoc useTime = (Long JavaDoc)productContent.get("useTime");
1576        Integer JavaDoc newUseTime = new Integer JavaDoc(useTime.intValue() * qty.intValue());
1577        context.put("useTime", newUseTime);
1578        context.put("useTimeUomId", productContent.get("useTimeUomId"));
1579        context.put("useRoleTypeId", productContent.get("useRoleTypeId"));
1580        context.put("contentId", productContent.get("contentId"));
1581        ModelService subscriptionModel = dispatcher.getDispatchContext().getModelService("updateSubscription");
1582        Map JavaDoc ctx = subscriptionModel.makeValid(context, "IN");
1583        result = dispatcher.runSync("updateSubscription", ctx);
1584        return result;
1585    }
1586    
1587    public static Map JavaDoc updateSubscriptionByOrder(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1588        Map JavaDoc result = new HashMap JavaDoc();
1589        GenericDelegator delegator = dctx.getDelegator();
1590        LocalDispatcher dispatcher = dctx.getDispatcher();
1591        String JavaDoc orderId = (String JavaDoc) context.get("orderId");
1592        
1593        Debug.logInfo("In updateSubscriptionByOrder service with orderId: " + orderId, module);
1594        
1595        GenericValue orderHeader = null;
1596        try {
1597            List JavaDoc orderRoleList = delegator.findByAnd("OrderRole", UtilMisc.toMap("orderId", orderId, "roleTypeId", "END_USER_CUSTOMER"));
1598            if (orderRoleList.size() > 0 ) {
1599                GenericValue orderRole = (GenericValue)orderRoleList.get(0);
1600                String JavaDoc partyId = (String JavaDoc) orderRole.get("partyId");
1601                context.put("partyId", partyId);
1602            } else {
1603                String JavaDoc msg = "No OrderRole found for orderId:" + orderId;
1604                Debug.logError(msg, module);
1605                return ServiceUtil.returnError(msg);
1606                
1607            }
1608            orderHeader = delegator.findByPrimaryKeyCache("OrderHeader", UtilMisc.toMap("orderId", orderId));
1609            if (orderHeader == null) {
1610                String JavaDoc msg = "No OrderHeader found for orderId:" + orderId;
1611                Debug.logError(msg, module);
1612                return ServiceUtil.returnError(msg);
1613            }
1614            Timestamp JavaDoc orderCreatedDate = (Timestamp JavaDoc) orderHeader.get("orderDate");
1615            context.put("orderCreatedDate", orderCreatedDate);
1616            List JavaDoc orderItemList = orderHeader.getRelated("OrderItem");
1617            Iterator JavaDoc orderItemIter = orderItemList.iterator();
1618                ModelService subscriptionModel = dispatcher.getDispatchContext().getModelService("updateSubscriptionByProduct");
1619            while (orderItemIter.hasNext()) {
1620                GenericValue orderItem = (GenericValue)orderItemIter.next();
1621                Double JavaDoc qty = (Double JavaDoc) orderItem.get("quantity");
1622                String JavaDoc productId = (String JavaDoc) orderItem.get("productId");
1623                List JavaDoc productContentList = delegator.findByAnd("ProductContent", UtilMisc.toMap("productId", productId, "productContentTypeId", "ONLINE_ACCESS"));
1624                List JavaDoc productContentListFiltered = EntityUtil.filterByDate(productContentList);
1625                if (productContentListFiltered.size() > 0) {
1626                    context.put("productId", productId);
1627                    context.put("quantity", new Integer JavaDoc(qty.intValue()));
1628                    Map JavaDoc ctx = subscriptionModel.makeValid(context, "IN");
1629                    Map JavaDoc thisResult = dispatcher.runSync("updateSubscriptionByProduct", ctx);
1630                }
1631            }
1632        } catch(GenericEntityException e) {
1633            Debug.logError(e.getMessage(), module);
1634            return ServiceUtil.returnError(e.getMessage());
1635        }
1636        return result;
1637    }
1638
1639    public static Map JavaDoc followNodeChildren(DispatchContext dctx, Map JavaDoc context) throws GenericServiceException{
1640        
1641        Map JavaDoc result = null;
1642        GenericDelegator delegator = dctx.getDelegator();
1643        LocalDispatcher dispatcher = dctx.getDispatcher();
1644        Security security = dctx.getSecurity();
1645        GenericValue userLogin = (GenericValue)context.get("userLogin");
1646        if (!security.hasEntityPermission("CONTENTMGR", "_ADMIN", userLogin)) {
1647            return ServiceUtil.returnError("Permission denied.");
1648        }
1649        String JavaDoc contentId = (String JavaDoc)context.get("contentId");
1650        String JavaDoc serviceName = (String JavaDoc)context.get("serviceName");
1651        String JavaDoc contentAssocTypeId = (String JavaDoc)context.get("contentAssocTypeId");
1652        List JavaDoc contentAssocTypeIdList = new ArrayList JavaDoc();
1653        if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
1654             contentAssocTypeIdList = StringUtil.split(contentAssocTypeId, "|");
1655        }
1656        if (contentAssocTypeIdList.size() == 0) {
1657            contentAssocTypeIdList.add("SUB_CONTENT");
1658        }
1659        Map JavaDoc ctx = new HashMap JavaDoc();
1660        ctx.put("userLogin", userLogin);
1661        ctx.put("contentAssocTypeIdList", contentAssocTypeIdList);
1662        try {
1663            
1664            GenericValue content = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
1665            result = followNodeChildrenMethod(content, dispatcher, serviceName, ctx);
1666        } catch(GenericEntityException e) {
1667            Debug.logError(e.getMessage(), module);
1668            return ServiceUtil.returnError(e.getMessage());
1669        }
1670        return result;
1671    }
1672    public static Map JavaDoc followNodeChildrenMethod(GenericValue content, LocalDispatcher dispatcher, String JavaDoc serviceName, Map JavaDoc context)
1673        throws GenericEntityException, GenericServiceException {
1674        
1675        Map JavaDoc result = null;
1676        String JavaDoc contentId = content.getString("contentId");
1677        List JavaDoc contentAssocTypeIdList = (List JavaDoc)context.get("contentAssocTypeIdList" );
1678        Set JavaDoc visitedSet = (Set JavaDoc)context.get("visitedSet");
1679        if (visitedSet == null) {
1680            visitedSet = new HashSet JavaDoc();
1681            context.put("visitedSet", visitedSet);
1682        } else {
1683            if (visitedSet.contains(contentId)) {
1684                Debug.logWarning("visitedSet already contains:" + contentId, module);
1685                return ServiceUtil.returnError("visitedSet already contains:" + contentId);
1686            } else {
1687                visitedSet.add(contentId);
1688            }
1689        }
1690
1691        GenericValue userLogin = (GenericValue)context.get("userLogin");
1692        result = dispatcher.runSync(serviceName, UtilMisc.toMap("content", content, "userLogin", userLogin));
1693        
1694        List JavaDoc kids = ContentWorker.getAssociatedContent(content, "from", contentAssocTypeIdList, null, null, null);
1695        Iterator JavaDoc iter = kids.iterator();
1696        while (iter.hasNext()) {
1697            GenericValue kidContent = (GenericValue)iter.next();
1698            followNodeChildrenMethod(kidContent, dispatcher, serviceName, context);
1699        }
1700        return result;
1701    }
1702
1703    /**
1704   */

1705  public static Map JavaDoc persistContentWithRevision(DispatchContext dctx, Map JavaDoc context) {
1706      Map JavaDoc result = null;
1707      boolean dataResourceExists = false;
1708      GenericDelegator delegator = dctx.getDelegator();
1709      LocalDispatcher dispatcher = dctx.getDispatcher();
1710      GenericValue dataResource = null;
1711      String JavaDoc masterRevisionContentId = (String JavaDoc)context.get("masterRevisionContentId");
1712      String JavaDoc oldDataResourceId = (String JavaDoc)context.get("drDataResourceId");
1713      if (UtilValidate.isEmpty(oldDataResourceId)) {
1714          oldDataResourceId = (String JavaDoc)context.get("dataResourceId");
1715      }
1716      if (UtilValidate.isNotEmpty(oldDataResourceId)) {
1717          try {
1718              dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", oldDataResourceId));
1719          } catch(GenericEntityException e) {
1720              Debug.logError(e.getMessage(), module);
1721              return ServiceUtil.returnError(e.getMessage());
1722          }
1723      }
1724      
1725      try {
1726          ModelService persistContentAndAssocModel = dispatcher.getDispatchContext().getModelService("persistContentAndAssoc");
1727          Map JavaDoc ctx = persistContentAndAssocModel.makeValid(context, "IN");
1728          if (dataResource != null) {
1729              ctx.remove("dataResourceId");
1730              ctx.remove("drDataResourceId");
1731          }
1732          result = dispatcher.runSync("persistContentAndAssoc", ctx);
1733          String JavaDoc errorMsg = ServiceUtil.getErrorMessage(result);
1734          if (UtilValidate.isNotEmpty(errorMsg)) {
1735              return ServiceUtil.returnError(errorMsg);
1736          }
1737          String JavaDoc contentId = (String JavaDoc)result.get("contentId");
1738          List JavaDoc parentList = new ArrayList JavaDoc();
1739          if (UtilValidate.isEmpty(masterRevisionContentId)) {
1740              Map JavaDoc traversMap = new HashMap JavaDoc();
1741              traversMap.put("contentId", contentId);
1742              traversMap.put("direction", "To");
1743              traversMap.put("contentAssocTypeId", "COMPDOC_PART");
1744              Map JavaDoc traversResult = dispatcher.runSync("traverseContent", traversMap);
1745              parentList = (List JavaDoc)traversResult.get("parentList");
1746          } else {
1747              parentList.add(masterRevisionContentId);
1748          }
1749          
1750          // Update ContentRevision and ContentRevisonItem
1751
Map JavaDoc contentRevisionMap = new HashMap JavaDoc();
1752          contentRevisionMap.put("itemContentId", contentId);
1753          contentRevisionMap.put("newDataResourceId", result.get("dataResourceId"));
1754          contentRevisionMap.put("oldDataResourceId", oldDataResourceId);
1755          // need committedByPartyId
1756
for (int i=0; i < parentList.size(); i++) {
1757              String JavaDoc thisContentId = (String JavaDoc)parentList.get(i);
1758              contentRevisionMap.put("contentId", thisContentId);
1759              result = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap);
1760              errorMsg = ServiceUtil.getErrorMessage(result);
1761              if (UtilValidate.isNotEmpty(errorMsg)) {
1762                  return ServiceUtil.returnError(errorMsg);
1763              }
1764          }
1765          
1766      } catch (GenericServiceException e) {
1767          Debug.logError(e.getMessage(), module);
1768          return ServiceUtil.returnError(e.getMessage());
1769      }
1770      return result;
1771  }
1772
1773}
1774
Popular Tags