KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > content > survey > PdfSurveyServices


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.survey;
19
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileNotFoundException JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.sql.Timestamp JavaDoc;
26 import java.util.Date JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Locale JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Set JavaDoc;
33
34 import org.ofbiz.base.util.Debug;
35 import org.ofbiz.base.util.GeneralException;
36 import org.ofbiz.base.util.UtilDateTime;
37 import org.ofbiz.base.util.UtilMisc;
38 import org.ofbiz.base.util.UtilValidate;
39 import org.ofbiz.content.data.DataResourceWorker;
40 import org.ofbiz.entity.GenericDelegator;
41 import org.ofbiz.entity.GenericEntityException;
42 import org.ofbiz.entity.GenericValue;
43 import org.ofbiz.entity.util.ByteWrapper;
44 import org.ofbiz.entity.util.EntityUtil;
45 import org.ofbiz.service.DispatchContext;
46 import org.ofbiz.service.GenericServiceException;
47 import org.ofbiz.service.LocalDispatcher;
48 import org.ofbiz.service.ModelService;
49 import org.ofbiz.service.ServiceUtil;
50
51 import com.lowagie.text.Chunk;
52 import com.lowagie.text.Document;
53 import com.lowagie.text.DocumentException;
54 import com.lowagie.text.Paragraph;
55 import com.lowagie.text.pdf.AcroFields;
56 import com.lowagie.text.pdf.PdfDictionary;
57 import com.lowagie.text.pdf.PdfName;
58 import com.lowagie.text.pdf.PdfObject;
59 import com.lowagie.text.pdf.PdfReader;
60 import com.lowagie.text.pdf.PdfStamper;
61 import com.lowagie.text.pdf.PdfWriter;
62
63
64 /**
65  * PdfSurveyServices Class
66  *
67  * @author <a HREF="mailto:byersa@automationgroups.com">Al Byers</a>
68  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
69  * @version $Rev: 5462 $
70  * @since 3.2
71  */

72
73 public class PdfSurveyServices {
74     
75     public static final String JavaDoc module = PdfSurveyServices.class.getName();
76
77     /**
78      *
79      */

80     public static Map JavaDoc buildSurveyFromPdf(DispatchContext dctx, Map JavaDoc context) {
81         GenericDelegator delegator = dctx.getDelegator();
82         LocalDispatcher dispatcher = dctx.getDispatcher();
83         GenericValue userLogin = (GenericValue) context.get("userLogin");
84         Timestamp JavaDoc nowTimestamp = UtilDateTime.nowTimestamp();
85         String JavaDoc surveyId = null;
86         try {
87             String JavaDoc surveyName = (String JavaDoc) context.get("surveyName");
88             ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
89             ByteWrapper byteWrapper = getInputByteWrapper(context, delegator);
90             PdfReader pdfReader = new PdfReader(byteWrapper.getBytes());
91             PdfStamper pdfStamper = new PdfStamper(pdfReader, os);
92             AcroFields acroFields = pdfStamper.getAcroFields();
93             HashMap JavaDoc acroFieldMap = acroFields.getFields();
94             
95             String JavaDoc contentId = (String JavaDoc) context.get("contentId");
96             GenericValue survey = null;
97             surveyId = (String JavaDoc) context.get("surveyId");
98             if (UtilValidate.isEmpty(surveyId)) {
99                 surveyId = delegator.getNextSeqId("Survey");
100                 survey = delegator.makeValue("Survey", UtilMisc.toMap("surveyName", surveyName));
101                 survey.set("surveyId", surveyId);
102                 survey.set("allowMultiple", "Y");
103                 survey.set("allowUpdate", "Y");
104                 survey.create();
105             }
106             
107             // create a SurveyQuestionCategory to put the questions in
108
Map JavaDoc createCategoryResultMap = dispatcher.runSync("createSurveyQuestionCategory",
109                     UtilMisc.toMap("description", "From AcroForm in Content [" + contentId + "] for Survey [" + surveyId + "]", "userLogin", userLogin));
110             String JavaDoc surveyQuestionCategoryId = (String JavaDoc) createCategoryResultMap.get("surveyQuestionCategoryId");
111             
112             pdfStamper.setFormFlattening(true);
113             Iterator JavaDoc i = acroFieldMap.keySet().iterator();
114             while (i.hasNext()) {
115                 String JavaDoc fieldName = (String JavaDoc) i.next();
116                 AcroFields.Item item = acroFields.getFieldItem(fieldName);
117                 int type = acroFields.getFieldType(fieldName);
118                 String JavaDoc value = acroFields.getField(fieldName);
119                 Debug.logInfo("fieldName:" + fieldName + "; item: " + item + "; value: " + value, module);
120
121                 GenericValue surveyQuestion = delegator.makeValue("SurveyQuestion", UtilMisc.toMap("question", fieldName));
122                 String JavaDoc surveyQuestionId = delegator.getNextSeqId("SurveyQuestion");
123                 surveyQuestion.set("surveyQuestionId", surveyQuestionId);
124                 surveyQuestion.set("surveyQuestionCategoryId", surveyQuestionCategoryId);
125
126                 if (type == AcroFields.FIELD_TYPE_TEXT) {
127                     surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
128                 } else if (type == AcroFields.FIELD_TYPE_RADIOBUTTON) {
129                     surveyQuestion.set("surveyQuestionTypeId", "OPTION");
130                 } else if (type == AcroFields.FIELD_TYPE_LIST || type == AcroFields.FIELD_TYPE_COMBO) {
131                     surveyQuestion.set("surveyQuestionTypeId", "OPTION");
132                     // TODO: handle these specially with the acroFields.getListOptionDisplay (and getListOptionExport?)
133
String JavaDoc[] listOptionDisplayArray = acroFields.getListOptionDisplay(fieldName);
134                     String JavaDoc[] listOptionExportArray = acroFields.getListOptionExport(fieldName);
135                     Debug.logInfo("listOptionDisplayArray: " + listOptionDisplayArray + "; listOptionExportArray: " + listOptionExportArray, module);
136                 } else {
137                     surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
138                     Debug.logWarning("Building Survey from PDF, fieldName=[" + fieldName + "]: don't know how to handle field type: " + type + "; defaulting to short text", module);
139                 }
140                 
141                 // ==== create a good sequenceNum based on tab order or if no tab order then the page location
142

143                 Integer JavaDoc tabPage = (Integer JavaDoc) item.page.get(0);
144                 Integer JavaDoc tabOrder = (Integer JavaDoc) item.tabOrder.get(0);
145                 Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder, module);
146                 
147                 //array of float multiple of 5. For each of this groups the values are: [page, llx, lly, urx, ury]
148
float[] fieldPositions = acroFields.getFieldPositions(fieldName);
149                 float fieldPage = fieldPositions[0];
150                 float fieldLlx = fieldPositions[1];
151                 float fieldLly = fieldPositions[2];
152                 float fieldUrx = fieldPositions[3];
153                 float fieldUry = fieldPositions[4];
154                 Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry, module);
155
156                 Long JavaDoc sequenceNum = null;
157                 if (tabPage != null && tabOrder != null) {
158                     sequenceNum = new Long JavaDoc(tabPage.intValue() * 1000 + tabOrder.intValue());
159                     Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder + ", sequenceNum=" + sequenceNum, module);
160                 } else if (fieldPositions.length > 0) {
161                     sequenceNum = new Long JavaDoc((long) fieldPage * 10000 + (long) fieldLly * 1000 + (long) fieldLlx);
162                     Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry + ", sequenceNum=" + sequenceNum, module);
163                 }
164                 
165                 // TODO: need to find something better to put into these fields...
166
String JavaDoc annotation = null;
167                 Iterator JavaDoc widgetIter = item.widgets.iterator();
168                 while (widgetIter.hasNext()) {
169                     PdfDictionary dict = (PdfDictionary) widgetIter.next();
170                     
171                     // if the "/Type" value is "/Annot", then get the value of "/TU" for the annotation
172

173                     /* Interesting... this doesn't work, I guess we have to iterate to find the stuff...
174                     PdfObject typeValue = dict.get(new PdfName("/Type"));
175                     if (typeValue != null && "/Annot".equals(typeValue.toString())) {
176                         PdfObject tuValue = dict.get(new PdfName("/TU"));
177                         annotation = tuValue.toString();
178                     }
179                     */

180                     
181                     PdfObject typeValue = null;
182                     PdfObject tuValue = null;
183                     
184                     Set JavaDoc dictKeys = dict.getKeys();
185                     Iterator JavaDoc dictKeyIter = dictKeys.iterator();
186                     while (dictKeyIter.hasNext()) {
187                         PdfName dictKeyName = (PdfName) dictKeyIter.next();
188                         PdfObject dictObject = dict.get(dictKeyName);
189                         
190                         if ("/Type".equals(dictKeyName.toString())) {
191                             typeValue = dictObject;
192                         } else if ("/TU".equals(dictKeyName.toString())) {
193                             tuValue = dictObject;
194                         }
195                         //Debug.logInfo("AcroForm widget fieldName[" + fieldName + "] dictKey[" + dictKeyName.toString() + "] dictValue[" + dictObject.toString() + "]", module);
196
}
197                     if (tuValue != null && typeValue != null && "/Annot".equals(typeValue.toString())) {
198                         annotation = tuValue.toString();
199                     }
200                 }
201                 
202                 surveyQuestion.set("description", fieldName);
203                 if (UtilValidate.isNotEmpty(annotation)) {
204                     surveyQuestion.set("question", annotation);
205                 } else {
206                     surveyQuestion.set("question", fieldName);
207                 }
208
209                 GenericValue surveyQuestionAppl = delegator.makeValue("SurveyQuestionAppl", UtilMisc.toMap("surveyId", surveyId, "surveyQuestionId", surveyQuestionId));
210                 surveyQuestionAppl.set("fromDate", nowTimestamp);
211                 surveyQuestionAppl.set("externalFieldRef", fieldName);
212
213                 if (sequenceNum != null) {
214                     surveyQuestionAppl.set("sequenceNum", sequenceNum);
215                 }
216
217                 surveyQuestion.create();
218                 surveyQuestionAppl.create();
219             }
220             pdfStamper.close();
221             if (UtilValidate.isNotEmpty(contentId)) {
222                 survey = delegator.findByPrimaryKey("Survey", UtilMisc.toMap("surveyId", surveyId));
223                 survey.set("acroFormContentId", contentId);
224                 survey.store();
225             }
226         } catch (GenericEntityException e) {
227             String JavaDoc errMsg = "Error generating PDF: " + e.toString();
228             Debug.logError(e, errMsg, module);
229             return ServiceUtil.returnError(errMsg);
230         } catch(GeneralException e) {
231             System.err.println(e.getMessage());
232             ServiceUtil.returnError(e.getMessage());
233         } catch (Exception JavaDoc e) {
234             String JavaDoc errMsg = "Error generating PDF: " + e.toString();
235             Debug.logError(e, errMsg, module);
236             return ServiceUtil.returnError(errMsg);
237         }
238         
239         Map JavaDoc results = ServiceUtil.returnSuccess();
240         results.put("surveyId", surveyId);
241         return results;
242     }
243     
244     /**
245      *
246      */

247     public static Map JavaDoc buildSurveyResponseFromPdf(DispatchContext dctx, Map JavaDoc context) {
248
249         String JavaDoc surveyResponseId = null;
250         try {
251             
252             GenericDelegator delegator = dctx.getDelegator();
253             String JavaDoc partyId = (String JavaDoc)context.get("partyId");
254             String JavaDoc surveyId = (String JavaDoc)context.get("surveyId");
255             //String contentId = (String)context.get("contentId");
256
surveyResponseId = (String JavaDoc)context.get("surveyResponseId");
257             if (UtilValidate.isNotEmpty(surveyResponseId)) {
258                 GenericValue surveyResponse = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
259                 if (surveyResponse != null) {
260                     surveyId = surveyResponse.getString("surveyId");
261                 }
262             } else {
263                 surveyResponseId = delegator.getNextSeqId("SurveyResponse");
264                 GenericValue surveyResponse = delegator.makeValue("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyId", surveyId, "partyId", partyId));
265                 surveyResponse.set("responseDate", UtilDateTime.nowTimestamp());
266                 surveyResponse.set("lastModifiedDate", UtilDateTime.nowTimestamp());
267                 surveyResponse.create();
268             }
269             
270             ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
271             ByteWrapper byteWrapper = getInputByteWrapper(context, delegator);
272             PdfReader r = new PdfReader(byteWrapper.getBytes());
273             PdfStamper s = new PdfStamper(r,os);
274             AcroFields fs = s.getAcroFields();
275             HashMap JavaDoc hm = fs.getFields();
276             
277             
278             s.setFormFlattening(true);
279             Iterator JavaDoc i = hm.keySet().iterator();
280             while (i.hasNext()) {
281                 String JavaDoc fieldName = (String JavaDoc)i.next();
282                 //AcroFields.Item item = fs.getFieldItem(fieldName);
283
//int type = fs.getFieldType(fieldName);
284
String JavaDoc value = fs.getField(fieldName);
285                 
286                 List JavaDoc questions = delegator.findByAnd("SurveyQuestionAndAppl", UtilMisc.toMap("surveyId", surveyId, "externalFieldRef", fieldName));
287                 if (questions.size() == 0 ) {
288                     Debug.logInfo("No question found for surveyId:" + surveyId + " and externalFieldRef:" + fieldName, module);
289                     continue;
290                 }
291                 
292                 GenericValue surveyQuestionAndAppl = (GenericValue)questions.get(0);
293                 String JavaDoc surveyQuestionId = (String JavaDoc)surveyQuestionAndAppl.get("surveyQuestionId");
294                 String JavaDoc surveyQuestionTypeId = (String JavaDoc)surveyQuestionAndAppl.get("surveyQuestionTypeId");
295                 GenericValue surveyResponseAnswer = delegator.makeValue("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyQuestionId", surveyQuestionId));
296                 if (surveyQuestionTypeId ==null || surveyQuestionTypeId.equals("TEXT_SHORT")) {
297                     surveyResponseAnswer.set("textResponse", value);
298                 }
299
300                 delegator.create(surveyResponseAnswer);
301             }
302             s.close();
303         } catch (GenericEntityException e) {
304             String JavaDoc errMsg = "Error generating PDF: " + e.toString();
305             Debug.logError(e, errMsg, module);
306             return ServiceUtil.returnError(errMsg);
307         } catch(GeneralException e) {
308             System.err.println(e.getMessage());
309             ServiceUtil.returnError(e.getMessage());
310         } catch (Exception JavaDoc e) {
311             String JavaDoc errMsg = "Error generating PDF: " + e.toString();
312             Debug.logError(e, errMsg, module);
313             return ServiceUtil.returnError(errMsg);
314         }
315         
316         Map JavaDoc results = ServiceUtil.returnSuccess();
317         results.put("surveyResponseId", surveyResponseId);
318         return results;
319     }
320
321     /**
322      */

323     public static Map JavaDoc getAcroFieldsFromPdf(DispatchContext dctx, Map JavaDoc context) {
324         
325         Map JavaDoc acroFieldMap = new HashMap JavaDoc();
326         try {
327             ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
328             GenericDelegator delegator = dctx.getDelegator();
329             ByteWrapper byteWrapper = getInputByteWrapper(context, delegator);
330             PdfReader r = new PdfReader(byteWrapper.getBytes());
331             PdfStamper s = new PdfStamper(r,os);
332             AcroFields fs = s.getAcroFields();
333             HashMap JavaDoc map = fs.getFields();
334             
335             s.setFormFlattening(true);
336             
337             // Debug code to get the values for setting TDP
338
// String[] sa = fs.getAppearanceStates("TDP");
339
// for (int i=0;i<sa.length;i++)
340
// Debug.log("Appearance="+sa[i]);
341

342             Iterator JavaDoc iter = map.keySet().iterator();
343             while (iter.hasNext()) {
344                 String JavaDoc fieldName=(String JavaDoc)iter.next();
345                 String JavaDoc parmValue = fs.getField(fieldName);
346                 acroFieldMap.put(fieldName, parmValue);
347             }
348                  
349         } catch(DocumentException e) {
350             System.err.println(e.getMessage());
351             ServiceUtil.returnError(e.getMessage());
352         } catch(GeneralException e) {
353             System.err.println(e.getMessage());
354             ServiceUtil.returnError(e.getMessage());
355         } catch(IOException JavaDoc ioe) {
356             System.err.println(ioe.getMessage());
357             ServiceUtil.returnError(ioe.getMessage());
358         }
359         
360     Map JavaDoc results = ServiceUtil.returnSuccess();
361     results.put("acroFieldMap", acroFieldMap);
362     return results;
363     }
364     
365     /**
366      */

367     public static Map JavaDoc setAcroFields(DispatchContext dctx, Map JavaDoc context) {
368         
369         Map JavaDoc results = ServiceUtil.returnSuccess();
370         GenericDelegator delegator = dctx.getDelegator();
371         try {
372             Map JavaDoc acroFieldMap = (Map JavaDoc)context.get("acroFieldMap");
373             ByteWrapper byteWrapper = getInputByteWrapper(context, delegator);
374             PdfReader r = new PdfReader(byteWrapper.getBytes());
375             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
376             PdfStamper s = new PdfStamper(r, baos);
377             AcroFields fs = s.getAcroFields();
378             Map JavaDoc map = fs.getFields();
379             
380             s.setFormFlattening(true);
381             
382             // Debug code to get the values for setting TDP
383
// String[] sa = fs.getAppearanceStates("TDP");
384
// for (int i=0;i<sa.length;i++)
385
// Debug.log("Appearance="+sa[i]);
386

387             Iterator JavaDoc iter = map.keySet().iterator();
388             while (iter.hasNext()) {
389                 String JavaDoc fieldName=(String JavaDoc)iter.next();
390                 String JavaDoc fieldValue = fs.getField(fieldName);
391                 Object JavaDoc obj = acroFieldMap.get(fieldName);
392                 if (obj instanceof Date JavaDoc) {
393                     Date JavaDoc d=(Date JavaDoc)obj;
394                     fieldValue=UtilDateTime.toDateString(d);
395                 } else if (obj instanceof Long JavaDoc) {
396                     Long JavaDoc lg=(Long JavaDoc)obj;
397                     fieldValue=lg.toString();
398                 } else if (obj instanceof Integer JavaDoc) {
399                     Integer JavaDoc ii=(Integer JavaDoc)obj;
400                     fieldValue=ii.toString();
401                 } else {
402                     fieldValue=(String JavaDoc)obj;
403                 }
404             
405                 if (UtilValidate.isNotEmpty(fieldValue))
406                     fs.setField(fieldName, fieldValue);
407             }
408                  
409             s.close();
410             baos.close();
411             ByteWrapper outByteWrapper = new ByteWrapper(baos.toByteArray());
412             results.put("outByteWrapper", outByteWrapper);
413         } catch(DocumentException e) {
414             System.err.println(e.getMessage());
415             ServiceUtil.returnError(e.getMessage());
416         } catch(GeneralException e) {
417             System.err.println(e.getMessage());
418             ServiceUtil.returnError(e.getMessage());
419         } catch(FileNotFoundException JavaDoc e) {
420             System.err.println(e.getMessage());
421             ServiceUtil.returnError(e.getMessage());
422         } catch(IOException JavaDoc ioe) {
423             System.err.println(ioe.getMessage());
424             ServiceUtil.returnError(ioe.getMessage());
425         } catch(Exception JavaDoc ioe) {
426             System.err.println(ioe.getMessage());
427             ServiceUtil.returnError(ioe.getMessage());
428         }
429         
430     return results;
431     }
432     
433     
434     /**
435      */

436     public static Map JavaDoc buildPdfFromSurveyResponse(DispatchContext dctx, Map JavaDoc context) {
437         GenericDelegator delegator = dctx.getDelegator();
438         //LocalDispatcher dispatcher = dctx.getDispatcher();
439
Map JavaDoc results = ServiceUtil.returnSuccess();
440         String JavaDoc surveyResponseId = (String JavaDoc)context.get("surveyResponseId");
441         String JavaDoc contentId = (String JavaDoc)context.get("contentId");
442         String JavaDoc surveyId = null;
443
444         Document document = new Document();
445         try {
446             if (UtilValidate.isNotEmpty(surveyResponseId)) {
447                 GenericValue surveyResponse = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
448                 if (surveyResponse != null) {
449                     surveyId = surveyResponse.getString("surveyId");
450                 }
451             }
452             if (UtilValidate.isNotEmpty(surveyId) && UtilValidate.isEmpty(contentId)) {
453                 GenericValue survey = delegator.findByPrimaryKey("Survey", UtilMisc.toMap("surveyId", surveyId));
454                 if (survey != null) {
455                     String JavaDoc acroFormContentId = survey.getString("acroFormContentId");
456                     if (UtilValidate.isNotEmpty(acroFormContentId)) {
457                         context.put("contentId", acroFormContentId);
458                     }
459                 }
460             }
461         
462             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
463             PdfWriter.getInstance(document, baos);
464             
465             List JavaDoc responses = delegator.findByAnd("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId));
466             Iterator JavaDoc iter = responses.iterator();
467             while (iter.hasNext()) {
468                 String JavaDoc value = null;
469                 GenericValue surveyResponseAnswer = (GenericValue) iter.next();
470                 String JavaDoc surveyQuestionId = (String JavaDoc) surveyResponseAnswer.get("surveyQuestionId");
471                 GenericValue surveyQuestion = delegator.findByPrimaryKey("SurveyQuestion", UtilMisc.toMap("surveyQuestionId", surveyQuestionId));
472                 String JavaDoc questionType = surveyQuestion.getString("surveyQuestionTypeId");
473                 // DEJ20060227 this isn't used, if needed in the future should get from SurveyQuestionAppl.externalFieldRef String fieldName = surveyQuestion.getString("description");
474
if ("OPTION".equals(questionType)) {
475                     value = surveyResponseAnswer.getString("surveyOptionSeqId");
476                 } else if ("BOOLEAN".equals(questionType)) {
477                     value = surveyResponseAnswer.getString("booleanResponse");
478                 } else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType) || "NUMBER_FLOAT".equals(questionType)) {
479                     Double JavaDoc num = surveyResponseAnswer.getDouble("numericResponse");
480                     if (num != null) {
481                         value = num.toString();
482                     }
483                 } else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
484                     // not really a question; ingore completely
485
} else {
486                     value = surveyResponseAnswer.getString("textResponse");
487                 }
488                 Chunk chunk = new Chunk(surveyQuestion.getString("question") + ": " + value);
489                 Paragraph p = new Paragraph(chunk);
490                 document.add(p);
491             }
492             ByteWrapper outByteWrapper = new ByteWrapper(baos.toByteArray());
493             results.put("outByteWrapper", outByteWrapper);
494         } catch (GenericEntityException e) {
495             System.err.println(e.getMessage());
496             ServiceUtil.returnError(e.getMessage());
497         } catch (DocumentException e) {
498             System.err.println(e.getMessage());
499             ServiceUtil.returnError(e.getMessage());
500         }
501         
502         return results;
503     }
504     
505     /**
506      */

507     public static Map JavaDoc setAcroFieldsFromSurveyResponse(DispatchContext dctx, Map JavaDoc context) {
508         GenericDelegator delegator = dctx.getDelegator();
509         LocalDispatcher dispatcher = dctx.getDispatcher();
510         Map JavaDoc results = ServiceUtil.returnSuccess();
511         Map JavaDoc acroFieldMap = new HashMap JavaDoc();
512         String JavaDoc surveyResponseId = (String JavaDoc)context.get("surveyResponseId");
513         String JavaDoc acroFormContentId = null;
514     
515         try {
516             String JavaDoc surveyId = null;
517             if (UtilValidate.isNotEmpty(surveyResponseId)) {
518                 GenericValue surveyResponse = delegator.findByPrimaryKey("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
519                 if (surveyResponse != null) {
520                     surveyId = surveyResponse.getString("surveyId");
521                 }
522             }
523
524             if (UtilValidate.isNotEmpty(surveyId)) {
525                 GenericValue survey = delegator.findByPrimaryKey("Survey", UtilMisc.toMap("surveyId", surveyId));
526                 if (survey != null) {
527                     acroFormContentId = survey.getString("acroFormContentId");
528                 }
529             }
530             
531             List JavaDoc responses = delegator.findByAnd("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId));
532             Iterator JavaDoc iter = responses.iterator();
533             while (iter.hasNext()) {
534                 String JavaDoc value = null;
535                 GenericValue surveyResponseAnswer = (GenericValue) iter.next();
536                 String JavaDoc surveyQuestionId = (String JavaDoc) surveyResponseAnswer.get("surveyQuestionId");
537
538                 GenericValue surveyQuestion = delegator.findByPrimaryKeyCache("SurveyQuestion", UtilMisc.toMap("surveyQuestionId", surveyQuestionId));
539                 
540                 List JavaDoc surveyQuestionApplList = EntityUtil.filterByDate(delegator.findByAndCache("SurveyQuestionAppl", UtilMisc.toMap("surveyId", surveyId, "surveyQuestionId", surveyQuestionId), UtilMisc.toList("-fromDate")), false);
541                 GenericValue surveyQuestionAppl = EntityUtil.getFirst(surveyQuestionApplList);
542                 
543                 String JavaDoc questionType = surveyQuestion.getString("surveyQuestionTypeId");
544                 String JavaDoc fieldName = surveyQuestionAppl.getString("externalFieldRef");
545                 if ("OPTION".equals(questionType)) {
546                     value = surveyResponseAnswer.getString("surveyOptionSeqId");
547                 } else if ("BOOLEAN".equals(questionType)) {
548                     value = surveyResponseAnswer.getString("booleanResponse");
549                 } else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType) || "NUMBER_FLOAT".equals(questionType)) {
550                     Double JavaDoc num = surveyResponseAnswer.getDouble("numericResponse");
551                     if (num != null) {
552                         value = num.toString();
553                     }
554                 } else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
555                     // not really a question; ingore completely
556
} else {
557                     value = surveyResponseAnswer.getString("textResponse");
558                 }
559                 acroFieldMap.put(fieldName, value);
560             }
561         } catch (GenericEntityException e) {
562             System.err.println(e.getMessage());
563             ServiceUtil.returnError(e.getMessage());
564         }
565         
566         try {
567             ModelService modelService = dispatcher.getDispatchContext().getModelService("setAcroFields");
568             Map JavaDoc ctx = modelService.makeValid(context, "IN");
569             ctx.put("acroFieldMap", acroFieldMap);
570             ctx.put("contentId", acroFormContentId);
571             Map JavaDoc map = dispatcher.runSync("setAcroFields", ctx);
572             if (ServiceUtil.isError(map)) {
573                 String JavaDoc errMsg = ServiceUtil.makeErrorMessage(map, null, null, null, null);
574                 System.err.println(errMsg);
575                 ServiceUtil.returnError(errMsg);
576             }
577             String JavaDoc pdfFileNameOut = (String JavaDoc)context.get("pdfFileNameOut");
578             ByteWrapper outByteWrapper = (ByteWrapper)map.get("outByteWrapper");
579             results.put("outByteWrapper", outByteWrapper);
580             if (UtilValidate.isNotEmpty(pdfFileNameOut)) {
581                 FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(pdfFileNameOut);
582                 fos.write(outByteWrapper.getBytes());
583                 fos.close();
584             }
585         } catch(FileNotFoundException JavaDoc e) {
586             System.err.println(e.getMessage());
587             ServiceUtil.returnError(e.getMessage());
588         } catch(IOException JavaDoc e) {
589             System.err.println(e.getMessage());
590             ServiceUtil.returnError(e.getMessage());
591         } catch (GenericServiceException e) {
592             System.err.println(e.getMessage());
593             ServiceUtil.returnError(e.getMessage());
594         }
595             
596     return results;
597     }
598     
599     public static ByteWrapper getInputByteWrapper(Map JavaDoc context, GenericDelegator delegator) throws GeneralException {
600         
601         ByteWrapper inputByteWrapper = (ByteWrapper)context.get("inputByteWrapper");
602         
603         if (inputByteWrapper == null) {
604             String JavaDoc pdfFileNameIn = (String JavaDoc)context.get("pdfFileNameIn");
605             String JavaDoc contentId = (String JavaDoc)context.get("contentId");
606             if (UtilValidate.isNotEmpty(pdfFileNameIn)) {
607                 try {
608                     FileInputStream JavaDoc fis = new FileInputStream JavaDoc(pdfFileNameIn);
609                     int c;
610                     ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
611                     while ((c = fis.read()) != -1) baos.write(c);
612                     inputByteWrapper = new ByteWrapper(baos.toByteArray());
613                 } catch(FileNotFoundException JavaDoc e) {
614                     throw(new GeneralException(e.getMessage()));
615                 } catch(IOException JavaDoc e) {
616                     throw(new GeneralException(e.getMessage()));
617                 }
618             } else if (UtilValidate.isNotEmpty(contentId)) {
619                 try {
620                     Locale JavaDoc locale = (Locale JavaDoc)context.get("locale");
621                     String JavaDoc https = (String JavaDoc)context.get("https");
622                     String JavaDoc webSiteId = (String JavaDoc)context.get("webSiteId");
623                     String JavaDoc rootDir = (String JavaDoc)context.get("rootDir");
624                     GenericValue content = delegator.findByPrimaryKeyCache("Content", UtilMisc.toMap("contentId", contentId));
625                     String JavaDoc dataResourceId = content.getString("dataResourceId");
626                     inputByteWrapper = DataResourceWorker.getContentAsByteWrapper(delegator, dataResourceId, https, webSiteId, locale, rootDir);
627                 } catch (GenericEntityException e) {
628                     throw(new GeneralException(e.getMessage()));
629                 } catch (IOException JavaDoc e) {
630                     throw(new GeneralException(e.getMessage()));
631                 }
632             }
633         }
634         return inputByteWrapper;
635     }
636 }
637
Popular Tags