Source Code Cross Referenced for DataResourceWorker.java in  » ERP-CRM-Financial » SourceTap-CRM » org » ofbiz » content » data » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » ERP CRM Financial » SourceTap CRM » org.ofbiz.content.data 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * $Id: DataResourceWorker.java,v 1.17 2004/01/07 19:30:11 byersa Exp $
003:         *
004:         *  Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
005:         *
006:         *  Permission is hereby granted, free of charge, to any person obtaining a
007:         *  copy of this software and associated documentation files (the "Software"),
008:         *  to deal in the Software without restriction, including without limitation
009:         *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
010:         *  and/or sell copies of the Software, and to permit persons to whom the
011:         *  Software is furnished to do so, subject to the following conditions:
012:         *
013:         *  The above copyright notice and this permission notice shall be included
014:         *  in all copies or substantial portions of the Software.
015:         *
016:         *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
017:         *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
018:         *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
019:         *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
020:         *  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
021:         *  OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
022:         *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023:         */
024:        package org.ofbiz.content.data;
025:
026:        import java.io.File;
027:        import java.io.FileNotFoundException;
028:        import java.io.FileReader;
029:        import java.io.IOException;
030:        import java.io.InputStream;
031:        import java.io.StringWriter;
032:        import java.io.Writer;
033:        import java.net.URL;
034:        import java.util.ArrayList;
035:        import java.util.HashMap;
036:        import java.util.List;
037:        import java.util.Locale;
038:        import java.util.Map;
039:
040:        import javax.servlet.http.HttpServletRequest;
041:
042:        import org.apache.commons.fileupload.DiskFileUpload;
043:        import org.apache.commons.fileupload.FileItem;
044:        import org.apache.commons.fileupload.FileUploadException;
045:        import org.ofbiz.base.util.Debug;
046:        import org.ofbiz.base.util.GeneralException;
047:        import org.ofbiz.base.util.UtilMisc;
048:        import org.ofbiz.base.util.UtilProperties;
049:        import org.ofbiz.base.util.UtilValidate;
050:        import org.ofbiz.content.email.NotificationServices;
051:        import org.ofbiz.content.webapp.ftl.FreeMarkerWorker;
052:        import org.ofbiz.entity.GenericDelegator;
053:        import org.ofbiz.entity.GenericEntityException;
054:        import org.ofbiz.entity.GenericValue;
055:        import org.ofbiz.service.GenericServiceException;
056:        import org.ofbiz.service.LocalDispatcher;
057:
058:        import freemarker.template.TemplateException;
059:
060:        /**
061:         * DataResourceWorker Class
062:         * 
063:         * @author <a href="mailto:byersa@automationgroups.com">Al Byers</a>
064:         * @author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
065:         * @version $Revision: 1.17 $
066:         * @since 3.0
067:         */
068:        public class DataResourceWorker {
069:
070:            public static final String module = DataResourceWorker.class
071:                    .getName();
072:
073:            /**
074:             * Traverses the DataCategory parent/child structure and put it in categoryNode. Returns non-null error string if there is an error.
075:             * @param depth The place on the categoryTypesIds to start collecting.
076:             * @param getAll Indicates that all descendants are to be gotten. Used as "true" to populate an 
077:             *     indented select list.
078:             */
079:            public static String getDataCategoryMap(GenericDelegator delegator,
080:                    int depth, Map categoryNode, List categoryTypeIds,
081:                    boolean getAll) throws GenericEntityException {
082:                String errorMsg = null;
083:                String parentCategoryId = (String) categoryNode.get("id");
084:                String currentDataCategoryId = null;
085:                int sz = categoryTypeIds.size();
086:
087:                // The categoryTypeIds has the most senior types at the end, so it is necessary to 
088:                // work backwards. As "depth" is incremented, that is the effect.
089:                // The convention for the topmost type is "ROOT".
090:                if (depth >= 0 && (sz - depth) > 0) {
091:                    currentDataCategoryId = (String) categoryTypeIds.get(sz
092:                            - depth - 1);
093:                }
094:
095:                // Find all the categoryTypes that are children of the categoryNode.
096:                String matchValue = null;
097:                if (parentCategoryId != null) {
098:                    matchValue = parentCategoryId;
099:                } else {
100:                    matchValue = null;
101:                }
102:                List categoryValues = delegator.findByAndCache("DataCategory",
103:                        UtilMisc.toMap("parentCategoryId", matchValue));
104:                categoryNode.put("count", new Integer(categoryValues.size()));
105:                List subCategoryIds = new ArrayList();
106:                for (int i = 0; i < categoryValues.size(); i++) {
107:                    GenericValue category = (GenericValue) categoryValues
108:                            .get(i);
109:                    String id = (String) category.get("dataCategoryId");
110:                    String categoryName = (String) category.get("categoryName");
111:                    Map newNode = new HashMap();
112:                    newNode.put("id", id);
113:                    newNode.put("name", categoryName);
114:                    errorMsg = getDataCategoryMap(delegator, depth + 1,
115:                            newNode, categoryTypeIds, getAll);
116:                    if (errorMsg != null)
117:                        break;
118:                    subCategoryIds.add(newNode);
119:                }
120:
121:                // The first two parentCategoryId test just make sure that the first level of children
122:                // is gotten. This is a hack to make them available for display, but a more correct
123:                // approach should be formulated.
124:                // The "getAll" switch makes sure all descendants make it into the tree, if true.
125:                // The other test is to only get all the children if the "leaf" node where all the
126:                // children of the leaf are wanted for expansion.
127:                if (parentCategoryId == null
128:                        || parentCategoryId.equals("ROOT")
129:                        || (currentDataCategoryId != null && currentDataCategoryId
130:                                .equals(parentCategoryId)) || getAll) {
131:                    categoryNode.put("kids", subCategoryIds);
132:                }
133:                return errorMsg;
134:            }
135:
136:            /**
137:             * Finds the parents of DataCategory entity and puts them in a list, the start entity at the top.
138:             */
139:            public static void getDataCategoryAncestry(
140:                    GenericDelegator delegator, String dataCategoryId,
141:                    List categoryTypeIds) throws GenericEntityException {
142:                categoryTypeIds.add(dataCategoryId);
143:                GenericValue dataCategoryValue = delegator.findByPrimaryKey(
144:                        "DataCategory", UtilMisc.toMap("dataCategoryId",
145:                                dataCategoryId));
146:                if (dataCategoryValue == null)
147:                    return;
148:                String parentCategoryId = (String) dataCategoryValue
149:                        .get("parentCategoryId");
150:                if (parentCategoryId != null) {
151:                    getDataCategoryAncestry(delegator, parentCategoryId,
152:                            categoryTypeIds);
153:                }
154:                return;
155:            }
156:
157:            /**
158:             * Takes a DataCategory structure and builds a list of maps, one value (id) is the dataCategoryId value and the other is an indented string suitable for
159:             * use in a drop-down pick list.
160:             */
161:            public static void buildList(HashMap nd, List lst, int depth) {
162:                String id = (String) nd.get("id");
163:                String nm = (String) nd.get("name");
164:                String spc = "";
165:                for (int i = 0; i < depth; i++)
166:                    spc += "&nbsp;&nbsp;";
167:                HashMap map = new HashMap();
168:                map.put("dataCategoryId", id);
169:                map.put("categoryName", spc + nm);
170:                if (id != null && !id.equals("ROOT") && !id.equals("")) {
171:                    lst.add(map);
172:                }
173:                List kids = (List) nd.get("kids");
174:                int sz = kids.size();
175:                for (int i = 0; i < sz; i++) {
176:                    HashMap kidNode = (HashMap) kids.get(i);
177:                    buildList(kidNode, lst, depth + 1);
178:                }
179:            }
180:
181:            /**
182:             * Uploads image data from a form and stores it in ImageDataResource. Expects key data in a field identitified by the "idField" value and the binary data
183:             * to be in a field id'd by uploadField.
184:             */
185:            public static String uploadAndStoreImage(
186:                    HttpServletRequest request, String idField,
187:                    String uploadField) {
188:                GenericDelegator delegator = (GenericDelegator) request
189:                        .getAttribute("delegator");
190:
191:                if (Debug.verboseOn())
192:                    Debug.logVerbose("in uploadAndStoreImage, idField:"
193:                            + idField, "");
194:                String idFieldValue = null;
195:                DiskFileUpload fu = new DiskFileUpload();
196:                java.util.List lst = null;
197:                try {
198:                    lst = fu.parseRequest(request);
199:                } catch (FileUploadException e4) {
200:                    request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
201:                    return "error";
202:                }
203:
204:                if (lst.size() == 0) {
205:                    request
206:                            .setAttribute("_ERROR_MESSAGE_",
207:                                    "No files uploaded");
208:                    Debug.logWarning(
209:                            "[DataEvents.uploadImage] No files uploaded",
210:                            module);
211:                    return "error";
212:                }
213:
214:                // This code finds the idField and the upload FileItems
215:                FileItem fi = null;
216:                FileItem imageFi = null;
217:                for (int i = 0; i < lst.size(); i++) {
218:                    fi = (FileItem) lst.get(i);
219:                    //String fn = fi.getName();
220:                    String fieldName = fi.getFieldName();
221:                    String fieldStr = fi.getString();
222:                    if (Debug.verboseOn())
223:                        Debug.logVerbose("in uploadAndStoreImage, fieldName:"
224:                                + fieldName, "");
225:                    if (fieldName.equals(idField)) {
226:                        idFieldValue = fieldStr;
227:                    }
228:                    if (fieldName.equals(uploadField)) {
229:                        imageFi = fi;
230:                    }
231:                }
232:                if (imageFi == null || idFieldValue == null) {
233:                    request.setAttribute("_ERROR_MESSAGE_", "imageFi("
234:                            + imageFi + " or idFieldValue(" + idFieldValue
235:                            + " is null");
236:                    Debug.logWarning("[DataEvents.uploadImage] imageFi("
237:                            + imageFi + " or idFieldValue(" + idFieldValue
238:                            + " is null", module);
239:                    return "error";
240:                }
241:
242:                if (Debug.verboseOn())
243:                    Debug.logVerbose("in uploadAndStoreImage, idFieldValue:"
244:                            + idFieldValue, "");
245:
246:                byte[] imageBytes = imageFi.get();
247:
248:                try {
249:                    GenericValue dataResource = delegator.findByPrimaryKey(
250:                            "DataResource", UtilMisc.toMap("dataResourceId",
251:                                    idFieldValue));
252:                    // Use objectInfo field to store the name of the file, since there is no
253:                    // place in ImageDataResource for it.
254:                    if (dataResource != null) {
255:                        dataResource.set("objectInfo", imageFi.getName());
256:                        dataResource.store();
257:                    }
258:
259:                    // See if this needs to be a create or an update procedure
260:                    GenericValue imageDataResource = delegator
261:                            .findByPrimaryKey("ImageDataResource", UtilMisc
262:                                    .toMap("dataResourceId", idFieldValue));
263:                    if (imageDataResource == null) {
264:                        imageDataResource = delegator.makeValue(
265:                                "ImageDataResource", UtilMisc.toMap(
266:                                        "dataResourceId", idFieldValue));
267:                        imageDataResource.set("imageData", imageBytes);
268:                        imageDataResource.create();
269:                    } else {
270:                        imageDataResource.set("imageData", imageBytes);
271:                        imageDataResource.store();
272:                    }
273:                } catch (GenericEntityException e3) {
274:                    request.setAttribute("_ERROR_MESSAGE_", e3.getMessage());
275:                    return "error";
276:                }
277:
278:                request.setAttribute("dataResourceId", idFieldValue);
279:                request.setAttribute(idField, idFieldValue);
280:                return "success";
281:            }
282:
283:            /**
284:             * callDataResourcePermissionCheck Formats data for a call to the checkContentPermission service.
285:             */
286:            public static String callDataResourcePermissionCheck(
287:                    GenericDelegator delegator, LocalDispatcher dispatcher,
288:                    Map context) {
289:                String permissionStatus = "granted";
290:                String skipPermissionCheck = (String) context
291:                        .get("skipPermissionCheck");
292:
293:                if (skipPermissionCheck == null
294:                        || skipPermissionCheck.length() == 0
295:                        || (!skipPermissionCheck.equalsIgnoreCase("true") && !skipPermissionCheck
296:                                .equalsIgnoreCase("granted"))) {
297:                    GenericValue userLogin = (GenericValue) context
298:                            .get("userLogin");
299:                    Map serviceInMap = new HashMap();
300:                    serviceInMap.put("userLogin", userLogin);
301:                    serviceInMap.put("targetOperationList", context
302:                            .get("targetOperationList"));
303:                    serviceInMap.put("contentPurposeList", context
304:                            .get("contentPurposeList"));
305:                    serviceInMap.put("entityOperation", context
306:                            .get("entityOperation"));
307:
308:                    // It is possible that permission to work with DataResources will be controlled
309:                    // by an external Content entity.
310:                    String ownerContentId = (String) context
311:                            .get("ownerContentId");
312:                    if (ownerContentId != null && ownerContentId.length() > 0) {
313:                        try {
314:                            GenericValue content = delegator.findByPrimaryKey(
315:                                    "Content", UtilMisc.toMap("contentId",
316:                                            ownerContentId));
317:                            if (content != null)
318:                                serviceInMap.put("currentContent", content);
319:                        } catch (GenericEntityException e) {
320:                            Debug.logError(e, "e.getMessage()",
321:                                    "ContentServices");
322:                        }
323:                    }
324:                    try {
325:                        Map permResults = dispatcher.runSync(
326:                                "checkContentPermission", serviceInMap);
327:                        permissionStatus = (String) permResults
328:                                .get("permissionStatus");
329:                    } catch (GenericServiceException e) {
330:                        Debug.logError(e, "Problem checking permissions",
331:                                "ContentServices");
332:                    }
333:                }
334:                return permissionStatus;
335:            }
336:
337:            /**
338:             * Gets image data from ImageDataResource and returns it as a byte array.
339:             */
340:            public static byte[] acquireImage(GenericDelegator delegator,
341:                    String dataResourceId) throws GenericEntityException {
342:                GenericValue imageDataResource = delegator.findByPrimaryKey(
343:                        "ImageDataResource", UtilMisc.toMap("dataResourceId",
344:                                dataResourceId));
345:                byte[] b = null;
346:                if (imageDataResource != null) {
347:                    b = (byte[]) imageDataResource.get("imageData");
348:                }
349:                return b;
350:            }
351:
352:            /**
353:             * Returns the image type.
354:             */
355:            public static String getImageType(GenericDelegator delegator,
356:                    String dataResourceId) throws GenericEntityException {
357:                GenericValue dataResource = delegator.findByPrimaryKey(
358:                        "DataResource", UtilMisc.toMap("dataResourceId",
359:                                dataResourceId));
360:                String imageType = (String) dataResource.get("mimeTypeId");
361:                return imageType;
362:            }
363:
364:            public static String renderDataResourceAsText(
365:                    GenericDelegator delegator, String dataResourceId,
366:                    Map templateContext, GenericValue view, Locale locale,
367:                    String mimeTypeId) throws GeneralException, IOException {
368:                Writer outWriter = new StringWriter();
369:                renderDataResourceAsText(delegator, dataResourceId, outWriter,
370:                        templateContext, view, locale, mimeTypeId);
371:                return outWriter.toString();
372:            }
373:
374:            public static String renderDataResourceAsTextCache(
375:                    GenericDelegator delegator, String dataResourceId,
376:                    Map templateContext, GenericValue view, Locale locale,
377:                    String mimeTypeId) throws GeneralException, IOException {
378:                Writer outWriter = new StringWriter();
379:                renderDataResourceAsTextCache(delegator, dataResourceId,
380:                        outWriter, templateContext, view, locale, mimeTypeId);
381:                return outWriter.toString();
382:            }
383:
384:            public static void renderDataResourceAsText(
385:                    GenericDelegator delegator, String dataResourceId,
386:                    Writer out, Map templateContext, GenericValue view,
387:                    Locale locale, String mimeTypeId) throws GeneralException,
388:                    IOException {
389:                if (templateContext == null) {
390:                    templateContext = new HashMap();
391:                }
392:
393:                Map context = (Map) templateContext.get("context");
394:                if (context == null) {
395:                    context = new HashMap();
396:                }
397:
398:                //if (Debug.verboseOn()) Debug.logVerbose(" in renderDataResourceAsHtml, mimeTypeId:" + mimeTypeId, module);
399:                if (UtilValidate.isEmpty(mimeTypeId)) {
400:                    mimeTypeId = "text/html";
401:                }
402:
403:                // if the target mimeTypeId is not a text type, throw an exception
404:                if (!mimeTypeId.startsWith("text/")) {
405:                    throw new GeneralException(
406:                            "The desired mime-type is not a text type, cannot render as text: "
407:                                    + mimeTypeId);
408:                }
409:
410:                GenericValue dataResource = null;
411:                if (view != null) {
412:                    String entityName = view.getEntityName();
413:                    dataResource = delegator.makeValue("DataResource", null);
414:                    if ("DataResource".equals(entityName)) {
415:                        dataResource.setAllFields(view, true, null, null);
416:                    } else {
417:                        dataResource.setAllFields(view, true, "dr", null);
418:                    }
419:                    //if (Debug.verboseOn()) Debug.logVerbose("in renderDAtaResource(work), view:" + view, "");
420:                    //if (Debug.verboseOn()) Debug.logVerbose("in renderDAtaResource(work), dataResource:" + dataResource, "");
421:                    //if (Debug.verboseOn()) Debug.logVerbose("in renderDAtaResource(work), dataResourceMap:" + dataResourceMap, "");
422:                    dataResourceId = dataResource.getString("dataResourceId");
423:                    if (UtilValidate.isEmpty(dataResourceId)) {
424:                        throw new GeneralException("The dataResourceId ["
425:                                + dataResourceId + "] is empty.");
426:                    }
427:                }
428:
429:                if (dataResource == null || dataResource.isEmpty()) {
430:                    if (dataResourceId == null) {
431:                        throw new GeneralException("DataResourceId is null");
432:                    }
433:                    dataResource = delegator.findByPrimaryKey("DataResource",
434:                            UtilMisc.toMap("dataResourceId", dataResourceId));
435:                }
436:                if (dataResource == null || dataResource.isEmpty()) {
437:                    throw new GeneralException(
438:                            "DataResource not found with id=" + dataResourceId);
439:                }
440:
441:                String drMimeTypeId = dataResource.getString("mimeTypeId");
442:                if (UtilValidate.isEmpty(drMimeTypeId)) {
443:                    drMimeTypeId = "text/plain";
444:                }
445:
446:                String dataTemplateTypeId = dataResource
447:                        .getString("dataTemplateTypeId");
448:
449:                // if this is a template, we need to get the full template text and interpret it, otherwise we should just write a bit at a time to the writer to better support large text
450:                if (UtilValidate.isEmpty(dataTemplateTypeId)
451:                        || "NONE".equals(dataTemplateTypeId)) {
452:                    writeDataResourceText(dataResource, mimeTypeId, locale,
453:                            templateContext, delegator, out);
454:                } else {
455:                    String subContentId = (String) context.get("subContentId");
456:                    if (Debug.verboseOn())
457:                        Debug.logVerbose(
458:                                " in renderDataResourceAsHtml, subContentId:"
459:                                        + subContentId, module);
460:                    if (UtilValidate.isNotEmpty(subContentId)) {
461:                        context.put("contentId", subContentId);
462:                        context.put("subContentId", null);
463:                    }
464:
465:                    //String subContentId2 = (String)context.get("subContentId");
466:
467:                    // get the full text of the DataResource
468:                    String templateText = getDataResourceText(dataResource,
469:                            mimeTypeId, locale, templateContext, delegator);
470:
471:                    //String subContentId3 = (String)context.get("subContentId");
472:
473:                    context.put("mimeTypeId", null);
474:                    templateContext.put("context", context);
475:
476:                    if ("FTL".equals(dataTemplateTypeId)) {
477:                        try {
478:                            FreeMarkerWorker.renderTemplate("DataResource:"
479:                                    + dataResourceId, templateText,
480:                                    templateContext, out);
481:                        } catch (TemplateException e) {
482:                            throw new GeneralException(
483:                                    "Error rendering FTL template", e);
484:                        }
485:                    } else {
486:                        throw new GeneralException("The dataTemplateTypeId ["
487:                                + dataTemplateTypeId + "] is not yet supported");
488:                    }
489:                }
490:            }
491:
492:            public static void renderDataResourceAsTextCache(
493:                    GenericDelegator delegator, String dataResourceId,
494:                    Writer out, Map templateContext, GenericValue view,
495:                    Locale locale, String mimeTypeId) throws GeneralException,
496:                    IOException {
497:                if (templateContext == null) {
498:                    templateContext = new HashMap();
499:                }
500:
501:                Map context = (Map) templateContext.get("context");
502:                if (context == null) {
503:                    context = new HashMap();
504:                }
505:
506:                //if (Debug.verboseOn()) Debug.logVerbose(" in renderDataResourceAsHtml, mimeTypeId:" + mimeTypeId, module);
507:                if (UtilValidate.isEmpty(mimeTypeId)) {
508:                    mimeTypeId = "text/html";
509:                }
510:
511:                // if the target mimeTypeId is not a text type, throw an exception
512:                if (!mimeTypeId.startsWith("text/")) {
513:                    throw new GeneralException(
514:                            "The desired mime-type is not a text type, cannot render as text: "
515:                                    + mimeTypeId);
516:                }
517:
518:                GenericValue dataResource = null;
519:                if (view != null) {
520:                    String entityName = view.getEntityName();
521:                    dataResource = delegator.makeValue("DataResource", null);
522:                    if ("DataResource".equals(entityName)) {
523:                        dataResource.setAllFields(view, true, null, null);
524:                    } else {
525:                        dataResource.setAllFields(view, true, "dr", null);
526:                    }
527:                    String this DataResourceId = null;
528:                    try {
529:                        this DataResourceId = (String) view
530:                                .get("drDataResourceId");
531:                    } catch (Exception e) {
532:                        this DataResourceId = (String) view
533:                                .get("dataResourceId");
534:                    }
535:                    if (Debug.verboseOn())
536:                        Debug.logVerbose("in renderDAtaResource(work), view:"
537:                                + view, "");
538:                    if (Debug.verboseOn())
539:                        Debug.logVerbose(
540:                                "in renderDAtaResource(work), dataResource:"
541:                                        + dataResource, "");
542:                    if (Debug.verboseOn())
543:                        Debug.logVerbose(
544:                                "in renderDAtaResource(work), thisDataResourceId:"
545:                                        + this DataResourceId, "");
546:                    if (UtilValidate.isEmpty(this DataResourceId)) {
547:                        if (UtilValidate.isNotEmpty(dataResourceId))
548:                            view = null; // causes lookup of DataResource
549:                        else
550:                            throw new GeneralException("The dataResourceId ["
551:                                    + dataResourceId + "] is empty.");
552:                    }
553:                }
554:
555:                if (dataResource == null || dataResource.isEmpty()) {
556:                    if (dataResourceId == null) {
557:                        throw new GeneralException("DataResourceId is null");
558:                    }
559:                    dataResource = delegator.findByPrimaryKeyCache(
560:                            "DataResource", UtilMisc.toMap("dataResourceId",
561:                                    dataResourceId));
562:                }
563:                if (dataResource == null || dataResource.isEmpty()) {
564:                    throw new GeneralException(
565:                            "DataResource not found with id=" + dataResourceId);
566:                }
567:
568:                String drMimeTypeId = dataResource.getString("mimeTypeId");
569:                if (UtilValidate.isEmpty(drMimeTypeId)) {
570:                    drMimeTypeId = "text/plain";
571:                }
572:
573:                String dataTemplateTypeId = dataResource
574:                        .getString("dataTemplateTypeId");
575:
576:                // if this is a template, we need to get the full template text and interpret it, otherwise we should just write a bit at a time to the writer to better support large text
577:                if (UtilValidate.isEmpty(dataTemplateTypeId)
578:                        || "NONE".equals(dataTemplateTypeId)) {
579:                    writeDataResourceTextCache(dataResource, mimeTypeId,
580:                            locale, templateContext, delegator, out);
581:                } else {
582:                    String subContentId = (String) context.get("subContentId");
583:                    if (Debug.verboseOn())
584:                        Debug.logVerbose(
585:                                " in renderDataResourceAsHtml, subContentId:"
586:                                        + subContentId, module);
587:                    if (UtilValidate.isNotEmpty(subContentId)) {
588:                        context.put("contentId", subContentId);
589:                        context.put("subContentId", null);
590:                    }
591:
592:                    //String subContentId2 = (String)context.get("subContentId");
593:
594:                    // get the full text of the DataResource
595:                    String templateText = getDataResourceTextCache(
596:                            dataResource, mimeTypeId, locale, templateContext,
597:                            delegator);
598:
599:                    //String subContentId3 = (String)context.get("subContentId");
600:
601:                    context.put("mimeTypeId", null);
602:                    templateContext.put("context", context);
603:
604:                    if ("FTL".equals(dataTemplateTypeId)) {
605:                        try {
606:                            FreeMarkerWorker.renderTemplate("DataResource:"
607:                                    + dataResourceId, templateText,
608:                                    templateContext, out);
609:                        } catch (TemplateException e) {
610:                            throw new GeneralException(
611:                                    "Error rendering FTL template", e);
612:                        }
613:                    } else {
614:                        throw new GeneralException("The dataTemplateTypeId ["
615:                                + dataTemplateTypeId + "] is not yet supported");
616:                    }
617:                }
618:            }
619:
620:            public static String getDataResourceText(GenericValue dataResource,
621:                    String mimeTypeId, Locale locale, Map context,
622:                    GenericDelegator delegator) throws IOException,
623:                    GeneralException {
624:                Writer outWriter = new StringWriter();
625:                writeDataResourceText(dataResource, mimeTypeId, locale,
626:                        context, delegator, outWriter);
627:                return outWriter.toString();
628:            }
629:
630:            public static void writeDataResourceText(GenericValue dataResource,
631:                    String mimeTypeId, Locale locale, Map context,
632:                    GenericDelegator delegator, Writer outWriter)
633:                    throws IOException, GeneralException {
634:                String webSiteId = (String) context.get("webSiteId");
635:                String https = (String) context.get("https");
636:
637:                String dataResourceId = dataResource
638:                        .getString("dataResourceId");
639:                String dataResourceTypeId = dataResource
640:                        .getString("dataResourceTypeId");
641:                if (UtilValidate.isEmpty(dataResourceTypeId)) {
642:                    dataResourceTypeId = "SHORT_TEXT";
643:                }
644:                if (Debug.verboseOn())
645:                    Debug.logVerbose(
646:                            " in writeDataResourceAsHtml, dataResourceId:"
647:                                    + dataResourceId, module);
648:                if (Debug.verboseOn())
649:                    Debug.logVerbose(
650:                            " in writeDataResourceAsHtml, dataResourceTypeId:"
651:                                    + dataResourceTypeId, module);
652:
653:                if (dataResourceTypeId.equals("SHORT_TEXT")) {
654:                    String text = dataResource.getString("objectInfo");
655:                    outWriter.write(text);
656:                } else if (dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
657:                    GenericValue electronicText = delegator.findByPrimaryKey(
658:                            "ElectronicText", UtilMisc.toMap("dataResourceId",
659:                                    dataResourceId));
660:                    String text = electronicText.getString("textData");
661:                    if (Debug.verboseOn())
662:                        Debug.logVerbose(" in writeDataResourceAsHtml, text:"
663:                                + text, module);
664:                    outWriter.write(text);
665:                } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
666:                    // TODO: Is this where the image (or any binary) object URL is created? looks like it is just returning 
667:                    //the ID, maybe is okay, but maybe should create the whole image tag so that text and images can be 
668:                    //interchanged without changing the wrapping template, and so the wrapping template doesn't have to know what the root is, etc
669:                    /*
670:                    // decide how to render based on the mime-types
671:                    // TODO: put this in a separate method to be re-used for file objects as well...
672:                    if ("text/html".equals(mimeTypeId)) {
673:                    } else if ("text/plain".equals(mimeTypeId)) {
674:                    } else {
675:                        throw new GeneralException("The renderDataResourceAsText operation does not yet support the desired mime-type: " + mimeTypeId);
676:                    }
677:                     */
678:
679:                    if (Debug.verboseOn())
680:                        Debug.logVerbose(
681:                                " in renderDataResourceAsHtml(IMAGE), mimeTypeId:"
682:                                        + mimeTypeId, module);
683:                    String text = (String) dataResource.get("dataResourceId");
684:                    outWriter.write(text);
685:                } else if (dataResourceTypeId.equals("LINK")) {
686:                    String text = dataResource.getString("objectInfo");
687:                    outWriter.write(text);
688:                } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
689:                    String text = null;
690:                    URL url = new URL(dataResource.getString("objectInfo"));
691:                    if (url.getHost() != null) { // is absolute
692:                        InputStream in = url.openStream();
693:                        int c;
694:                        StringWriter sw = new StringWriter();
695:                        while ((c = in.read()) != -1) {
696:                            sw.write(c);
697:                        }
698:                        sw.close();
699:                        text = sw.toString();
700:                        if (Debug.verboseOn())
701:                            Debug.logVerbose(
702:                                    " in renderDataResourceAsHtml(URL-ABS), text:"
703:                                            + text, module);
704:                    } else {
705:                        String prefix = buildRequestPrefix(delegator, locale,
706:                                webSiteId, https);
707:                        String sep = "";
708:                        //String s = "";
709:                        if (url.toString().indexOf("/") != 0
710:                                && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
711:                            sep = "/";
712:                        }
713:                        String s2 = prefix + sep + url.toString();
714:                        URL url2 = new URL(s2);
715:                        if (Debug.verboseOn())
716:                            Debug.logVerbose(
717:                                    " in renderDataResourceAsHtml(URL-REL), s2:"
718:                                            + s2, module);
719:                        text = (String) url2.getContent();
720:                        if (Debug.verboseOn())
721:                            Debug.logVerbose(
722:                                    " in renderDataResourceAsHtml(URL-REL), text:"
723:                                            + text, module);
724:                    }
725:                    outWriter.write(text);
726:                } else if (dataResourceTypeId.indexOf("_FILE") >= 0) {
727:                    String rootDir = (String) context.get("rootDir");
728:                    renderFile(dataResourceTypeId, dataResource
729:                            .getString("objectInfo"), rootDir, outWriter);
730:                } else {
731:                    throw new GeneralException("The dataResourceTypeId ["
732:                            + dataResourceTypeId
733:                            + "] is not supported in renderDataResourceAsText");
734:                }
735:            }
736:
737:            public static String getDataResourceTextCache(
738:                    GenericValue dataResource, String mimeTypeId,
739:                    Locale locale, Map context, GenericDelegator delegator)
740:                    throws IOException, GeneralException {
741:                Writer outWriter = new StringWriter();
742:                writeDataResourceText(dataResource, mimeTypeId, locale,
743:                        context, delegator, outWriter);
744:                return outWriter.toString();
745:            }
746:
747:            public static void writeDataResourceTextCache(
748:                    GenericValue dataResource, String mimeTypeId,
749:                    Locale locale, Map context, GenericDelegator delegator,
750:                    Writer outWriter) throws IOException, GeneralException {
751:                String webSiteId = (String) context.get("webSiteId");
752:                String https = (String) context.get("https");
753:
754:                String dataResourceId = dataResource
755:                        .getString("dataResourceId");
756:                String dataResourceTypeId = dataResource
757:                        .getString("dataResourceTypeId");
758:                if (UtilValidate.isEmpty(dataResourceTypeId)) {
759:                    dataResourceTypeId = "SHORT_TEXT";
760:                }
761:                if (Debug.verboseOn())
762:                    Debug.logVerbose(
763:                            " in writeDataResourceAsHtml, dataResourceId:"
764:                                    + dataResourceId, module);
765:                if (Debug.verboseOn())
766:                    Debug.logVerbose(
767:                            " in writeDataResourceAsHtml, dataResourceTypeId:"
768:                                    + dataResourceTypeId, module);
769:
770:                if (dataResourceTypeId.equals("SHORT_TEXT")) {
771:                    String text = dataResource.getString("objectInfo");
772:                    outWriter.write(text);
773:                } else if (dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
774:                    GenericValue electronicText = delegator
775:                            .findByPrimaryKeyCache("ElectronicText", UtilMisc
776:                                    .toMap("dataResourceId", dataResourceId));
777:                    String text = electronicText.getString("textData");
778:                    if (Debug.verboseOn())
779:                        Debug.logVerbose(" in writeDataResourceAsHtml, text:"
780:                                + text, module);
781:                    outWriter.write(text);
782:                } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
783:                    // TODO: Is this where the image (or any binary) object URL is created? looks like it is just returning 
784:                    //the ID, maybe is okay, but maybe should create the whole image tag so that text and images can be 
785:                    //interchanged without changing the wrapping template, and so the wrapping template doesn't have to know what the root is, etc
786:                    /*
787:                    // decide how to render based on the mime-types
788:                    // TODO: put this in a separate method to be re-used for file objects as well...
789:                    if ("text/html".equals(mimeTypeId)) {
790:                    } else if ("text/plain".equals(mimeTypeId)) {
791:                    } else {
792:                        throw new GeneralException("The renderDataResourceAsText operation does not yet support the desired mime-type: " + mimeTypeId);
793:                    }
794:                     */
795:
796:                    if (Debug.verboseOn())
797:                        Debug.logVerbose(
798:                                " in renderDataResourceAsHtml(IMAGE), mimeTypeId:"
799:                                        + mimeTypeId, module);
800:                    String text = (String) dataResource.get("dataResourceId");
801:                    outWriter.write(text);
802:                } else if (dataResourceTypeId.equals("LINK")) {
803:                    String text = dataResource.getString("objectInfo");
804:                    outWriter.write(text);
805:                } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
806:                    String text = null;
807:                    URL url = new URL(dataResource.getString("objectInfo"));
808:                    if (url.getHost() != null) { // is absolute
809:                        InputStream in = url.openStream();
810:                        int c;
811:                        StringWriter sw = new StringWriter();
812:                        while ((c = in.read()) != -1) {
813:                            sw.write(c);
814:                        }
815:                        sw.close();
816:                        text = sw.toString();
817:                        if (Debug.verboseOn())
818:                            Debug.logVerbose(
819:                                    " in renderDataResourceAsHtml(URL-ABS), text:"
820:                                            + text, module);
821:                    } else {
822:                        String prefix = buildRequestPrefix(delegator, locale,
823:                                webSiteId, https);
824:                        String sep = "";
825:                        //String s = "";
826:                        if (url.toString().indexOf("/") != 0
827:                                && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
828:                            sep = "/";
829:                        }
830:                        String s2 = prefix + sep + url.toString();
831:                        URL url2 = new URL(s2);
832:                        if (Debug.verboseOn())
833:                            Debug.logVerbose(
834:                                    " in renderDataResourceAsHtml(URL-REL), s2:"
835:                                            + s2, module);
836:                        text = (String) url2.getContent();
837:                        if (Debug.verboseOn())
838:                            Debug.logVerbose(
839:                                    " in renderDataResourceAsHtml(URL-REL), text:"
840:                                            + text, module);
841:                    }
842:                    outWriter.write(text);
843:                } else if (dataResourceTypeId.indexOf("_FILE") >= 0) {
844:                    String rootDir = (String) context.get("rootDir");
845:                    renderFile(dataResourceTypeId, dataResource
846:                            .getString("objectInfo"), rootDir, outWriter);
847:                } else {
848:                    throw new GeneralException("The dataResourceTypeId ["
849:                            + dataResourceTypeId
850:                            + "] is not supported in renderDataResourceAsText");
851:                }
852:            }
853:
854:            public static void renderFile(String dataResourceTypeId,
855:                    String objectInfo, String rootDir, Writer out)
856:                    throws GeneralException, IOException {
857:                // TODO: this method assumes the file is a text file, if it is an image we should respond differently, see the comment above for IMAGE_OBJECT type data resource
858:
859:                if (dataResourceTypeId.equals("LOCAL_FILE")) {
860:                    File file = new File(objectInfo);
861:                    if (!file.isAbsolute()) {
862:                        throw new GeneralException("File (" + objectInfo
863:                                + ") is not absolute");
864:                    }
865:                    int c;
866:                    if (Debug.verboseOn())
867:                        Debug.logVerbose(
868:                                " in renderDataResourceAsHtml(LOCAL), file:"
869:                                        + file, module);
870:                    FileReader in = new FileReader(file);
871:                    while ((c = in.read()) != -1) {
872:                        out.write(c);
873:                    }
874:                } else if (dataResourceTypeId.equals("OFBIZ_FILE")) {
875:                    String prefix = System.getProperty("ofbiz.home");
876:                    String sep = "";
877:                    if (objectInfo.indexOf("/") != 0
878:                            && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
879:                        sep = "/";
880:                    }
881:                    File file = new File(prefix + sep + objectInfo);
882:                    if (Debug.verboseOn())
883:                        Debug.logVerbose(
884:                                " in renderDataResourceAsHtml(OFBIZ_FILE), file:"
885:                                        + file, module);
886:                    int c;
887:                    FileReader in = new FileReader(file);
888:                    while ((c = in.read()) != -1)
889:                        out.write(c);
890:                } else if (dataResourceTypeId.equals("CONTEXT_FILE")) {
891:                    String prefix = rootDir;
892:                    String sep = "";
893:                    if (objectInfo.indexOf("/") != 0
894:                            && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
895:                        sep = "/";
896:                    }
897:                    File file = new File(prefix + sep + objectInfo);
898:                    int c;
899:                    FileReader in = null;
900:                    try {
901:                        in = new FileReader(file);
902:                    } catch (FileNotFoundException e) {
903:                        if (Debug.verboseOn())
904:                            Debug.logVerbose(
905:                                    " in renderDataResourceAsHtml(CONTEXT_FILE), in FNFexception:"
906:                                            + e.getMessage(), module);
907:                        throw new GeneralException(
908:                                "Could not find context file to render", e);
909:                    } catch (Exception e) {
910:                        Debug.logError(
911:                                " in renderDataResourceAsHtml(CONTEXT_FILE), got exception:"
912:                                        + e.getMessage(), module);
913:                    }
914:                    if (Debug.verboseOn())
915:                        Debug
916:                                .logVerbose(
917:                                        " in renderDataResourceAsHtml(CONTEXT_FILE), after FileReader:",
918:                                        module);
919:                    while ((c = in.read()) != -1) {
920:                        out.write(c);
921:                    }
922:                }
923:                return;
924:            }
925:
926:            public static String buildRequestPrefix(GenericDelegator delegator,
927:                    Locale locale, String webSiteId, String https) {
928:                String prefix = null;
929:                Map prefixValues = new HashMap();
930:                NotificationServices.setBaseUrl(delegator, webSiteId,
931:                        prefixValues);
932:                if (https != null && https.equalsIgnoreCase("true")) {
933:                    prefix = (String) prefixValues.get("baseSecureUrl");
934:                } else {
935:                    prefix = (String) prefixValues.get("baseUrl");
936:                }
937:                if (UtilValidate.isEmpty(prefix)) {
938:                    if (https != null && https.equalsIgnoreCase("true")) {
939:                        prefix = UtilProperties.getMessage("content",
940:                                "baseSecureUrl", locale);
941:                    } else {
942:                        prefix = UtilProperties.getMessage("content",
943:                                "baseUrl", locale);
944:                    }
945:                }
946:                if (Debug.verboseOn())
947:                    Debug.logVerbose("in buildRequestPrefix, prefix:" + prefix,
948:                            "");
949:
950:                return prefix;
951:            }
952:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.