KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > content > compdoc > CompDocServices


1 /*
2  * $Id: $
3  *
4  * Copyright 2005-2006 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7  * use this file except in compliance with the License. You may obtain a copy of
8  * the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15  * License for the specific language governing permissions and limitations
16  * under the License.
17  */

18 package org.ofbiz.content.compdoc;
19
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.sql.Timestamp JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Locale JavaDoc;
28 import java.util.Map JavaDoc;
29
30 import org.ofbiz.base.util.Debug;
31 import org.ofbiz.base.util.UtilDateTime;
32 import org.ofbiz.base.util.UtilMisc;
33 import org.ofbiz.base.util.UtilProperties;
34 import org.ofbiz.base.util.UtilValidate;
35 import org.ofbiz.content.data.DataResourceWorker;
36 import org.ofbiz.entity.GenericDelegator;
37 import org.ofbiz.entity.GenericEntityException;
38 import org.ofbiz.entity.GenericValue;
39 import org.ofbiz.entity.condition.EntityConditionList;
40 import org.ofbiz.entity.condition.EntityExpr;
41 import org.ofbiz.entity.condition.EntityOperator;
42 import org.ofbiz.entity.util.ByteWrapper;
43 import org.ofbiz.service.DispatchContext;
44 import org.ofbiz.service.GenericServiceException;
45 import org.ofbiz.service.LocalDispatcher;
46 import org.ofbiz.service.ModelService;
47 import org.ofbiz.service.ServiceUtil;
48 import org.ofbiz.webapp.event.CoreEvents;
49 import org.ofbiz.webapp.view.ViewHandlerException;
50
51 import com.lowagie.text.Document;
52 import com.lowagie.text.PageSize;
53 import com.lowagie.text.pdf.PdfCopy;
54 import com.lowagie.text.pdf.PdfImportedPage;
55 import com.lowagie.text.pdf.PdfReader;
56
57 /**
58  * CompDocEvents Class
59  *
60  * @author <a HREF="mailto:byersa@automationgroups.com">Al Byers</a>
61  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
62  */

63
64 public class CompDocServices {
65     public static final String JavaDoc module = CompDocServices.class.getName();
66     
67     /**
68      *
69      * @param request
70      * @param response
71      * @return
72      *
73      * Creates the topmost Content entity of a Composite Document tree.
74      * Also creates an "empty" Composite Document Instance Content entity.
75      * Creates ContentRevision/Item records for each, as well.
76      */

77
78     public static Map JavaDoc persistRootCompDoc(DispatchContext dctx, Map JavaDoc context) {
79         Map JavaDoc result = new HashMap JavaDoc();
80         GenericDelegator delegator = dctx.getDelegator();
81         LocalDispatcher dispatcher = dctx.getDispatcher();
82         Locale JavaDoc locale = (Locale JavaDoc)context.get("locale");
83         GenericValue userLogin = (GenericValue)context.get("userLogin");
84         String JavaDoc contentId = (String JavaDoc)context.get("contentId");
85         //String instanceContentId = null;
86

87         boolean contentExists = true;
88         if (UtilValidate.isEmpty(contentId)) {
89             contentExists = false;
90         } else {
91             try {
92                 GenericValue val = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
93                 if (val == null) contentExists = false;
94             } catch(GenericEntityException e) {
95                 Debug.logError(e, "Error running serviceName persistContentAndAssoc", module);
96                 String JavaDoc errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
97                 return ServiceUtil.returnError(errMsg);
98            }
99         }
100         
101         ModelService modelService = null;
102         try {
103             modelService = dispatcher.getDispatchContext().getModelService("persistContentAndAssoc");
104         } catch (GenericServiceException e) {
105             String JavaDoc errMsg = "Error getting model service for serviceName, 'persistContentAndAssoc'. " + e.toString();
106             Debug.logError(errMsg, module);
107             return ServiceUtil.returnError(errMsg);
108         }
109         Map JavaDoc persistMap = modelService.makeValid(context, ModelService.IN_PARAM);
110         persistMap.put("userLogin", userLogin);
111         try {
112             Map JavaDoc persistContentResult = dispatcher.runSync("persistContentAndAssoc", persistMap);
113             if (ServiceUtil.isError(persistContentResult)) {
114                 //Debug.logError("Error running service 'persistContentAndAssoc'. " + ServiceUtil.getErrorMessage(persistContentResult), module);
115
return ServiceUtil.returnError("Error saving content information: ", null, null, persistContentResult);
116             }
117
118             contentId = (String JavaDoc) persistContentResult.get("contentId");
119             result.putAll(persistContentResult);
120             //request.setAttribute("contentId", contentId);
121
// Update ContentRevision and ContentRevisonItem
122

123             Map JavaDoc contentRevisionMap = new HashMap JavaDoc();
124             contentRevisionMap.put("itemContentId", contentId);
125             contentRevisionMap.put("contentId", contentId);
126             contentRevisionMap.put("userLogin", userLogin);
127
128             Map JavaDoc persistRevResult = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap);
129             if (ServiceUtil.isError(persistRevResult)) {
130                 //Debug.logError("Error running service 'persistContentRevisionAndItem'. " + ServiceUtil.getErrorMessage(persistRevResult), module);
131
return ServiceUtil.returnError("Error saving revision information: ", null, null, persistRevResult);
132             }
133
134             result.putAll(persistRevResult);
135             return result;
136         } catch(GenericServiceException e) {
137             String JavaDoc errMsg = "Error running serviceName, 'persistContentAndAssoc'. " + e.toString();
138             Debug.logError(e, errMsg, module);
139             return ServiceUtil.returnError(errMsg);
140         }
141     }
142
143     public static Map JavaDoc renderCompDocPdf(DispatchContext dctx, Map JavaDoc context) {
144         LocalDispatcher dispatcher = dctx.getDispatcher();
145         
146         Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
147         String JavaDoc rootDir = (String JavaDoc) context.get("rootDir");
148         String JavaDoc webSiteId = (String JavaDoc) context.get("webSiteId");
149         String JavaDoc https = (String JavaDoc) context.get("https");
150         
151         GenericDelegator delegator = dctx.getDelegator();
152         
153         String JavaDoc contentId = (String JavaDoc) context.get("contentId");
154         String JavaDoc contentRevisionSeqId = (String JavaDoc) context.get("contentRevisionSeqId");
155         String JavaDoc oooHost = (String JavaDoc) context.get("oooHost");
156         String JavaDoc oooPort = (String JavaDoc) context.get("oooPort");
157         GenericValue userLogin = (GenericValue) context.get("userLogin");
158         
159         try {
160             Timestamp JavaDoc nowTimestamp = UtilDateTime.nowTimestamp();
161             List JavaDoc exprList = new ArrayList JavaDoc();
162             exprList.add(new EntityExpr("contentIdTo", EntityOperator.EQUALS, contentId));
163             exprList.add(new EntityExpr("rootRevisionContentId", EntityOperator.EQUALS, contentId));
164             if (UtilValidate.isNotEmpty(contentRevisionSeqId)) {
165                 exprList.add(new EntityExpr("contentRevisionSeqId", EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId));
166             }
167             exprList.add(new EntityExpr("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART"));
168             exprList.add(new EntityExpr("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp));
169
170             List JavaDoc thruList = new ArrayList JavaDoc();
171             thruList.add(new EntityExpr("thruDate", EntityOperator.EQUALS, null));
172             thruList.add(new EntityExpr("thruDate", EntityOperator.GREATER_THAN, nowTimestamp));
173             exprList.add(new EntityConditionList(thruList, EntityOperator.OR));
174
175             EntityConditionList conditionList = new EntityConditionList(exprList, EntityOperator.AND);
176             
177             String JavaDoc [] fields = {"rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId", "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum"};
178             List JavaDoc selectFields = UtilMisc.toListArray(fields);
179             List JavaDoc orderByFields = UtilMisc.toList("sequenceNum");
180             List JavaDoc compDocParts = delegator.findByCondition("ContentAssocRevisionItemView", conditionList, selectFields, orderByFields);
181             
182             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
183             Document document = new Document();
184             document.setPageSize(PageSize.LETTER);
185             //Rectangle rect = document.getPageSize();
186
//PdfWriter writer = PdfWriter.getInstance(document, baos);
187
PdfCopy writer = new PdfCopy(document, baos);
188             document.open();
189             Iterator JavaDoc iter = compDocParts.iterator();
190             int pgCnt =0;
191             while (iter.hasNext()) {
192                 GenericValue contentAssocRevisionItemView = (GenericValue)iter.next();
193                 //String thisContentId = contentAssocRevisionItemView.getString("contentId");
194
//String thisContentRevisionSeqId = contentAssocRevisionItemView.getString("maxRevisionSeqId");
195
String JavaDoc thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
196                 GenericValue dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", thisDataResourceId));
197                 String JavaDoc inputMimeType = null;
198                 if(dataResource != null) {
199                     inputMimeType = (String JavaDoc)dataResource.getString("mimeTypeId");
200                 }
201                 byte [] inputByteArray = null;
202                 PdfReader reader = null;
203                 if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
204                     ByteWrapper byteWrapper = DataResourceWorker.getContentAsByteWrapper(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
205                     inputByteArray = byteWrapper.getBytes();
206                     reader = new PdfReader(inputByteArray);
207                 } else if (inputMimeType != null && inputMimeType.equals("text/html")) {
208                     ByteWrapper byteWrapper = DataResourceWorker.getContentAsByteWrapper(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
209                     inputByteArray = byteWrapper.getBytes();
210                     String JavaDoc s = new String JavaDoc(inputByteArray);
211                     Debug.logInfo("text/html string:" + s, module);
212                     continue;
213                 } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
214                     String JavaDoc surveyResponseId = dataResource.getString("relatedDetailId");
215                     String JavaDoc surveyId = null;
216                     String JavaDoc acroFormContentId = null;
217                     GenericValue surveyResponse = null;
218                     if (UtilValidate.isNotEmpty(surveyResponseId)) {
219                         surveyResponse = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
220                         if (surveyResponse != null) {
221                             surveyId = surveyResponse.getString("surveyId");
222                         }
223                     }
224                     if (UtilValidate.isNotEmpty(surveyId)) {
225                         GenericValue survey = delegator.findByPrimaryKey("Survey", UtilMisc.toMap("surveyId", surveyId));
226                         if (survey != null) {
227                             acroFormContentId = survey.getString("acroFormContentId");
228                             if (UtilValidate.isNotEmpty(acroFormContentId)) {
229                                 // TODO: is something supposed to be done here?
230
}
231                         }
232                     }
233                     if (surveyResponse != null) {
234                         if (UtilValidate.isEmpty(acroFormContentId)) {
235                             // Create AcroForm PDF
236
Map JavaDoc survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId));
237                             if (ServiceUtil.isError(survey2PdfResults)) {
238                                 return ServiceUtil.returnError("Error building PDF from SurveyResponse: ", null, null, survey2PdfResults);
239                             }
240
241                             ByteWrapper outByteWrapper = (ByteWrapper)survey2PdfResults.get("outByteWrapper");
242                             inputByteArray = outByteWrapper.getBytes();
243                             reader = new PdfReader(inputByteArray);
244                         } else {
245                             // Fill in acroForm
246
Map JavaDoc survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
247                             if (ServiceUtil.isError(survey2AcroFieldResults)) {
248                                 return ServiceUtil.returnError("Error setting AcroFields from SurveyResponse: ", null, null, survey2AcroFieldResults);
249                             }
250
251                             ByteWrapper outByteWrapper = (ByteWrapper) survey2AcroFieldResults.get("outByteWrapper");
252                             inputByteArray = outByteWrapper.getBytes();
253                             reader = new PdfReader(inputByteArray);
254                         }
255                     }
256                 } else {
257                     ByteWrapper inByteWrapper = DataResourceWorker.getContentAsByteWrapper(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
258
259                     Map JavaDoc convertInMap = UtilMisc.toMap("userLogin", userLogin, "inByteWrapper", inByteWrapper, "inputMimeType", inputMimeType, "outputMimeType", "application/pdf");
260                     if (UtilValidate.isNotEmpty(oooHost)) convertInMap.put("oooHost", oooHost);
261                     if (UtilValidate.isNotEmpty(oooPort)) convertInMap.put("oooPort", oooPort);
262
263                     Map JavaDoc convertResult = dispatcher.runSync("convertDocumentByteWrapper", convertInMap);
264                     
265                     if (ServiceUtil.isError(convertResult)) {
266                         return ServiceUtil.returnError("Error in Open", null, null, convertResult);
267                     }
268
269                     ByteWrapper outByteWrapper = (ByteWrapper) convertResult.get("outByteWrapper");
270                     inputByteArray = outByteWrapper.getBytes();
271                     reader = new PdfReader(inputByteArray);
272                 }
273                 if (reader != null) {
274                     int n = reader.getNumberOfPages();
275                     for (int i=0; i < n; i++) {
276                         PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
277                         //cb.addTemplate(pg, left, height * pgCnt);
278
writer.addPage(pg);
279                         pgCnt++;
280                     }
281                 }
282             }
283             document.close();
284             ByteWrapper outByteWrapper = new ByteWrapper(baos.toByteArray());
285
286             Map JavaDoc results = ServiceUtil.returnSuccess();
287             results.put("outByteWrapper", outByteWrapper);
288             return results;
289         } catch (GenericEntityException e) {
290             return ServiceUtil.returnError(e.toString());
291         } catch (IOException JavaDoc e) {
292             Debug.logError(e, "Error in CompDoc operation: ", module);
293             return ServiceUtil.returnError(e.toString());
294         } catch(Exception JavaDoc e) {
295             Debug.logError(e, "Error in CompDoc operation: ", module);
296             return ServiceUtil.returnError(e.toString());
297         }
298     }
299
300     public static Map JavaDoc renderContentPdf(DispatchContext dctx, Map JavaDoc context) {
301         LocalDispatcher dispatcher = dctx.getDispatcher();
302         Map JavaDoc results = ServiceUtil.returnSuccess();
303         String JavaDoc dataResourceId = null;
304         
305         Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
306         String JavaDoc rootDir = (String JavaDoc) context.get("rootDir");
307         String JavaDoc webSiteId = (String JavaDoc) context.get("webSiteId");
308         String JavaDoc https = (String JavaDoc) context.get("https");
309         
310         GenericDelegator delegator = dctx.getDelegator();
311         
312         String JavaDoc contentId = (String JavaDoc) context.get("contentId");
313         String JavaDoc contentRevisionSeqId = (String JavaDoc) context.get("contentRevisionSeqId");
314         String JavaDoc oooHost = (String JavaDoc) context.get("oooHost");
315         String JavaDoc oooPort = (String JavaDoc) context.get("oooPort");
316         GenericValue userLogin = (GenericValue) context.get("userLogin");
317         
318         try {
319             //Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
320
//ByteArrayOutputStream baos = new ByteArrayOutputStream();
321
Document document = new Document();
322             document.setPageSize(PageSize.LETTER);
323             //Rectangle rect = document.getPageSize();
324
//PdfCopy writer = new PdfCopy(document, baos);
325
document.open();
326
327             GenericValue dataResource = null;
328             if (UtilValidate.isEmpty(contentRevisionSeqId)) {
329                 GenericValue content = delegator.findByPrimaryKeyCache("Content", UtilMisc.toMap("contentId", contentId));
330                 dataResourceId = content.getString("dataResourceId");
331                 Debug.logInfo("SCVH(0b)- dataResourceId:" + dataResourceId, module);
332                 dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
333              } else {
334                 GenericValue contentRevisionItem = delegator.findByPrimaryKeyCache("ContentRevisionItem", UtilMisc.toMap("contentId", contentId, "itemContentId", contentId, "contentRevisionSeqId", contentRevisionSeqId));
335                 if (contentRevisionItem == null) {
336                     throw new ViewHandlerException("ContentRevisionItem record not found for contentId=" + contentId
337                                                    + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId);
338                 }
339                 Debug.logInfo("SCVH(1)- contentRevisionItem:" + contentRevisionItem, module);
340                 Debug.logInfo("SCVH(2)-contentId=" + contentId
341                         + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId, module);
342                 dataResourceId = contentRevisionItem.getString("newDataResourceId");
343                 Debug.logInfo("SCVH(3)- dataResourceId:" + dataResourceId, module);
344                 dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
345             }
346             String JavaDoc inputMimeType = null;
347             if(dataResource != null) {
348                 inputMimeType = (String JavaDoc)dataResource.getString("mimeTypeId");
349             }
350             byte [] inputByteArray = null;
351             if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
352                 ByteWrapper byteWrapper = DataResourceWorker.getContentAsByteWrapper(delegator, dataResourceId, https, webSiteId, locale, rootDir);
353                 inputByteArray = byteWrapper.getBytes();
354             } else if (inputMimeType != null && inputMimeType.equals("text/html")) {
355                 ByteWrapper byteWrapper = DataResourceWorker.getContentAsByteWrapper(delegator, dataResourceId, https, webSiteId, locale, rootDir);
356                 inputByteArray = byteWrapper.getBytes();
357                 String JavaDoc s = new String JavaDoc(inputByteArray);
358                 Debug.logInfo("text/html string:" + s, module);
359             } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
360                 String JavaDoc surveyResponseId = dataResource.getString("relatedDetailId");
361                 String JavaDoc surveyId = null;
362                 String JavaDoc acroFormContentId = null;
363                 GenericValue surveyResponse = null;
364                 if (UtilValidate.isNotEmpty(surveyResponseId)) {
365                     surveyResponse = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
366                     if (surveyResponse != null) {
367                         surveyId = surveyResponse.getString("surveyId");
368                     }
369                 }
370                 if (UtilValidate.isNotEmpty(surveyId)) {
371                     GenericValue survey = delegator.findByPrimaryKey("Survey", UtilMisc.toMap("surveyId", surveyId));
372                     if (survey != null) {
373                         acroFormContentId = survey.getString("acroFormContentId");
374                         if (UtilValidate.isNotEmpty(acroFormContentId)) {
375                             // TODO: is something supposed to be done here?
376
}
377                     }
378                 }
379             
380                 if (surveyResponse != null) {
381                     if (UtilValidate.isEmpty(acroFormContentId)) {
382                         // Create AcroForm PDF
383
Map JavaDoc survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
384                         if (ServiceUtil.isError(survey2PdfResults)) {
385                             return ServiceUtil.returnError("Error building PDF from SurveyResponse: ", null, null, survey2PdfResults);
386                         }
387
388                         ByteWrapper outByteWrapper = (ByteWrapper)survey2PdfResults.get("outByteWrapper");
389                         inputByteArray = outByteWrapper.getBytes();
390                     } else {
391                         // Fill in acroForm
392
Map JavaDoc survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
393                         if (ServiceUtil.isError(survey2AcroFieldResults)) {
394                             return ServiceUtil.returnError("Error setting AcroFields from SurveyResponse: ", null, null, survey2AcroFieldResults);
395                         }
396
397                         ByteWrapper outByteWrapper = (ByteWrapper) survey2AcroFieldResults.get("outByteWrapper");
398                         inputByteArray = outByteWrapper.getBytes();
399                     }
400                 }
401             } else {
402                 ByteWrapper inByteWrapper = DataResourceWorker.getContentAsByteWrapper(delegator, dataResourceId, https, webSiteId, locale, rootDir);
403                 
404                 Map JavaDoc convertInMap = UtilMisc.toMap("userLogin", userLogin, "inByteWrapper", inByteWrapper,
405                         "inputMimeType", inputMimeType, "outputMimeType", "application/pdf");
406                 if (UtilValidate.isNotEmpty(oooHost)) convertInMap.put("oooHost", oooHost);
407                 if (UtilValidate.isNotEmpty(oooPort)) convertInMap.put("oooPort", oooPort);
408
409                 Map JavaDoc convertResult = dispatcher.runSync("convertDocumentByteWrapper", convertInMap);
410                 
411                 if (ServiceUtil.isError(convertResult)) {
412                     return ServiceUtil.returnError("Error in Open", null, null, convertResult);
413                 }
414
415                 ByteWrapper outByteWrapper = (ByteWrapper) convertResult.get("outByteWrapper");
416                 inputByteArray = outByteWrapper.getBytes();
417             }
418             
419             ByteWrapper outByteWrapper = new ByteWrapper(inputByteArray);
420             results.put("outByteWrapper", outByteWrapper);
421         } catch (GenericEntityException e) {
422             return ServiceUtil.returnError(e.toString());
423         } catch (IOException JavaDoc e) {
424             Debug.logError(e, "Error in PDF generation: ", module);
425             return ServiceUtil.returnError(e.toString());
426         } catch(Exception JavaDoc e) {
427             Debug.logError(e, "Error in PDF generation: ", module);
428             return ServiceUtil.returnError(e.toString());
429         }
430         return results;
431     }
432 }
433
Popular Tags