Source Code Cross Referenced for DataResourceWorker.java in  » ERP-CRM-Financial » ofbiz » 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 » ofbiz » org.ofbiz.content.data 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*******************************************************************************
0002:         * Licensed to the Apache Software Foundation (ASF) under one
0003:         * or more contributor license agreements.  See the NOTICE file
0004:         * distributed with this work for additional information
0005:         * regarding copyright ownership.  The ASF licenses this file
0006:         * to you under the Apache License, Version 2.0 (the
0007:         * "License"); you may not use this file except in compliance
0008:         * with the License.  You may obtain a copy of the License at
0009:         * 
0010:         * http://www.apache.org/licenses/LICENSE-2.0
0011:         * 
0012:         * Unless required by applicable law or agreed to in writing,
0013:         * software distributed under the License is distributed on an
0014:         * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
0015:         * KIND, either express or implied.  See the License for the
0016:         * specific language governing permissions and limitations
0017:         * under the License.
0018:         *******************************************************************************/package org.ofbiz.content.data;
0019:
0020:        import java.io.*;
0021:        import java.net.URL;
0022:        import java.net.URLConnection;
0023:        import java.util.ArrayList;
0024:        import java.util.Comparator;
0025:        import java.util.HashMap;
0026:        import java.util.List;
0027:        import java.util.Locale;
0028:        import java.util.Map;
0029:        import java.util.TreeMap;
0030:
0031:        import javax.servlet.http.HttpServletRequest;
0032:        import javax.servlet.http.HttpSession;
0033:        import javax.xml.parsers.ParserConfigurationException;
0034:
0035:        import org.apache.commons.fileupload.DiskFileUpload;
0036:        import org.apache.commons.fileupload.FileItem;
0037:        import org.apache.commons.fileupload.FileUploadException;
0038:        import org.ofbiz.base.util.Debug;
0039:        import org.ofbiz.base.util.GeneralException;
0040:        import org.ofbiz.base.util.UtilHttp;
0041:        import org.ofbiz.base.util.UtilMisc;
0042:        import org.ofbiz.base.util.UtilProperties;
0043:        import org.ofbiz.base.util.UtilValidate;
0044:        import org.ofbiz.base.util.collections.MapStack;
0045:        import org.ofbiz.base.util.template.FreeMarkerWorker;
0046:        import org.ofbiz.base.location.FlexibleLocation;
0047:        import org.ofbiz.content.content.UploadContentAndImage;
0048:        import org.ofbiz.content.email.NotificationServices;
0049:        import org.ofbiz.entity.GenericDelegator;
0050:        import org.ofbiz.entity.GenericEntityException;
0051:        import org.ofbiz.entity.GenericValue;
0052:        import org.ofbiz.entity.util.ByteWrapper;
0053:        import org.ofbiz.service.GenericServiceException;
0054:        import org.ofbiz.service.LocalDispatcher;
0055:        import org.ofbiz.widget.html.HtmlScreenRenderer;
0056:        import org.ofbiz.widget.screen.ModelScreen;
0057:        import org.ofbiz.widget.screen.ScreenFactory;
0058:        import org.ofbiz.widget.screen.ScreenRenderer;
0059:        import org.ofbiz.widget.screen.ScreenStringRenderer;
0060:        import org.xml.sax.SAXException;
0061:
0062:        import freemarker.template.Template;
0063:        import freemarker.template.TemplateException;
0064:        import javolution.util.FastMap;
0065:
0066:        /**
0067:         * DataResourceWorker Class
0068:         */
0069:        public class DataResourceWorker {
0070:
0071:            public static final String module = DataResourceWorker.class
0072:                    .getName();
0073:            public static final String err_resource = "ContentErrorUiLabel";
0074:
0075:            /**
0076:             * Traverses the DataCategory parent/child structure and put it in categoryNode. Returns non-null error string if there is an error.
0077:             * @param depth The place on the categoryTypesIds to start collecting.
0078:             * @param getAll Indicates that all descendants are to be gotten. Used as "true" to populate an
0079:             *     indented select list.
0080:             */
0081:            public static String getDataCategoryMap(GenericDelegator delegator,
0082:                    int depth, Map categoryNode, List categoryTypeIds,
0083:                    boolean getAll) throws GenericEntityException {
0084:                String errorMsg = null;
0085:                String parentCategoryId = (String) categoryNode.get("id");
0086:                String currentDataCategoryId = null;
0087:                int sz = categoryTypeIds.size();
0088:
0089:                // The categoryTypeIds has the most senior types at the end, so it is necessary to
0090:                // work backwards. As "depth" is incremented, that is the effect.
0091:                // The convention for the topmost type is "ROOT".
0092:                if (depth >= 0 && (sz - depth) > 0) {
0093:                    currentDataCategoryId = (String) categoryTypeIds.get(sz
0094:                            - depth - 1);
0095:                }
0096:
0097:                // Find all the categoryTypes that are children of the categoryNode.
0098:                String matchValue = null;
0099:                if (parentCategoryId != null) {
0100:                    matchValue = parentCategoryId;
0101:                } else {
0102:                    matchValue = null;
0103:                }
0104:                List categoryValues = delegator.findByAndCache("DataCategory",
0105:                        UtilMisc.toMap("parentCategoryId", matchValue));
0106:                categoryNode.put("count", new Integer(categoryValues.size()));
0107:                List subCategoryIds = new ArrayList();
0108:                for (int i = 0; i < categoryValues.size(); i++) {
0109:                    GenericValue category = (GenericValue) categoryValues
0110:                            .get(i);
0111:                    String id = (String) category.get("dataCategoryId");
0112:                    String categoryName = (String) category.get("categoryName");
0113:                    Map newNode = new HashMap();
0114:                    newNode.put("id", id);
0115:                    newNode.put("name", categoryName);
0116:                    errorMsg = getDataCategoryMap(delegator, depth + 1,
0117:                            newNode, categoryTypeIds, getAll);
0118:                    if (errorMsg != null)
0119:                        break;
0120:                    subCategoryIds.add(newNode);
0121:                }
0122:
0123:                // The first two parentCategoryId test just make sure that the first level of children
0124:                // is gotten. This is a hack to make them available for display, but a more correct
0125:                // approach should be formulated.
0126:                // The "getAll" switch makes sure all descendants make it into the tree, if true.
0127:                // The other test is to only get all the children if the "leaf" node where all the
0128:                // children of the leaf are wanted for expansion.
0129:                if (parentCategoryId == null
0130:                        || parentCategoryId.equals("ROOT")
0131:                        || (currentDataCategoryId != null && currentDataCategoryId
0132:                                .equals(parentCategoryId)) || getAll) {
0133:                    categoryNode.put("kids", subCategoryIds);
0134:                }
0135:                return errorMsg;
0136:            }
0137:
0138:            /**
0139:             * Finds the parents of DataCategory entity and puts them in a list, the start entity at the top.
0140:             */
0141:            public static void getDataCategoryAncestry(
0142:                    GenericDelegator delegator, String dataCategoryId,
0143:                    List categoryTypeIds) throws GenericEntityException {
0144:                categoryTypeIds.add(dataCategoryId);
0145:                GenericValue dataCategoryValue = delegator.findByPrimaryKey(
0146:                        "DataCategory", UtilMisc.toMap("dataCategoryId",
0147:                                dataCategoryId));
0148:                if (dataCategoryValue == null)
0149:                    return;
0150:                String parentCategoryId = (String) dataCategoryValue
0151:                        .get("parentCategoryId");
0152:                if (parentCategoryId != null) {
0153:                    getDataCategoryAncestry(delegator, parentCategoryId,
0154:                            categoryTypeIds);
0155:                }
0156:            }
0157:
0158:            /**
0159:             * 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
0160:             * use in a drop-down pick list.
0161:             */
0162:            public static void buildList(HashMap nd, List lst, int depth) {
0163:                String id = (String) nd.get("id");
0164:                String nm = (String) nd.get("name");
0165:                String spc = "";
0166:                for (int i = 0; i < depth; i++)
0167:                    spc += "&nbsp;&nbsp;";
0168:                HashMap map = new HashMap();
0169:                map.put("dataCategoryId", id);
0170:                map.put("categoryName", spc + nm);
0171:                if (id != null && !id.equals("ROOT") && !id.equals("")) {
0172:                    lst.add(map);
0173:                }
0174:                List kids = (List) nd.get("kids");
0175:                int sz = kids.size();
0176:                for (int i = 0; i < sz; i++) {
0177:                    HashMap kidNode = (HashMap) kids.get(i);
0178:                    buildList(kidNode, lst, depth + 1);
0179:                }
0180:            }
0181:
0182:            /**
0183:             * 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
0184:             * to be in a field id'd by uploadField.
0185:             */
0186:            // TODO: This method is not used and should be removed. amb
0187:            public static String uploadAndStoreImage(
0188:                    HttpServletRequest request, String idField,
0189:                    String uploadField) {
0190:                //GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
0191:
0192:                //String idFieldValue = null;
0193:                DiskFileUpload fu = new DiskFileUpload();
0194:                List lst = null;
0195:                Locale locale = UtilHttp.getLocale(request);
0196:
0197:                try {
0198:                    lst = fu.parseRequest(request);
0199:                } catch (FileUploadException e) {
0200:                    request.setAttribute("_ERROR_MESSAGE_", e.toString());
0201:                    return "error";
0202:                }
0203:
0204:                if (lst.size() == 0) {
0205:                    String errMsg = UtilProperties.getMessage(
0206:                            DataResourceWorker.err_resource,
0207:                            "dataResourceWorker.no_files_uploaded", locale);
0208:                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
0209:                    Debug.logWarning(
0210:                            "[DataEvents.uploadImage] No files uploaded",
0211:                            module);
0212:                    return "error";
0213:                }
0214:
0215:                // This code finds the idField and the upload FileItems
0216:                FileItem fi = null;
0217:                FileItem imageFi = null;
0218:                String imageFileName = null;
0219:                Map passedParams = new HashMap();
0220:                HttpSession session = request.getSession();
0221:                GenericValue userLogin = (GenericValue) session
0222:                        .getAttribute("userLogin");
0223:                passedParams.put("userLogin", userLogin);
0224:                byte[] imageBytes = null;
0225:                for (int i = 0; i < lst.size(); i++) {
0226:                    fi = (FileItem) lst.get(i);
0227:                    //String fn = fi.getName();
0228:                    String fieldName = fi.getFieldName();
0229:                    if (fi.isFormField()) {
0230:                        String fieldStr = fi.getString();
0231:                        passedParams.put(fieldName, fieldStr);
0232:                    } else if (fieldName.startsWith("imageData")) {
0233:                        imageFi = fi;
0234:                        imageBytes = imageFi.get();
0235:                        passedParams.put(fieldName, imageBytes);
0236:                        imageFileName = imageFi.getName();
0237:                        passedParams.put("drObjectInfo", imageFileName);
0238:                        if (Debug.infoOn())
0239:                            Debug.logInfo("[UploadContentAndImage]imageData: "
0240:                                    + imageBytes.length, module);
0241:                    }
0242:                }
0243:
0244:                if (imageBytes != null && imageBytes.length > 0) {
0245:                    String mimeType = getMimeTypeFromImageFileName(imageFileName);
0246:                    if (UtilValidate.isNotEmpty(mimeType)) {
0247:                        passedParams.put("drMimeTypeId", mimeType);
0248:                        try {
0249:                            String returnMsg = UploadContentAndImage
0250:                                    .processContentUpload(passedParams, "",
0251:                                            request);
0252:                            if (returnMsg.equals("error")) {
0253:                                return "error";
0254:                            }
0255:                        } catch (GenericServiceException e) {
0256:                            request.setAttribute("_ERROR_MESSAGE_", e
0257:                                    .getMessage());
0258:                            return "error";
0259:                        }
0260:                    } else {
0261:                        request.setAttribute("_ERROR_MESSAGE_",
0262:                                "mimeType is empty.");
0263:                        return "error";
0264:                    }
0265:                }
0266:                return "success";
0267:            }
0268:
0269:            public static String getMimeTypeFromImageFileName(
0270:                    String imageFileName) {
0271:                String mimeType = null;
0272:                if (UtilValidate.isEmpty(imageFileName))
0273:                    return mimeType;
0274:
0275:                int pos = imageFileName.lastIndexOf(".");
0276:                if (pos < 0)
0277:                    return mimeType;
0278:
0279:                String suffix = imageFileName.substring(pos + 1);
0280:                String suffixLC = suffix.toLowerCase();
0281:                if (suffixLC.equals("jpg"))
0282:                    mimeType = "image/jpeg";
0283:                else
0284:                    mimeType = "image/" + suffixLC;
0285:
0286:                return mimeType;
0287:            }
0288:
0289:            /**
0290:             * callDataResourcePermissionCheck Formats data for a call to the checkContentPermission service.
0291:             */
0292:            public static String callDataResourcePermissionCheck(
0293:                    GenericDelegator delegator, LocalDispatcher dispatcher,
0294:                    Map context) {
0295:                Map permResults = callDataResourcePermissionCheckResult(
0296:                        delegator, dispatcher, context);
0297:                String permissionStatus = (String) permResults
0298:                        .get("permissionStatus");
0299:                return permissionStatus;
0300:            }
0301:
0302:            /**
0303:             * callDataResourcePermissionCheck Formats data for a call to the checkContentPermission service.
0304:             */
0305:            public static Map callDataResourcePermissionCheckResult(
0306:                    GenericDelegator delegator, LocalDispatcher dispatcher,
0307:                    Map context) {
0308:
0309:                Map permResults = new HashMap();
0310:                String skipPermissionCheck = (String) context
0311:                        .get("skipPermissionCheck");
0312:                if (Debug.infoOn())
0313:                    Debug.logInfo(
0314:                            "in callDataResourcePermissionCheckResult, skipPermissionCheck:"
0315:                                    + skipPermissionCheck, "");
0316:
0317:                if (skipPermissionCheck == null
0318:                        || skipPermissionCheck.length() == 0
0319:                        || (!skipPermissionCheck.equalsIgnoreCase("true") && !skipPermissionCheck
0320:                                .equalsIgnoreCase("granted"))) {
0321:                    GenericValue userLogin = (GenericValue) context
0322:                            .get("userLogin");
0323:                    Map serviceInMap = new HashMap();
0324:                    serviceInMap.put("userLogin", userLogin);
0325:                    serviceInMap.put("targetOperationList", context
0326:                            .get("targetOperationList"));
0327:                    serviceInMap.put("contentPurposeList", context
0328:                            .get("contentPurposeList"));
0329:                    serviceInMap.put("entityOperation", context
0330:                            .get("entityOperation"));
0331:
0332:                    // It is possible that permission to work with DataResources will be controlled
0333:                    // by an external Content entity.
0334:                    String ownerContentId = (String) context
0335:                            .get("ownerContentId");
0336:                    if (ownerContentId != null && ownerContentId.length() > 0) {
0337:                        try {
0338:                            GenericValue content = delegator
0339:                                    .findByPrimaryKeyCache("Content", UtilMisc
0340:                                            .toMap("contentId", ownerContentId));
0341:                            if (content != null)
0342:                                serviceInMap.put("currentContent", content);
0343:                        } catch (GenericEntityException e) {
0344:                            Debug.logError(e, "e.getMessage()",
0345:                                    "ContentServices");
0346:                        }
0347:                    }
0348:                    try {
0349:                        permResults = dispatcher.runSync(
0350:                                "checkContentPermission", serviceInMap);
0351:                    } catch (GenericServiceException e) {
0352:                        Debug.logError(e, "Problem checking permissions",
0353:                                "ContentServices");
0354:                    }
0355:                } else {
0356:                    permResults.put("permissionStatus", "granted");
0357:                }
0358:                return permResults;
0359:            }
0360:
0361:            /**
0362:             * Gets image data from ImageDataResource and returns it as a byte array.
0363:             */
0364:            public static byte[] acquireImage(GenericDelegator delegator,
0365:                    String dataResourceId) throws GenericEntityException {
0366:
0367:                byte[] b = null;
0368:                GenericValue dataResource = delegator.findByPrimaryKeyCache(
0369:                        "DataResource", UtilMisc.toMap("dataResourceId",
0370:                                dataResourceId));
0371:                if (dataResource == null)
0372:                    return b;
0373:
0374:                b = acquireImage(delegator, dataResource);
0375:                return b;
0376:            }
0377:
0378:            public static byte[] acquireImage(GenericDelegator delegator,
0379:                    GenericValue dataResource) throws GenericEntityException {
0380:                byte[] b = null;
0381:                String dataResourceTypeId = dataResource
0382:                        .getString("dataResourceTypeId");
0383:                String dataResourceId = dataResource
0384:                        .getString("dataResourceId");
0385:                GenericValue imageDataResource = delegator.findByPrimaryKey(
0386:                        "ImageDataResource", UtilMisc.toMap("dataResourceId",
0387:                                dataResourceId));
0388:                if (imageDataResource != null) {
0389:                    //b = (byte[]) imageDataResource.get("imageData");
0390:                    b = imageDataResource.getBytes("imageData");
0391:                }
0392:                return b;
0393:            }
0394:
0395:            /**
0396:             * Returns the image type.
0397:             */
0398:            public static String getImageType(GenericDelegator delegator,
0399:                    String dataResourceId) throws GenericEntityException {
0400:                GenericValue dataResource = delegator.findByPrimaryKey(
0401:                        "DataResource", UtilMisc.toMap("dataResourceId",
0402:                                dataResourceId));
0403:                String imageType = getImageType(delegator, dataResource);
0404:                return imageType;
0405:            }
0406:
0407:            public static String getMimeType(GenericValue dataResource) {
0408:                String mimeTypeId = null;
0409:                if (dataResource != null) {
0410:                    mimeTypeId = (String) dataResource.get("mimeTypeId");
0411:                    if (UtilValidate.isEmpty(mimeTypeId)) {
0412:                        String fileName = (String) dataResource
0413:                                .get("objectInfo");
0414:                        if (fileName != null && fileName.indexOf('.') > -1) {
0415:                            String fileExtension = fileName.substring(fileName
0416:                                    .lastIndexOf('.') + 1);
0417:                            if (UtilValidate.isNotEmpty(fileExtension)) {
0418:                                GenericValue ext = null;
0419:                                try {
0420:                                    ext = dataResource.getDelegator()
0421:                                            .findByPrimaryKey(
0422:                                                    "FileExtension",
0423:                                                    UtilMisc.toMap(
0424:                                                            "fileExtensionId",
0425:                                                            fileExtension));
0426:                                } catch (GenericEntityException e) {
0427:                                    Debug.logError(e, module);
0428:                                }
0429:                                if (ext != null) {
0430:                                    mimeTypeId = ext.getString("mimeTypeId");
0431:                                }
0432:                            }
0433:                        }
0434:
0435:                        // check one last time
0436:                        if (UtilValidate.isEmpty(mimeTypeId)) {
0437:                            // use a default mime type
0438:                            mimeTypeId = "application/octet-stream";
0439:                        }
0440:                    }
0441:                }
0442:                return mimeTypeId;
0443:            }
0444:
0445:            /** @deprecated */
0446:            public static String getImageType(GenericDelegator delegator,
0447:                    GenericValue dataResource) {
0448:                String imageType = null;
0449:                if (dataResource != null) {
0450:                    imageType = (String) dataResource.get("mimeTypeId");
0451:                    if (UtilValidate.isEmpty(imageType)) {
0452:                        String imageFileNameExt = null;
0453:                        String imageFileName = (String) dataResource
0454:                                .get("objectInfo");
0455:                        if (UtilValidate.isNotEmpty(imageFileName)) {
0456:                            int pos = imageFileName.lastIndexOf(".");
0457:                            if (pos >= 0)
0458:                                imageFileNameExt = imageFileName
0459:                                        .substring(pos + 1);
0460:                        }
0461:                        imageType = "image/" + imageFileNameExt;
0462:                    }
0463:                }
0464:                return imageType;
0465:            }
0466:
0467:            public static String buildRequestPrefix(GenericDelegator delegator,
0468:                    Locale locale, String webSiteId, String https) {
0469:                Map prefixValues = FastMap.newInstance();
0470:                String prefix;
0471:
0472:                NotificationServices.setBaseUrl(delegator, webSiteId,
0473:                        prefixValues);
0474:                if (https != null && https.equalsIgnoreCase("true")) {
0475:                    prefix = (String) prefixValues.get("baseSecureUrl");
0476:                } else {
0477:                    prefix = (String) prefixValues.get("baseUrl");
0478:                }
0479:                if (UtilValidate.isEmpty(prefix)) {
0480:                    if (https != null && https.equalsIgnoreCase("true")) {
0481:                        prefix = UtilProperties.getMessage("content",
0482:                                "baseSecureUrl", locale);
0483:                    } else {
0484:                        prefix = UtilProperties.getMessage("content",
0485:                                "baseUrl", locale);
0486:                    }
0487:                }
0488:
0489:                return prefix;
0490:            }
0491:
0492:            public static File getContentFile(String dataResourceTypeId,
0493:                    String objectInfo, String contextRoot)
0494:                    throws GeneralException, FileNotFoundException {
0495:                File file = null;
0496:
0497:                if (dataResourceTypeId.equals("LOCAL_FILE")
0498:                        || dataResourceTypeId.equals("LOCAL_FILE_BIN")) {
0499:                    file = new File(objectInfo);
0500:                    if (!file.exists()) {
0501:                        throw new FileNotFoundException("No file found: "
0502:                                + (objectInfo));
0503:                    }
0504:                    if (!file.isAbsolute()) {
0505:                        throw new GeneralException("File (" + objectInfo
0506:                                + ") is not absolute");
0507:                    }
0508:                } else if (dataResourceTypeId.equals("OFBIZ_FILE")
0509:                        || dataResourceTypeId.equals("OFBIZ_FILE_BIN")) {
0510:                    String prefix = System.getProperty("ofbiz.home");
0511:
0512:                    String sep = "";
0513:                    if (objectInfo.indexOf("/") != 0
0514:                            && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
0515:                        sep = "/";
0516:                    }
0517:                    file = new File(prefix + sep + objectInfo);
0518:                    if (!file.exists()) {
0519:                        throw new FileNotFoundException("No file found: "
0520:                                + (prefix + sep + objectInfo));
0521:                    }
0522:                } else if (dataResourceTypeId.equals("CONTEXT_FILE")
0523:                        || dataResourceTypeId.equals("CONTEXT_FILE_BIN")) {
0524:                    if (UtilValidate.isEmpty(contextRoot)) {
0525:                        throw new GeneralException(
0526:                                "Cannot find CONTEXT_FILE with an empty context root!");
0527:                    }
0528:
0529:                    String sep = "";
0530:                    if (objectInfo.indexOf("/") != 0
0531:                            && contextRoot.lastIndexOf("/") != (contextRoot
0532:                                    .length() - 1)) {
0533:                        sep = "/";
0534:                    }
0535:                    file = new File(contextRoot + sep + objectInfo);
0536:                    if (!file.exists()) {
0537:                        throw new FileNotFoundException("No file found: "
0538:                                + (contextRoot + sep + objectInfo));
0539:                    }
0540:                }
0541:
0542:                return file;
0543:            }
0544:
0545:            public static String getDataResourceMimeType(
0546:                    GenericDelegator delegator, String dataResourceId,
0547:                    GenericValue view) throws GenericEntityException {
0548:
0549:                String mimeType = null;
0550:                if (view != null)
0551:                    mimeType = view.getString("drMimeTypeId");
0552:                //if (Debug.infoOn()) Debug.logInfo("getDataResourceMimeType, mimeType(2):" + mimeType, "");
0553:                if (UtilValidate.isEmpty(mimeType)
0554:                        && UtilValidate.isNotEmpty(dataResourceId)) {
0555:                    GenericValue dataResource = delegator
0556:                            .findByPrimaryKeyCache("DataResource", UtilMisc
0557:                                    .toMap("dataResourceId", dataResourceId));
0558:                    //if (Debug.infoOn()) Debug.logInfo("getDataResourceMimeType, dataResource(2):" + dataResource, "");
0559:                    mimeType = dataResource.getString("mimeTypeId");
0560:
0561:                }
0562:                return mimeType;
0563:            }
0564:
0565:            public static String getDataResourceContentUploadPath() {
0566:                String initialPath = UtilProperties.getPropertyValue(
0567:                        "content.properties", "content.upload.path.prefix");
0568:                double maxFiles = UtilProperties.getPropertyNumber(
0569:                        "content.properties", "content.upload.max.files");
0570:                if (maxFiles < 1) {
0571:                    maxFiles = 250;
0572:                }
0573:                String ofbizHome = System.getProperty("ofbiz.home");
0574:
0575:                if (!initialPath.startsWith("/")) {
0576:                    initialPath = "/" + initialPath;
0577:                }
0578:
0579:                // descending comparator
0580:                Comparator desc = new Comparator() {
0581:                    public int compare(Object o1, Object o2) {
0582:                        if (((Long) o1).longValue() > ((Long) o2).longValue()) {
0583:                            return -1;
0584:                        } else if (((Long) o1).longValue() < ((Long) o2)
0585:                                .longValue()) {
0586:                            return 1;
0587:                        }
0588:                        return 0;
0589:                    }
0590:                };
0591:
0592:                // check for the latest subdirectory
0593:                String parentDir = ofbizHome + initialPath;
0594:                File parent = new File(parentDir);
0595:                TreeMap dirMap = new TreeMap(desc);
0596:                if (parent.exists()) {
0597:                    File[] subs = parent.listFiles();
0598:                    for (int i = 0; i < subs.length; i++) {
0599:                        if (subs[i].isDirectory()) {
0600:                            dirMap.put(new Long(subs[0].lastModified()),
0601:                                    subs[i]);
0602:                        }
0603:                    }
0604:                } else {
0605:                    // if the parent doesn't exist; create it now
0606:                    boolean created = parent.mkdir();
0607:                    if (!created) {
0608:                        Debug.logWarning(
0609:                                "Unable to create top level upload directory ["
0610:                                        + parentDir + "].", module);
0611:                    }
0612:                }
0613:
0614:                // first item in map is the most current directory
0615:                File latestDir = null;
0616:                if (dirMap != null && dirMap.size() > 0) {
0617:                    latestDir = (File) dirMap.values().iterator().next();
0618:                    if (latestDir != null) {
0619:                        File[] dirList = latestDir.listFiles();
0620:                        if (dirList.length >= maxFiles) {
0621:                            latestDir = makeNewDirectory(parent);
0622:                        }
0623:                    }
0624:                } else {
0625:                    latestDir = makeNewDirectory(parent);
0626:                }
0627:
0628:                Debug.log("Directory Name : " + latestDir.getName(), module);
0629:                return latestDir.getAbsolutePath().replace('\\', '/');
0630:            }
0631:
0632:            private static File makeNewDirectory(File parent) {
0633:                File latestDir = null;
0634:                boolean newDir = false;
0635:                while (!newDir) {
0636:                    latestDir = new File(parent, ""
0637:                            + System.currentTimeMillis());
0638:                    if (!latestDir.exists()) {
0639:                        latestDir.mkdir();
0640:                        newDir = true;
0641:                    }
0642:                }
0643:                return latestDir;
0644:            }
0645:
0646:            // -------------------------------------
0647:            // DataResource rendering methods
0648:            // -------------------------------------
0649:
0650:            public static String renderDataResourceAsText(
0651:                    GenericDelegator delegator, String dataResourceId,
0652:                    Map templateContext, Locale locale,
0653:                    String targetMimeTypeId, boolean cache)
0654:                    throws GeneralException, IOException {
0655:                Writer writer = new StringWriter();
0656:                renderDataResourceAsText(delegator, dataResourceId, writer,
0657:                        templateContext, locale, targetMimeTypeId, cache);
0658:                return writer.toString();
0659:            }
0660:
0661:            public static void renderDataResourceAsText(
0662:                    GenericDelegator delegator, String dataResourceId,
0663:                    Writer out, Map templateContext, Locale locale,
0664:                    String targetMimeTypeId, boolean cache)
0665:                    throws GeneralException, IOException {
0666:                if (dataResourceId == null) {
0667:                    throw new GeneralException(
0668:                            "Cannot lookup data resource with for a null dataResourceId");
0669:                }
0670:                if (templateContext == null) {
0671:                    templateContext = FastMap.newInstance();
0672:                }
0673:                if (UtilValidate.isEmpty(targetMimeTypeId)) {
0674:                    targetMimeTypeId = "text/html";
0675:                }
0676:                if (locale == null) {
0677:                    locale = Locale.getDefault();
0678:                }
0679:
0680:                // check for a cached template
0681:                if (cache) {
0682:                    String disableCache = UtilProperties.getPropertyValue(
0683:                            "content", "disable.ftl.template.cache");
0684:                    if (disableCache == null
0685:                            || !disableCache.equalsIgnoreCase("true")) {
0686:                        try {
0687:                            Template cachedTemplate = FreeMarkerWorker
0688:                                    .getTemplate("DataResource:"
0689:                                            + dataResourceId);
0690:                            if (cachedTemplate != null) {
0691:                                String subContentId = (String) templateContext
0692:                                        .get("subContentId");
0693:                                if (UtilValidate.isNotEmpty(subContentId)) {
0694:                                    templateContext.put("contentId",
0695:                                            subContentId);
0696:                                    templateContext.put("subContentId", null);
0697:                                    templateContext
0698:                                            .put("globalNodeTrail", null); // Force getCurrentContent to query for subContent
0699:                                }
0700:                                FreeMarkerWorker.renderTemplate(cachedTemplate,
0701:                                        templateContext, out);
0702:                            }
0703:                        } catch (TemplateException e) {
0704:                            Debug.logError("Error rendering FTL template. "
0705:                                    + e.getMessage(), module);
0706:                            throw new GeneralException(
0707:                                    "Error rendering FTL template", e);
0708:                        }
0709:                        return;
0710:                    }
0711:                }
0712:
0713:                // if the target mimeTypeId is not a text type, throw an exception
0714:                if (!targetMimeTypeId.startsWith("text/")) {
0715:                    throw new GeneralException(
0716:                            "The desired mime-type is not a text type, cannot render as text: "
0717:                                    + targetMimeTypeId);
0718:                }
0719:
0720:                // get the data resource object
0721:                GenericValue dataResource = null;
0722:                if (cache) {
0723:                    dataResource = delegator.findByPrimaryKeyCache(
0724:                            "DataResource", UtilMisc.toMap("dataResourceId",
0725:                                    dataResourceId));
0726:                } else {
0727:                    dataResource = delegator.findByPrimaryKey("DataResource",
0728:                            UtilMisc.toMap("dataResourceId", dataResourceId));
0729:                }
0730:
0731:                if (dataResource == null) {
0732:                    throw new GeneralException(
0733:                            "No data resource object found for dataResourceId: ["
0734:                                    + dataResourceId + "]");
0735:                }
0736:
0737:                // a data template attached to the data resource
0738:                String dataTemplateTypeId = dataResource
0739:                        .getString("dataTemplateTypeId");
0740:
0741:                // no template; or template is NONE; render the data
0742:                if (UtilValidate.isEmpty(dataTemplateTypeId)
0743:                        || "NONE".equals(dataTemplateTypeId)) {
0744:                    DataResourceWorker.writeDataResourceText(dataResource,
0745:                            targetMimeTypeId, locale, templateContext,
0746:                            delegator, out, true);
0747:
0748:                    // a template is defined; render the template first
0749:                } else {
0750:                    templateContext.put("mimeTypeId", targetMimeTypeId);
0751:
0752:                    // FTL template
0753:                    if ("FTL".equals(dataTemplateTypeId)) {
0754:                        try {
0755:                            // get the template data for rendering
0756:                            String templateText = getDataResourceText(
0757:                                    dataResource, targetMimeTypeId, locale,
0758:                                    templateContext, delegator, cache);
0759:
0760:                            // render the FTL template
0761:                            FreeMarkerWorker.renderTemplate("DataResource:"
0762:                                    + dataResourceId, templateText,
0763:                                    templateContext, out);
0764:                        } catch (TemplateException e) {
0765:                            throw new GeneralException(
0766:                                    "Error rendering FTL template", e);
0767:                        }
0768:
0769:                        // Screen Widget template
0770:                    } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) {
0771:                        try {
0772:                            MapStack context = MapStack.create(templateContext);
0773:                            context.put("locale", locale);
0774:
0775:                            // prepare the map for preRenderedContent
0776:                            Map prc = FastMap.newInstance();
0777:                            String textData = (String) context.get("textData");
0778:                            String mapKey = (String) context.get("mapKey");
0779:                            if (mapKey != null) {
0780:                                prc.put(mapKey, textData);
0781:                            }
0782:                            prc.put("body", textData); // used for default screen defs
0783:                            context.put("preRenderedContent", prc);
0784:
0785:                            // get the screen renderer; or create a new one
0786:                            ScreenRenderer screens = (ScreenRenderer) context
0787:                                    .get("screens");
0788:                            if (screens == null) {
0789:                                screens = new ScreenRenderer(out, context,
0790:                                        new HtmlScreenRenderer());
0791:                                screens.getContext().put("screens", screens);
0792:                            }
0793:
0794:                            // render the screen
0795:                            ScreenStringRenderer renderer = screens
0796:                                    .getScreenStringRenderer();
0797:                            String combinedName = (String) dataResource
0798:                                    .get("objectInfo");
0799:                            ModelScreen modelScreen = ScreenFactory
0800:                                    .getScreenFromLocation(combinedName);
0801:                            modelScreen.renderScreenString(out, context,
0802:                                    renderer);
0803:                        } catch (SAXException e) {
0804:                            throw new GeneralException(
0805:                                    "Error rendering Screen template", e);
0806:                        } catch (ParserConfigurationException e) {
0807:                            throw new GeneralException(
0808:                                    "Error rendering Screen template", e);
0809:                        }
0810:                    } else {
0811:                        throw new GeneralException("The dataTemplateTypeId ["
0812:                                + dataTemplateTypeId + "] is not yet supported");
0813:                    }
0814:                }
0815:            }
0816:
0817:            /** @deprecated */
0818:            public static String renderDataResourceAsText(
0819:                    GenericDelegator delegator, String dataResourceId,
0820:                    Map templateContext, GenericValue view, Locale locale,
0821:                    String mimeTypeId) throws GeneralException, IOException {
0822:                return renderDataResourceAsText(delegator, dataResourceId,
0823:                        templateContext, locale, mimeTypeId, false);
0824:            }
0825:
0826:            /** @deprecated */
0827:            public static void renderDataResourceAsText(
0828:                    GenericDelegator delegator, String dataResourceId,
0829:                    Writer out, Map templateContext, GenericValue view,
0830:                    Locale locale, String targetMimeTypeId)
0831:                    throws GeneralException, IOException {
0832:                renderDataResourceAsText(delegator, dataResourceId, out,
0833:                        templateContext, locale, targetMimeTypeId, false);
0834:            }
0835:
0836:            /** @deprecated */
0837:            public static String renderDataResourceAsTextCache(
0838:                    GenericDelegator delegator, String dataResourceId,
0839:                    Map templateContext, GenericValue view, Locale locale,
0840:                    String mimeTypeId) throws GeneralException, IOException {
0841:                return renderDataResourceAsText(delegator, dataResourceId,
0842:                        templateContext, locale, mimeTypeId, true);
0843:            }
0844:
0845:            /** @deprecated */
0846:            public static void renderDataResourceAsTextCache(
0847:                    GenericDelegator delegator, String dataResourceId,
0848:                    Writer out, Map templateContext, GenericValue view,
0849:                    Locale locale, String targetMimeTypeId)
0850:                    throws GeneralException, IOException {
0851:                renderDataResourceAsText(delegator, dataResourceId, out,
0852:                        templateContext, locale, targetMimeTypeId, true);
0853:            }
0854:
0855:            // ----------------------------
0856:            // Data Resource Data Gathering
0857:            // ----------------------------
0858:
0859:            public static String getDataResourceText(GenericValue dataResource,
0860:                    String mimeTypeId, Locale locale, Map context,
0861:                    GenericDelegator delegator, boolean cache)
0862:                    throws IOException, GeneralException {
0863:                Writer out = new StringWriter();
0864:                writeDataResourceText(dataResource, mimeTypeId, locale,
0865:                        context, delegator, out, cache);
0866:                return out.toString();
0867:            }
0868:
0869:            public static void writeDataResourceText(GenericValue dataResource,
0870:                    String mimeTypeId, Locale locale, Map templateContext,
0871:                    GenericDelegator delegator, Writer out, boolean cache)
0872:                    throws IOException, GeneralException {
0873:                Map context = (Map) templateContext.get("context");
0874:                if (context == null) {
0875:                    context = FastMap.newInstance();
0876:                }
0877:                String webSiteId = (String) templateContext.get("webSiteId");
0878:                if (UtilValidate.isEmpty(webSiteId)) {
0879:                    if (context != null)
0880:                        webSiteId = (String) context.get("webSiteId");
0881:                }
0882:
0883:                String https = (String) templateContext.get("https");
0884:                if (UtilValidate.isEmpty(https)) {
0885:                    if (context != null)
0886:                        https = (String) context.get("https");
0887:                }
0888:
0889:                String dataResourceId = dataResource
0890:                        .getString("dataResourceId");
0891:                String dataResourceTypeId = dataResource
0892:                        .getString("dataResourceTypeId");
0893:
0894:                // default type
0895:                if (UtilValidate.isEmpty(dataResourceTypeId)) {
0896:                    dataResourceTypeId = "SHORT_TEXT";
0897:                }
0898:
0899:                // text types
0900:                if ("SHORT_TEXT".equals(dataResourceTypeId)
0901:                        || "LINK".equals(dataResourceTypeId)) {
0902:                    String text = dataResource.getString("objectInfo");
0903:                    writeText(dataResource, text, templateContext, mimeTypeId,
0904:                            locale, out);
0905:                } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
0906:                    GenericValue electronicText;
0907:                    if (cache) {
0908:                        electronicText = delegator.findByPrimaryKeyCache(
0909:                                "ElectronicText", UtilMisc.toMap(
0910:                                        "dataResourceId", dataResourceId));
0911:                    } else {
0912:                        electronicText = delegator.findByPrimaryKey(
0913:                                "ElectronicText", UtilMisc.toMap(
0914:                                        "dataResourceId", dataResourceId));
0915:                    }
0916:                    String text = electronicText.getString("textData");
0917:                    writeText(dataResource, text, templateContext, mimeTypeId,
0918:                            locale, out);
0919:
0920:                    // object types
0921:                } else if (dataResourceTypeId.endsWith("_OBJECT")) {
0922:                    String text = (String) dataResource.get("dataResourceId");
0923:                    writeText(dataResource, text, templateContext, mimeTypeId,
0924:                            locale, out);
0925:
0926:                    // resource type
0927:                } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
0928:                    String text = null;
0929:                    URL url = FlexibleLocation.resolveLocation(dataResource
0930:                            .getString("objectInfo"));
0931:
0932:                    if (url.getHost() != null) { // is absolute
0933:                        InputStream in = url.openStream();
0934:                        int c;
0935:                        StringWriter sw = new StringWriter();
0936:                        while ((c = in.read()) != -1) {
0937:                            sw.write(c);
0938:                        }
0939:                        sw.close();
0940:                        text = sw.toString();
0941:                    } else {
0942:                        String prefix = DataResourceWorker.buildRequestPrefix(
0943:                                delegator, locale, webSiteId, https);
0944:                        String sep = "";
0945:                        if (url.toString().indexOf("/") != 0
0946:                                && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
0947:                            sep = "/";
0948:                        }
0949:                        String fixedUrlStr = prefix + sep + url.toString();
0950:                        URL fixedUrl = new URL(fixedUrlStr);
0951:                        text = (String) fixedUrl.getContent();
0952:                    }
0953:                    out.write(text);
0954:
0955:                    // file types
0956:                } else if (dataResourceTypeId.endsWith("_FILE_BIN")) {
0957:                    writeText(dataResource, dataResourceId, templateContext,
0958:                            mimeTypeId, locale, out);
0959:                } else if (dataResourceTypeId.endsWith("_FILE")) {
0960:                    String dataResourceMimeTypeId = dataResource
0961:                            .getString("mimeTypeId");
0962:                    String objectInfo = dataResource.getString("objectInfo");
0963:                    String rootDir = (String) context.get("rootDir");
0964:
0965:                    if (dataResourceMimeTypeId == null
0966:                            || dataResourceMimeTypeId.startsWith("text")) {
0967:                        renderFile(dataResourceTypeId, objectInfo, rootDir, out);
0968:                    } else {
0969:                        writeText(dataResource, dataResourceId,
0970:                                templateContext, mimeTypeId, locale, out);
0971:                    }
0972:                } else {
0973:                    throw new GeneralException("The dataResourceTypeId ["
0974:                            + dataResourceTypeId
0975:                            + "] is not supported in renderDataResourceAsText");
0976:                }
0977:            }
0978:
0979:            /** @deprecated */
0980:            public static String getDataResourceTextCache(
0981:                    GenericValue dataResource, String mimeTypeId,
0982:                    Locale locale, Map context, GenericDelegator delegator)
0983:                    throws IOException, GeneralException {
0984:                return getDataResourceText(dataResource, mimeTypeId, locale,
0985:                        context, delegator, true);
0986:            }
0987:
0988:            /** @deprecated */
0989:            public static void writeDataResourceTextCache(
0990:                    GenericValue dataResource, String mimeTypeId,
0991:                    Locale locale, Map context, GenericDelegator delegator,
0992:                    Writer outWriter) throws IOException, GeneralException {
0993:                writeDataResourceText(dataResource, mimeTypeId, locale,
0994:                        context, delegator, outWriter, true);
0995:            }
0996:
0997:            /** @deprecated */
0998:            public static String getDataResourceText(GenericValue dataResource,
0999:                    String mimeTypeId, Locale locale, Map context,
1000:                    GenericDelegator delegator) throws IOException,
1001:                    GeneralException {
1002:                return getDataResourceText(dataResource, mimeTypeId, locale,
1003:                        context, delegator, false);
1004:            }
1005:
1006:            /** @deprecated */
1007:            public static void writeDataResourceText(GenericValue dataResource,
1008:                    String mimeTypeId, Locale locale, Map context,
1009:                    GenericDelegator delegator, Writer out) throws IOException,
1010:                    GeneralException {
1011:                writeDataResourceText(dataResource, mimeTypeId, locale,
1012:                        context, delegator, out, false);
1013:            }
1014:
1015:            public static void writeText(GenericValue dataResource,
1016:                    String textData, Map context, String targetMimeTypeId,
1017:                    Locale locale, Writer out) throws GeneralException,
1018:                    IOException {
1019:                String dataResourceMimeTypeId = dataResource
1020:                        .getString("mimeTypeId");
1021:                GenericDelegator delegator = dataResource.getDelegator();
1022:
1023:                // assume HTML as data resource data
1024:                if (UtilValidate.isEmpty(dataResourceMimeTypeId)) {
1025:                    dataResourceMimeTypeId = "text/html";
1026:                }
1027:
1028:                // assume HTML for target
1029:                if (UtilValidate.isEmpty(targetMimeTypeId)) {
1030:                    targetMimeTypeId = "text/html";
1031:                }
1032:
1033:                // we can only render text
1034:                if (!targetMimeTypeId.startsWith("text")) {
1035:                    throw new GeneralException(
1036:                            "Method writeText() only supports rendering text content : "
1037:                                    + targetMimeTypeId + " is not supported");
1038:                }
1039:
1040:                if ("text/html".equals(targetMimeTypeId)) {
1041:                    // get the default mime type template
1042:                    GenericValue mimeTypeTemplate = delegator
1043:                            .findByPrimaryKeyCache("MimeTypeHtmlTemplate",
1044:                                    UtilMisc.toMap("mimeTypeId",
1045:                                            dataResourceMimeTypeId));
1046:
1047:                    if (mimeTypeTemplate != null
1048:                            && mimeTypeTemplate.get("templateLocation") != null) {
1049:                        // prepare the context
1050:                        Map mimeContext = FastMap.newInstance();
1051:                        mimeContext.putAll(context);
1052:                        mimeContext.put("dataResource", dataResource);
1053:                        mimeContext.put("textData", textData);
1054:
1055:                        String mimeString = DataResourceWorker
1056:                                .renderMimeTypeTemplate(mimeTypeTemplate,
1057:                                        context);
1058:                        out.write(mimeString);
1059:                    } else {
1060:                        out.write(textData);
1061:                    }
1062:                } else if ("text/plain".equals(targetMimeTypeId)) {
1063:                    out.write(textData);
1064:                }
1065:            }
1066:
1067:            public static String renderMimeTypeTemplate(
1068:                    GenericValue mimeTypeTemplate, Map context)
1069:                    throws GeneralException, IOException {
1070:                String location = mimeTypeTemplate
1071:                        .getString("templateLocation");
1072:                StringWriter writer = new StringWriter();
1073:                try {
1074:                    FreeMarkerWorker.renderTemplateAtLocation(location,
1075:                            context, writer);
1076:                } catch (TemplateException e) {
1077:                    throw new GeneralException(e.getMessage(), e);
1078:                }
1079:
1080:                return writer.toString();
1081:            }
1082:
1083:            public static void renderFile(String dataResourceTypeId,
1084:                    String objectInfo, String rootDir, Writer out)
1085:                    throws GeneralException, IOException {
1086:                // 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
1087:
1088:                if (dataResourceTypeId.equals("LOCAL_FILE")) {
1089:                    File file = new File(objectInfo);
1090:                    if (!file.isAbsolute()) {
1091:                        throw new GeneralException("File (" + objectInfo
1092:                                + ") is not absolute");
1093:                    }
1094:                    int c;
1095:                    FileReader in = new FileReader(file);
1096:                    while ((c = in.read()) != -1) {
1097:                        out.write(c);
1098:                    }
1099:                } else if (dataResourceTypeId.equals("OFBIZ_FILE")) {
1100:                    String prefix = System.getProperty("ofbiz.home");
1101:                    String sep = "";
1102:                    if (objectInfo.indexOf("/") != 0
1103:                            && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
1104:                        sep = "/";
1105:                    }
1106:                    File file = new File(prefix + sep + objectInfo);
1107:                    int c;
1108:                    FileReader in = new FileReader(file);
1109:                    while ((c = in.read()) != -1)
1110:                        out.write(c);
1111:                } else if (dataResourceTypeId.equals("CONTEXT_FILE")) {
1112:                    String prefix = rootDir;
1113:                    String sep = "";
1114:                    if (objectInfo.indexOf("/") != 0
1115:                            && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
1116:                        sep = "/";
1117:                    }
1118:                    File file = new File(prefix + sep + objectInfo);
1119:                    int c;
1120:                    FileReader in = null;
1121:                    try {
1122:                        in = new FileReader(file);
1123:                        String enc = in.getEncoding();
1124:                        if (Debug.infoOn())
1125:                            Debug.logInfo("in serveImage, encoding:" + enc,
1126:                                    module);
1127:
1128:                    } catch (FileNotFoundException e) {
1129:                        Debug
1130:                                .logError(
1131:                                        e,
1132:                                        " in renderDataResourceAsHtml(CONTEXT_FILE), in FNFexception:",
1133:                                        module);
1134:                        throw new GeneralException(
1135:                                "Could not find context file to render", e);
1136:                    } catch (Exception e) {
1137:                        Debug.logError(
1138:                                " in renderDataResourceAsHtml(CONTEXT_FILE), got exception:"
1139:                                        + e.getMessage(), module);
1140:                    }
1141:                    while ((c = in.read()) != -1) {
1142:                        out.write(c);
1143:                    }
1144:                    //out.flush();
1145:                }
1146:            }
1147:
1148:            // ----------------------------
1149:            // Data Resource Streaming
1150:            // ----------------------------
1151:
1152:            /**
1153:             * getDataResourceStream - gets an InputStream and Content-Length of a DataResource
1154:             *
1155:             * @param dataResource
1156:             * @param https
1157:             * @param webSiteId
1158:             * @param locale
1159:             * @param contextRoot
1160:             * @return Map containing 'stream': the InputStream and 'length' a Long containing the content-length
1161:             * @throws IOException
1162:             * @throws GeneralException
1163:             */
1164:            public static Map getDataResourceStream(GenericValue dataResource,
1165:                    String https, String webSiteId, Locale locale,
1166:                    String contextRoot, boolean cache) throws IOException,
1167:                    GeneralException {
1168:                if (dataResource == null) {
1169:                    throw new GeneralException(
1170:                            "Cannot stream null data resource!");
1171:                }
1172:
1173:                String dataResourceTypeId = dataResource
1174:                        .getString("dataResourceTypeId");
1175:                String dataResourceId = dataResource
1176:                        .getString("dataResourceId");
1177:                GenericDelegator delegator = dataResource.getDelegator();
1178:
1179:                // first text based data
1180:                if (dataResourceTypeId.endsWith("_TEXT")
1181:                        || "LINK".equals(dataResourceTypeId)) {
1182:                    String text = "";
1183:
1184:                    if ("SHORT_TEXT".equals(dataResourceTypeId)
1185:                            || "LINK".equals(dataResourceTypeId)) {
1186:                        text = dataResource.getString("objectInfo");
1187:                    } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
1188:                        GenericValue electronicText;
1189:                        if (cache) {
1190:                            electronicText = delegator.findByPrimaryKeyCache(
1191:                                    "ElectronicText", UtilMisc.toMap(
1192:                                            "dataResourceId", dataResourceId));
1193:                        } else {
1194:                            electronicText = delegator.findByPrimaryKey(
1195:                                    "ElectronicText", UtilMisc.toMap(
1196:                                            "dataResourceId", dataResourceId));
1197:                        }
1198:                        if (electronicText != null) {
1199:                            text = electronicText.getString("textData");
1200:                        }
1201:                    } else {
1202:                        throw new GeneralException(
1203:                                "Unsupported TEXT type; cannot stream");
1204:                    }
1205:
1206:                    byte[] bytes = text.getBytes();
1207:                    return UtilMisc.toMap("stream", new ByteArrayInputStream(
1208:                            bytes), "length", new Integer(bytes.length));
1209:
1210:                    // object (binary) data
1211:                } else if (dataResourceTypeId.endsWith("_OBJECT")) {
1212:                    byte[] bytes = new byte[0];
1213:                    GenericValue valObj;
1214:
1215:                    if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
1216:                        if (cache) {
1217:                            valObj = delegator.findByPrimaryKeyCache(
1218:                                    "ImageDataResource", UtilMisc.toMap(
1219:                                            "dataResourceId", dataResourceId));
1220:                        } else {
1221:                            valObj = delegator.findByPrimaryKey(
1222:                                    "ImageDataResource", UtilMisc.toMap(
1223:                                            "dataResourceId", dataResourceId));
1224:                        }
1225:                        if (valObj != null) {
1226:                            bytes = valObj.getBytes("imageData");
1227:                        }
1228:                    } else if ("VIDEO_OBJECT".equals(dataResourceTypeId)) {
1229:                        if (cache) {
1230:                            valObj = delegator.findByPrimaryKeyCache(
1231:                                    "VideoDataResource", UtilMisc.toMap(
1232:                                            "dataResourceId", dataResourceId));
1233:                        } else {
1234:                            valObj = delegator.findByPrimaryKey(
1235:                                    "VideoDataResource", UtilMisc.toMap(
1236:                                            "dataResourceId", dataResourceId));
1237:                        }
1238:                        if (valObj != null) {
1239:                            bytes = valObj.getBytes("videoData");
1240:                        }
1241:                    } else if ("AUDIO_OBJECT".equals(dataResourceTypeId)) {
1242:                        if (cache) {
1243:                            valObj = delegator.findByPrimaryKeyCache(
1244:                                    "AudioDataResource", UtilMisc.toMap(
1245:                                            "dataResourceId", dataResourceId));
1246:                        } else {
1247:                            valObj = delegator.findByPrimaryKey(
1248:                                    "AudioDataResource", UtilMisc.toMap(
1249:                                            "dataResourceId", dataResourceId));
1250:                        }
1251:                        if (valObj != null) {
1252:                            bytes = valObj.getBytes("audioData");
1253:                        }
1254:                    } else if ("OTHER_OBJECT".equals(dataResourceTypeId)) {
1255:                        if (cache) {
1256:                            valObj = delegator.findByPrimaryKeyCache(
1257:                                    "OtherDataResource", UtilMisc.toMap(
1258:                                            "dataResourceId", dataResourceId));
1259:                        } else {
1260:                            valObj = delegator.findByPrimaryKey(
1261:                                    "OtherDataResource", UtilMisc.toMap(
1262:                                            "dataResourceId", dataResourceId));
1263:                        }
1264:                        if (valObj != null) {
1265:                            bytes = valObj.getBytes("dataResourceContent");
1266:                        }
1267:                    } else {
1268:                        throw new GeneralException("Unsupported OBJECT type ["
1269:                                + dataResourceTypeId + "]; cannot stream");
1270:                    }
1271:
1272:                    return UtilMisc.toMap("stream", new ByteArrayInputStream(
1273:                            bytes), "length", new Long(bytes.length));
1274:
1275:                    // file data
1276:                } else if (dataResourceTypeId.endsWith("_FILE")
1277:                        || dataResourceTypeId.endsWith("_FILE_BIN")) {
1278:                    String objectInfo = dataResource.getString("objectInfo");
1279:                    if (UtilValidate.isNotEmpty(objectInfo)) {
1280:                        File file = DataResourceWorker.getContentFile(
1281:                                dataResourceTypeId, objectInfo, contextRoot);
1282:                        return UtilMisc.toMap("stream", new FileInputStream(
1283:                                file), "length", new Long(file.length()));
1284:                    } else {
1285:                        throw new GeneralException(
1286:                                "No objectInfo found for FILE type ["
1287:                                        + dataResourceTypeId
1288:                                        + "]; cannot stream");
1289:                    }
1290:
1291:                    // URL resource data
1292:                } else if ("URL_RESOURCE".equals(dataResourceTypeId)) {
1293:                    String objectInfo = dataResource.getString("objectInfo");
1294:                    if (UtilValidate.isNotEmpty(objectInfo)) {
1295:                        URL url = new URL(objectInfo);
1296:                        if (url.getHost() == null) { // is relative
1297:                            String newUrl = DataResourceWorker
1298:                                    .buildRequestPrefix(delegator, locale,
1299:                                            webSiteId, https);
1300:                            if (!newUrl.endsWith("/")) {
1301:                                newUrl = newUrl + "/";
1302:                            }
1303:                            newUrl = newUrl + url.toString();
1304:                            url = new URL(newUrl);
1305:                        }
1306:
1307:                        URLConnection con = url.openConnection();
1308:                        return UtilMisc.toMap("stream", con.getInputStream(),
1309:                                "length", new Long(con.getContentLength()));
1310:                    } else {
1311:                        throw new GeneralException(
1312:                                "No objectInfo found for URL_RESOURCE type; cannot stream");
1313:                    }
1314:                }
1315:
1316:                // unsupported type
1317:                throw new GeneralException("The dataResourceTypeId ["
1318:                        + dataResourceTypeId
1319:                        + "] is not supported in getDataResourceStream");
1320:            }
1321:
1322:            // TODO: remove this method in favor of getDataResourceStream
1323:            public static void streamDataResource(OutputStream os,
1324:                    GenericDelegator delegator, String dataResourceId,
1325:                    String https, String webSiteId, Locale locale,
1326:                    String rootDir) throws IOException, GeneralException {
1327:                try {
1328:                    GenericValue dataResource = delegator
1329:                            .findByPrimaryKeyCache("DataResource", UtilMisc
1330:                                    .toMap("dataResourceId", dataResourceId));
1331:                    if (dataResource == null) {
1332:                        throw new GeneralException(
1333:                                "Error in streamDataResource: DataResource with ID ["
1334:                                        + dataResourceId + "] was not found.");
1335:                    }
1336:                    String dataResourceTypeId = dataResource
1337:                            .getString("dataResourceTypeId");
1338:                    if (UtilValidate.isEmpty(dataResourceTypeId)) {
1339:                        dataResourceTypeId = "SHORT_TEXT";
1340:                    }
1341:                    String mimeTypeId = dataResource.getString("mimeTypeId");
1342:                    if (UtilValidate.isEmpty(mimeTypeId)) {
1343:                        mimeTypeId = "text/html";
1344:                    }
1345:
1346:                    if (dataResourceTypeId.equals("SHORT_TEXT")) {
1347:                        String text = dataResource.getString("objectInfo");
1348:                        os.write(text.getBytes());
1349:                    } else if (dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
1350:                        GenericValue electronicText = delegator
1351:                                .findByPrimaryKeyCache("ElectronicText",
1352:                                        UtilMisc.toMap("dataResourceId",
1353:                                                dataResourceId));
1354:                        if (electronicText != null) {
1355:                            String text = electronicText.getString("textData");
1356:                            if (text != null)
1357:                                os.write(text.getBytes());
1358:                        }
1359:                    } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
1360:                        byte[] imageBytes = acquireImage(delegator,
1361:                                dataResource);
1362:                        if (imageBytes != null)
1363:                            os.write(imageBytes);
1364:                    } else if (dataResourceTypeId.equals("LINK")) {
1365:                        String text = dataResource.getString("objectInfo");
1366:                        os.write(text.getBytes());
1367:                    } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
1368:                        URL url = new URL(dataResource.getString("objectInfo"));
1369:                        if (url.getHost() == null) { // is relative
1370:                            String prefix = buildRequestPrefix(delegator,
1371:                                    locale, webSiteId, https);
1372:                            String sep = "";
1373:                            //String s = "";
1374:                            if (url.toString().indexOf("/") != 0
1375:                                    && prefix.lastIndexOf("/") != (prefix
1376:                                            .length() - 1)) {
1377:                                sep = "/";
1378:                            }
1379:                            String s2 = prefix + sep + url.toString();
1380:                            url = new URL(s2);
1381:                        }
1382:                        InputStream in = url.openStream();
1383:                        int c;
1384:                        while ((c = in.read()) != -1) {
1385:                            os.write(c);
1386:                        }
1387:                    } else if (dataResourceTypeId.indexOf("_FILE") >= 0) {
1388:                        String objectInfo = dataResource
1389:                                .getString("objectInfo");
1390:                        File inputFile = getContentFile(dataResourceTypeId,
1391:                                objectInfo, rootDir);
1392:                        //long fileSize = inputFile.length();
1393:                        FileInputStream fis = new FileInputStream(inputFile);
1394:                        int c;
1395:                        while ((c = fis.read()) != -1) {
1396:                            os.write(c);
1397:                        }
1398:                    } else {
1399:                        throw new GeneralException("The dataResourceTypeId ["
1400:                                + dataResourceTypeId
1401:                                + "] is not supported in streamDataResource");
1402:                    }
1403:                } catch (GenericEntityException e) {
1404:                    throw new GeneralException("Error in streamDataResource", e);
1405:                }
1406:            }
1407:
1408:            public static ByteWrapper getContentAsByteWrapper(
1409:                    GenericDelegator delegator, String dataResourceId,
1410:                    String https, String webSiteId, Locale locale,
1411:                    String rootDir) throws IOException, GeneralException {
1412:                ByteArrayOutputStream baos = new ByteArrayOutputStream();
1413:                streamDataResource(baos, delegator, dataResourceId, https,
1414:                        webSiteId, locale, rootDir);
1415:                ByteWrapper byteWrapper = new ByteWrapper(baos.toByteArray());
1416:                return byteWrapper;
1417:            }
1418:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.