KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > content > data > DataResourceWorker


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

24 package org.ofbiz.content.data;
25
26 import java.io.ByteArrayOutputStream JavaDoc;
27 import java.io.File JavaDoc;
28 import java.io.FileInputStream JavaDoc;
29 import java.io.FileNotFoundException JavaDoc;
30 import java.io.FileReader JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.io.OutputStream JavaDoc;
34 import java.io.StringWriter JavaDoc;
35 import java.io.Writer JavaDoc;
36 import java.net.URL JavaDoc;
37 import java.util.ArrayList JavaDoc;
38 import java.util.Comparator JavaDoc;
39 import java.util.HashMap JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.Locale JavaDoc;
42 import java.util.Map JavaDoc;
43 import java.util.TreeMap JavaDoc;
44
45 import javax.servlet.http.HttpServletRequest JavaDoc;
46 import javax.servlet.http.HttpSession JavaDoc;
47 import javax.xml.parsers.ParserConfigurationException JavaDoc;
48
49 import org.apache.commons.fileupload.DiskFileUpload;
50 import org.apache.commons.fileupload.FileItem;
51 import org.apache.commons.fileupload.FileUploadException;
52 import org.ofbiz.base.util.Debug;
53 import org.ofbiz.base.util.GeneralException;
54 import org.ofbiz.base.util.UtilHttp;
55 import org.ofbiz.base.util.UtilMisc;
56 import org.ofbiz.base.util.UtilProperties;
57 import org.ofbiz.base.util.UtilValidate;
58 import org.ofbiz.base.util.collections.MapStack;
59 import org.ofbiz.base.util.template.FreeMarkerWorker;
60 import org.ofbiz.content.content.UploadContentAndImage;
61 import org.ofbiz.content.email.NotificationServices;
62 import org.ofbiz.entity.GenericDelegator;
63 import org.ofbiz.entity.GenericEntityException;
64 import org.ofbiz.entity.GenericValue;
65 import org.ofbiz.entity.util.ByteWrapper;
66 import org.ofbiz.service.GenericServiceException;
67 import org.ofbiz.service.LocalDispatcher;
68 import org.ofbiz.webapp.view.ViewHandlerException;
69 import org.ofbiz.widget.html.HtmlScreenRenderer;
70 import org.ofbiz.widget.screen.ModelScreen;
71 import org.ofbiz.widget.screen.ScreenFactory;
72 import org.ofbiz.widget.screen.ScreenRenderer;
73 import org.ofbiz.widget.screen.ScreenStringRenderer;
74 import org.xml.sax.SAXException JavaDoc;
75
76 import freemarker.template.Template;
77 import freemarker.template.TemplateException;
78
79 //import com.clarkware.profiler.Profiler;
80

81 /**
82  * DataResourceWorker Class
83  *
84  * @author <a HREF="mailto:byersa@automationgroups.com">Al Byers</a>
85  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
86  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
87  * @version $Rev: 7125 $
88  * @since 3.0
89  */

90 public class DataResourceWorker {
91
92     public static final String JavaDoc module = DataResourceWorker.class.getName();
93     public static final String JavaDoc err_resource = "ContentErrorUiLabel";
94
95     /**
96      * Traverses the DataCategory parent/child structure and put it in categoryNode. Returns non-null error string if there is an error.
97      * @param depth The place on the categoryTypesIds to start collecting.
98      * @param getAll Indicates that all descendants are to be gotten. Used as "true" to populate an
99      * indented select list.
100      */

101     public static String JavaDoc getDataCategoryMap(GenericDelegator delegator, int depth, Map JavaDoc categoryNode, List JavaDoc categoryTypeIds, boolean getAll) throws GenericEntityException {
102         String JavaDoc errorMsg = null;
103         String JavaDoc parentCategoryId = (String JavaDoc) categoryNode.get("id");
104         String JavaDoc currentDataCategoryId = null;
105         int sz = categoryTypeIds.size();
106
107         // The categoryTypeIds has the most senior types at the end, so it is necessary to
108
// work backwards. As "depth" is incremented, that is the effect.
109
// The convention for the topmost type is "ROOT".
110
if (depth >= 0 && (sz - depth) > 0) {
111             currentDataCategoryId = (String JavaDoc) categoryTypeIds.get(sz - depth - 1);
112         }
113
114         // Find all the categoryTypes that are children of the categoryNode.
115
String JavaDoc matchValue = null;
116         if (parentCategoryId != null) {
117             matchValue = parentCategoryId;
118         } else {
119             matchValue = null;
120         }
121         List JavaDoc categoryValues = delegator.findByAndCache("DataCategory", UtilMisc.toMap("parentCategoryId", matchValue));
122         categoryNode.put("count", new Integer JavaDoc(categoryValues.size()));
123         List JavaDoc subCategoryIds = new ArrayList JavaDoc();
124         for (int i = 0; i < categoryValues.size(); i++) {
125             GenericValue category = (GenericValue) categoryValues.get(i);
126             String JavaDoc id = (String JavaDoc) category.get("dataCategoryId");
127             String JavaDoc categoryName = (String JavaDoc) category.get("categoryName");
128             Map JavaDoc newNode = new HashMap JavaDoc();
129             newNode.put("id", id);
130             newNode.put("name", categoryName);
131             errorMsg = getDataCategoryMap(delegator, depth + 1, newNode, categoryTypeIds, getAll);
132             if (errorMsg != null)
133                 break;
134             subCategoryIds.add(newNode);
135         }
136
137         // The first two parentCategoryId test just make sure that the first level of children
138
// is gotten. This is a hack to make them available for display, but a more correct
139
// approach should be formulated.
140
// The "getAll" switch makes sure all descendants make it into the tree, if true.
141
// The other test is to only get all the children if the "leaf" node where all the
142
// children of the leaf are wanted for expansion.
143
if (parentCategoryId == null
144             || parentCategoryId.equals("ROOT")
145             || (currentDataCategoryId != null && currentDataCategoryId.equals(parentCategoryId))
146             || getAll) {
147             categoryNode.put("kids", subCategoryIds);
148         }
149         return errorMsg;
150     }
151
152     /**
153      * Finds the parents of DataCategory entity and puts them in a list, the start entity at the top.
154      */

155     public static void getDataCategoryAncestry(GenericDelegator delegator, String JavaDoc dataCategoryId, List JavaDoc categoryTypeIds) throws GenericEntityException {
156         categoryTypeIds.add(dataCategoryId);
157         GenericValue dataCategoryValue = delegator.findByPrimaryKey("DataCategory", UtilMisc.toMap("dataCategoryId", dataCategoryId));
158         if (dataCategoryValue == null)
159             return;
160         String JavaDoc parentCategoryId = (String JavaDoc) dataCategoryValue.get("parentCategoryId");
161         if (parentCategoryId != null) {
162             getDataCategoryAncestry(delegator, parentCategoryId, categoryTypeIds);
163         }
164         return;
165     }
166
167     /**
168      * 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
169      * use in a drop-down pick list.
170      */

171     public static void buildList(HashMap JavaDoc nd, List JavaDoc lst, int depth) {
172         String JavaDoc id = (String JavaDoc) nd.get("id");
173         String JavaDoc nm = (String JavaDoc) nd.get("name");
174         String JavaDoc spc = "";
175         for (int i = 0; i < depth; i++)
176             spc += "&nbsp;&nbsp;";
177         HashMap JavaDoc map = new HashMap JavaDoc();
178         map.put("dataCategoryId", id);
179         map.put("categoryName", spc + nm);
180         if (id != null && !id.equals("ROOT") && !id.equals("")) {
181             lst.add(map);
182         }
183         List JavaDoc kids = (List JavaDoc) nd.get("kids");
184         int sz = kids.size();
185         for (int i = 0; i < sz; i++) {
186             HashMap JavaDoc kidNode = (HashMap JavaDoc) kids.get(i);
187             buildList(kidNode, lst, depth + 1);
188         }
189     }
190
191     /**
192      * 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
193      * to be in a field id'd by uploadField.
194      */

195     // TODO: This method is not used and should be removed. amb
196
public static String JavaDoc uploadAndStoreImage(HttpServletRequest JavaDoc request, String JavaDoc idField, String JavaDoc uploadField) {
197         //GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
198

199         //String idFieldValue = null;
200
DiskFileUpload fu = new DiskFileUpload();
201         List JavaDoc lst = null;
202         Locale JavaDoc locale = UtilHttp.getLocale(request);
203
204         try {
205             lst = fu.parseRequest(request);
206         } catch (FileUploadException e) {
207             request.setAttribute("_ERROR_MESSAGE_", e.toString());
208             return "error";
209         }
210
211         if (lst.size() == 0) {
212             String JavaDoc errMsg = UtilProperties.getMessage(DataResourceWorker.err_resource, "dataResourceWorker.no_files_uploaded", locale);
213             request.setAttribute("_ERROR_MESSAGE_", errMsg);
214             Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
215             return "error";
216         }
217
218         // This code finds the idField and the upload FileItems
219
FileItem fi = null;
220         FileItem imageFi = null;
221         String JavaDoc imageFileName = null;
222         Map JavaDoc passedParams = new HashMap JavaDoc();
223         HttpSession JavaDoc session = request.getSession();
224         GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
225         passedParams.put("userLogin", userLogin);
226         byte[] imageBytes = null;
227         for (int i = 0; i < lst.size(); i++) {
228             fi = (FileItem) lst.get(i);
229             //String fn = fi.getName();
230
String JavaDoc fieldName = fi.getFieldName();
231             if (fi.isFormField()) {
232                 String JavaDoc fieldStr = fi.getString();
233                 passedParams.put(fieldName, fieldStr);
234             } else if (fieldName.startsWith("imageData")) {
235                 imageFi = fi;
236                 imageBytes = imageFi.get();
237                 passedParams.put(fieldName, imageBytes);
238                 imageFileName = imageFi.getName();
239                 passedParams.put("drObjectInfo", imageFileName);
240                 if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
241             }
242         }
243
244         if (imageBytes != null && imageBytes.length > 0) {
245             String JavaDoc mimeType = getMimeTypeFromImageFileName(imageFileName);
246             if (UtilValidate.isNotEmpty(mimeType)) {
247                 passedParams.put("drMimeTypeId", mimeType);
248                 try {
249                     String JavaDoc returnMsg = UploadContentAndImage.processContentUpload(passedParams, "", request);
250                     if (returnMsg.equals("error")) {
251                         return "error";
252                     }
253                 } catch(GenericServiceException e) {
254                     request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
255                     return "error";
256                 }
257             } else {
258                 request.setAttribute("_ERROR_MESSAGE_", "mimeType is empty.");
259                 return "error";
260             }
261         }
262         return "success";
263     }
264
265     public static String JavaDoc getMimeTypeFromImageFileName(String JavaDoc imageFileName) {
266         String JavaDoc mimeType = null;
267         if (UtilValidate.isEmpty(imageFileName))
268            return mimeType;
269
270         int pos = imageFileName.lastIndexOf(".");
271         if (pos < 0)
272            return mimeType;
273
274         String JavaDoc suffix = imageFileName.substring(pos + 1);
275         String JavaDoc suffixLC = suffix.toLowerCase();
276         if (suffixLC.equals("jpg"))
277             mimeType = "image/jpeg";
278         else
279             mimeType = "image/" + suffixLC;
280
281         return mimeType;
282     }
283
284     /**
285      * callDataResourcePermissionCheck Formats data for a call to the checkContentPermission service.
286      */

287     public static String JavaDoc callDataResourcePermissionCheck(GenericDelegator delegator, LocalDispatcher dispatcher, Map JavaDoc context) {
288         Map JavaDoc permResults = callDataResourcePermissionCheckResult(delegator, dispatcher, context);
289         String JavaDoc permissionStatus = (String JavaDoc) permResults.get("permissionStatus");
290         return permissionStatus;
291     }
292
293     /**
294      * callDataResourcePermissionCheck Formats data for a call to the checkContentPermission service.
295      */

296     public static Map JavaDoc callDataResourcePermissionCheckResult(GenericDelegator delegator, LocalDispatcher dispatcher, Map JavaDoc context) {
297
298         Map JavaDoc permResults = new HashMap JavaDoc();
299         String JavaDoc skipPermissionCheck = (String JavaDoc) context.get("skipPermissionCheck");
300             if (Debug.infoOn()) Debug.logInfo("in callDataResourcePermissionCheckResult, skipPermissionCheck:" + skipPermissionCheck,"");
301
302         if (skipPermissionCheck == null
303             || skipPermissionCheck.length() == 0
304             || (!skipPermissionCheck.equalsIgnoreCase("true") && !skipPermissionCheck.equalsIgnoreCase("granted"))) {
305             GenericValue userLogin = (GenericValue) context.get("userLogin");
306             Map JavaDoc serviceInMap = new HashMap JavaDoc();
307             serviceInMap.put("userLogin", userLogin);
308             serviceInMap.put("targetOperationList", context.get("targetOperationList"));
309             serviceInMap.put("contentPurposeList", context.get("contentPurposeList"));
310             serviceInMap.put("entityOperation", context.get("entityOperation"));
311
312             // It is possible that permission to work with DataResources will be controlled
313
// by an external Content entity.
314
String JavaDoc ownerContentId = (String JavaDoc) context.get("ownerContentId");
315             if (ownerContentId != null && ownerContentId.length() > 0) {
316                 try {
317                     GenericValue content = delegator.findByPrimaryKeyCache("Content", UtilMisc.toMap("contentId", ownerContentId));
318                     if (content != null)
319                         serviceInMap.put("currentContent", content);
320                 } catch (GenericEntityException e) {
321                     Debug.logError(e, "e.getMessage()", "ContentServices");
322                 }
323             }
324             try {
325                 permResults = dispatcher.runSync("checkContentPermission", serviceInMap);
326             } catch (GenericServiceException e) {
327                 Debug.logError(e, "Problem checking permissions", "ContentServices");
328             }
329         } else {
330             permResults.put("permissionStatus", "granted");
331         }
332         return permResults;
333     }
334
335     /**
336      * Gets image data from ImageDataResource and returns it as a byte array.
337      */

338     public static byte[] acquireImage(GenericDelegator delegator, String JavaDoc dataResourceId) throws GenericEntityException {
339
340         byte[] b = null;
341         GenericValue dataResource = delegator.findByPrimaryKeyCache("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
342         if (dataResource == null)
343             return b;
344
345         b = acquireImage(delegator, dataResource);
346         return b;
347     }
348
349     public static byte[] acquireImage(GenericDelegator delegator, GenericValue dataResource) throws GenericEntityException {
350         byte[] b = null;
351         String JavaDoc dataResourceTypeId = dataResource.getString("dataResourceTypeId");
352         String JavaDoc dataResourceId = dataResource.getString("dataResourceId");
353         GenericValue imageDataResource = delegator.findByPrimaryKey("ImageDataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
354         if (imageDataResource != null) {
355             //b = (byte[]) imageDataResource.get("imageData");
356
b = imageDataResource.getBytes("imageData");
357         }
358         return b;
359     }
360
361     /**
362      * Returns the image type.
363      */

364     public static String JavaDoc getImageType(GenericDelegator delegator, String JavaDoc dataResourceId) throws GenericEntityException {
365         GenericValue dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
366         String JavaDoc imageType = getImageType(delegator, dataResource);
367         return imageType;
368     }
369
370     public static String JavaDoc getMimeType(GenericValue dataResource) {
371         String JavaDoc mimeTypeId = null;
372         if (dataResource != null) {
373             mimeTypeId = (String JavaDoc) dataResource.get("mimeTypeId");
374             if (UtilValidate.isEmpty(mimeTypeId)) {
375                 String JavaDoc fileName = (String JavaDoc) dataResource.get("objectInfo");
376                 if (fileName != null && fileName.indexOf('.') > -1) {
377                     String JavaDoc fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
378                     if (UtilValidate.isNotEmpty(fileExtension)) {
379                         GenericValue ext = null;
380                         try {
381                             ext = dataResource.getDelegator().findByPrimaryKey("FileExtension",
382                                     UtilMisc.toMap("fileExtensionId", fileExtension));
383                         } catch (GenericEntityException e) {
384                             Debug.logError(e, module);
385                         }
386                         if (ext != null) {
387                             mimeTypeId = ext.getString("mimeTypeId");
388                         }
389                     }
390                 }
391
392                 // check one last time
393
if (UtilValidate.isEmpty(mimeTypeId)) {
394                     // use a default mime type
395
mimeTypeId = "application/octet-stream";
396                 }
397             }
398         }
399         return mimeTypeId;
400     }
401
402     /** @deprecated */
403     public static String JavaDoc getImageType(GenericDelegator delegator, GenericValue dataResource) {
404         String JavaDoc imageType = null;
405         if (dataResource != null) {
406             imageType = (String JavaDoc) dataResource.get("mimeTypeId");
407             if (UtilValidate.isEmpty(imageType)) {
408                 String JavaDoc imageFileNameExt = null;
409                 String JavaDoc imageFileName = (String JavaDoc)dataResource.get("objectInfo");
410                 if (UtilValidate.isNotEmpty(imageFileName)) {
411                     int pos = imageFileName.lastIndexOf(".");
412                     if (pos >= 0)
413                         imageFileNameExt = imageFileName.substring(pos + 1);
414                 }
415                 imageType = "image/" + imageFileNameExt;
416             }
417         }
418         return imageType;
419     }
420
421     public static String JavaDoc renderDataResourceAsText(GenericDelegator delegator, String JavaDoc dataResourceId, Map JavaDoc templateContext, GenericValue view, Locale JavaDoc locale, String JavaDoc mimeTypeId) throws GeneralException, IOException JavaDoc {
422         Writer JavaDoc outWriter = new StringWriter JavaDoc();
423         renderDataResourceAsText(delegator, dataResourceId, outWriter, templateContext, view, locale, mimeTypeId);
424         return outWriter.toString();
425     }
426
427     public static void renderDataResourceAsText(GenericDelegator delegator, String JavaDoc dataResourceId, Writer JavaDoc out, Map JavaDoc templateContext, GenericValue view, Locale JavaDoc locale, String JavaDoc mimeTypeId) throws GeneralException, IOException JavaDoc {
428         if (templateContext == null) {
429             templateContext = new HashMap JavaDoc();
430         }
431
432
433 // Map context = (Map) templateContext.get("context");
434
// if (context == null) {
435
// context = new HashMap();
436
// }
437

438         if (UtilValidate.isEmpty(mimeTypeId)) {
439             mimeTypeId = "text/html";
440         }
441
442         // if the target mimeTypeId is not a text type, throw an exception
443
if (!mimeTypeId.startsWith("text/")) {
444             throw new GeneralException("The desired mime-type is not a text type, cannot render as text: " + mimeTypeId);
445         }
446
447         GenericValue dataResource = null;
448         if (view != null) {
449             String JavaDoc entityName = view.getEntityName();
450             dataResource = delegator.makeValue("DataResource", null);
451             if ("DataResource".equals(entityName)) {
452                 dataResource.setAllFields(view, true, null, null);
453             } else {
454                 dataResource.setAllFields(view, true, "dr", null);
455             }
456             dataResourceId = dataResource.getString("dataResourceId");
457             if (UtilValidate.isEmpty(dataResourceId)) {
458                 throw new GeneralException("The dataResourceId [" + dataResourceId + "] is empty.");
459             }
460         }
461
462         if (dataResource == null || dataResource.isEmpty()) {
463             if (dataResourceId == null) {
464                 throw new GeneralException("DataResourceId is null");
465             }
466             dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
467         }
468         if (dataResource == null || dataResource.isEmpty()) {
469             throw new GeneralException("DataResource not found with id=" + dataResourceId);
470         }
471
472         String JavaDoc drMimeTypeId = dataResource.getString("mimeTypeId");
473         if (UtilValidate.isEmpty(drMimeTypeId)) {
474             drMimeTypeId = "text/plain";
475         }
476
477         String JavaDoc dataTemplateTypeId = dataResource.getString("dataTemplateTypeId");
478
479         // 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
480
if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) {
481             writeDataResourceText(dataResource, mimeTypeId, locale, templateContext, delegator, out);
482         } else {
483             String JavaDoc subContentId = (String JavaDoc)templateContext.get("subContentId");
484             //String subContentId = (String)context.get("subContentId");
485
// TODO: the reason why I did this (and I can't remember) may not be valid or it can be done better
486
if (UtilValidate.isNotEmpty(subContentId)) {
487                 //context.put("contentId", subContentId);
488
//context.put("subContentId", null);
489
templateContext.put("contentId", subContentId);
490                 templateContext.put("subContentId", null);
491             }
492
493
494             // get the full text of the DataResource
495
String JavaDoc templateText = getDataResourceText(dataResource, mimeTypeId, locale, templateContext, delegator);
496
497             //String subContentId3 = (String)context.get("subContentId");
498

499 // context.put("mimeTypeId", null);
500
templateContext.put("mimeTypeId", null);
501 // templateContext.put("context", context);
502

503             if ("FTL".equals(dataTemplateTypeId)) {
504                 try {
505                     FreeMarkerWorker.renderTemplate("DataResource:" + dataResourceId, templateText, templateContext, out);
506                 } catch (TemplateException e) {
507                     throw new GeneralException("Error rendering FTL template", e);
508                 }
509             } else {
510                 throw new GeneralException("The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
511             }
512         }
513     }
514
515     public static String JavaDoc renderDataResourceAsTextCache(GenericDelegator delegator, String JavaDoc dataResourceId, Map JavaDoc templateContext, GenericValue view, Locale JavaDoc locale, String JavaDoc mimeTypeId) throws GeneralException, IOException JavaDoc {
516         Writer JavaDoc outWriter = new StringWriter JavaDoc();
517         renderDataResourceAsTextCache(delegator, dataResourceId, outWriter, templateContext, view, locale, mimeTypeId);
518         return outWriter.toString();
519     }
520
521
522     public static void renderDataResourceAsTextCache(GenericDelegator delegator, String JavaDoc dataResourceId, Writer JavaDoc out, Map JavaDoc templateRoot, GenericValue view, Locale JavaDoc locale, String JavaDoc mimeTypeId) throws GeneralException, IOException JavaDoc {
523
524         if (templateRoot == null) {
525             templateRoot = new HashMap JavaDoc();
526         }
527
528         //Map context = (Map) templateRoot.get("context");
529
//if (context == null) {
530
//context = new HashMap();
531
//}
532

533         String JavaDoc disableCache = UtilProperties.getPropertyValue("content", "disable.ftl.template.cache");
534         if (disableCache == null || !disableCache.equalsIgnoreCase("true")) {
535             Template cachedTemplate = FreeMarkerWorker.getTemplateCached(dataResourceId);
536             if (cachedTemplate != null) {
537                 try {
538                     String JavaDoc subContentId = (String JavaDoc)templateRoot.get("subContentId");
539                     if (UtilValidate.isNotEmpty(subContentId)) {
540                         templateRoot.put("contentId", subContentId);
541                         templateRoot.put("subContentId", null);
542                         templateRoot.put("globalNodeTrail", null); // Force getCurrentContent to query for subContent
543
}
544                     FreeMarkerWorker.renderTemplateCached(cachedTemplate, templateRoot, out);
545                 } catch (TemplateException e) {
546                     Debug.logError("Error rendering FTL template. " + e.getMessage(), module);
547                     throw new GeneralException("Error rendering FTL template", e);
548                 }
549                 return;
550             }
551         }
552
553         if (UtilValidate.isEmpty(mimeTypeId)) {
554             mimeTypeId = "text/html";
555         }
556
557         // if the target mimeTypeId is not a text type, throw an exception
558
if (!mimeTypeId.startsWith("text/")) {
559             throw new GeneralException("The desired mime-type is not a text type, cannot render as text: " + mimeTypeId);
560         }
561
562         GenericValue dataResource = null;
563         if (view != null) {
564             String JavaDoc entityName = view.getEntityName();
565             dataResource = delegator.makeValue("DataResource", null);
566             if ("DataResource".equals(entityName)) {
567                 dataResource.setAllFields(view, true, null, null);
568             } else {
569                 dataResource.setAllFields(view, true, "dr", null);
570             }
571             String JavaDoc thisDataResourceId = null;
572             try {
573                 thisDataResourceId = (String JavaDoc) view.get("drDataResourceId");
574             } catch (Exception JavaDoc e) {
575                 thisDataResourceId = (String JavaDoc) view.get("dataResourceId");
576             }
577             if (UtilValidate.isEmpty(thisDataResourceId)) {
578                 if (UtilValidate.isNotEmpty(dataResourceId))
579                     view = null; // causes lookup of DataResource
580
else
581                     throw new GeneralException("The dataResourceId [" + dataResourceId + "] is empty.");
582             }
583         }
584
585         if (dataResource == null || dataResource.isEmpty()) {
586             if (dataResourceId == null) {
587                 throw new GeneralException("DataResourceId is null");
588             }
589             dataResource = delegator.findByPrimaryKeyCache("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
590         }
591         if (dataResource == null || dataResource.isEmpty()) {
592             throw new GeneralException("DataResource not found with id=" + dataResourceId);
593         }
594
595         String JavaDoc drMimeTypeId = dataResource.getString("mimeTypeId");
596         if (UtilValidate.isEmpty(drMimeTypeId)) {
597             drMimeTypeId = "text/plain";
598         }
599
600         String JavaDoc dataTemplateTypeId = dataResource.getString("dataTemplateTypeId");
601         //if (Debug.infoOn()) Debug.logInfo("in renderDataResourceAsText, dataTemplateTypeId :" + dataTemplateTypeId ,"");
602

603         // 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
604
if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) {
605             writeDataResourceTextCache(dataResource, mimeTypeId, locale, templateRoot, delegator, out);
606         } else {
607             String JavaDoc subContentId = (String JavaDoc)templateRoot.get("subContentId");
608             if (UtilValidate.isNotEmpty(subContentId)) {
609                 templateRoot.put("contentId", subContentId);
610                 templateRoot.put("subContentId", null);
611             }
612
613             templateRoot.put("mimeTypeId", null);
614
615             if ("FTL".equals(dataTemplateTypeId)) {
616                 try {
617                     // This is something of a hack. FTL templates should need "contentId" value and
618
// not subContentId so that it will find subContent.
619
templateRoot.put("contentId", subContentId);
620                     templateRoot.put("subContentId", null);
621                     templateRoot.put("globalNodeTrail", null); // Force getCurrentContent to query for subContent
622
//if (Debug.infoOn()) Debug.logInfo("in renderDataResourceAsTextCache, templateRoot :" + templateRoot ,"");
623
//StringWriter sw = new StringWriter();
624
// get the full text of the DataResource
625
String JavaDoc templateText = getDataResourceTextCache(dataResource, mimeTypeId, locale, templateRoot, delegator);
626                     FreeMarkerWorker.renderTemplate("DataResource:" + dataResourceId, templateText, templateRoot, out);
627                     //if (Debug.infoOn()) Debug.logInfo("in renderDataResourceAsText, sw:" + sw.toString(),"");
628
//out.write(sw.toString());
629
//out.flush();
630
} catch (TemplateException e) {
631                     throw new GeneralException("Error rendering FTL template", e);
632                 }
633             } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) {
634                 try {
635                     Map JavaDoc context = MapStack.create(templateRoot);
636                     ScreenStringRenderer screenStringRenderer = null;
637                     ScreenRenderer screenRenderer = (ScreenRenderer)context.get("screens");
638                      if (screenRenderer != null) {
639                          screenStringRenderer = screenRenderer.getScreenStringRenderer();
640                      } else {
641                          if (screenStringRenderer == null) {
642                              screenStringRenderer = new HtmlScreenRenderer();
643                          }
644                      }
645
646                     String JavaDoc combinedName = (String JavaDoc)dataResource.get("objectInfo");
647                     ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(combinedName);
648                     modelScreen.renderScreenString(out, context, screenStringRenderer);
649
650                 } catch (SAXException JavaDoc e) {
651                     throw new GeneralException("Error rendering Screen template", e);
652                 } catch(ParserConfigurationException JavaDoc e3) {
653                     throw new GeneralException("Error rendering Screen template", e3);
654                 }
655             } else {
656                 throw new GeneralException("The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
657             }
658         }
659     }
660
661     public static String JavaDoc getDataResourceText(GenericValue dataResource, String JavaDoc mimeTypeId, Locale JavaDoc locale, Map JavaDoc context, GenericDelegator delegator) throws IOException JavaDoc, GeneralException {
662         Writer JavaDoc outWriter = new StringWriter JavaDoc();
663         writeDataResourceText(dataResource, mimeTypeId, locale, context, delegator, outWriter);
664         return outWriter.toString();
665     }
666
667     public static void writeDataResourceText(GenericValue dataResource, String JavaDoc mimeTypeId, Locale JavaDoc locale, Map JavaDoc templateContext, GenericDelegator delegator, Writer JavaDoc outWriter) throws IOException JavaDoc, GeneralException {
668
669         Map JavaDoc context = (Map JavaDoc)templateContext.get("context");
670         String JavaDoc webSiteId = (String JavaDoc) templateContext.get("webSiteId");
671         if (UtilValidate.isEmpty(webSiteId)) {
672             if (context != null)
673                 webSiteId = (String JavaDoc) context.get("webSiteId");
674         }
675         String JavaDoc https = (String JavaDoc) templateContext.get("https");
676         if (UtilValidate.isEmpty(https)) {
677             if (context != null)
678                 https = (String JavaDoc) context.get("https");
679         }
680
681         String JavaDoc dataResourceId = dataResource.getString("dataResourceId");
682         String JavaDoc dataResourceTypeId = dataResource.getString("dataResourceTypeId");
683         if (UtilValidate.isEmpty(dataResourceTypeId)) {
684             dataResourceTypeId = "SHORT_TEXT";
685         }
686
687         if (dataResourceTypeId.equals("SHORT_TEXT")) {
688             String JavaDoc text = dataResource.getString("objectInfo");
689             outWriter.write(text);
690         } else if (dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
691             GenericValue electronicText = delegator.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId));
692             String JavaDoc text = electronicText.getString("textData");
693             outWriter.write(text);
694         } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
695             // TODO: Is this where the image (or any binary) object URL is created? looks like it is just returning
696
//the ID, maybe is okay, but maybe should create the whole image tag so that text and images can be
697
//interchanged without changing the wrapping template, and so the wrapping template doesn't have to know what the root is, etc
698
/*
699             // decide how to render based on the mime-types
700             // TODO: put this in a separate method to be re-used for file objects as well...
701             if ("text/html".equals(mimeTypeId)) {
702             } else if ("text/plain".equals(mimeTypeId)) {
703             } else {
704                 throw new GeneralException("The renderDataResourceAsText operation does not yet support the desired mime-type: " + mimeTypeId);
705             }
706             */

707
708             String JavaDoc text = (String JavaDoc) dataResource.get("dataResourceId");
709             outWriter.write(text);
710         } else if (dataResourceTypeId.equals("LINK")) {
711             String JavaDoc text = dataResource.getString("objectInfo");
712             outWriter.write(text);
713         } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
714             String JavaDoc text = null;
715             URL JavaDoc url = new URL JavaDoc(dataResource.getString("objectInfo"));
716             if (url.getHost() != null) { // is absolute
717
InputStream JavaDoc in = url.openStream();
718                 int c;
719                 StringWriter JavaDoc sw = new StringWriter JavaDoc();
720                 while ((c = in.read()) != -1) {
721                     sw.write(c);
722                 }
723                 sw.close();
724                 text = sw.toString();
725             } else {
726                 String JavaDoc prefix = buildRequestPrefix(delegator, locale, webSiteId, https);
727                 String JavaDoc sep = "";
728                 //String s = "";
729
if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
730                     sep = "/";
731                 }
732                 String JavaDoc s2 = prefix + sep + url.toString();
733                 URL JavaDoc url2 = new URL JavaDoc(s2);
734                 text = (String JavaDoc) url2.getContent();
735             }
736             outWriter.write(text);
737         } else if (dataResourceTypeId.indexOf("_FILE") >= 0) {
738             String JavaDoc rootDir = (String JavaDoc) templateContext.get("rootDir");
739             if (UtilValidate.isEmpty(rootDir)) {
740                 if (context != null)
741                     rootDir = (String JavaDoc) context.get("rootDir");
742             }
743             if (mimeTypeId != null && mimeTypeId.startsWith("image")) {
744                 writeDataResourceText(dataResource, mimeTypeId, locale, context, delegator, outWriter);
745             } else {
746                 renderFile(dataResourceTypeId, dataResource.getString("objectInfo"), rootDir, outWriter);
747             }
748         } else {
749             throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText");
750         }
751     }
752
753     public static String JavaDoc getDataResourceTextCache(GenericValue dataResource, String JavaDoc mimeTypeId, Locale JavaDoc locale, Map JavaDoc context, GenericDelegator delegator) throws IOException JavaDoc, GeneralException {
754         Writer JavaDoc outWriter = new StringWriter JavaDoc();
755         writeDataResourceText(dataResource, mimeTypeId, locale, context, delegator, outWriter);
756         return outWriter.toString();
757     }
758
759     public static void writeDataResourceTextCache(GenericValue dataResource, String JavaDoc mimeTypeId, Locale JavaDoc locale, Map JavaDoc context, GenericDelegator delegator, Writer JavaDoc outWriter) throws IOException JavaDoc, GeneralException {
760
761         if (context == null)
762             context = new HashMap JavaDoc();
763
764         String JavaDoc text = null;
765         String JavaDoc webSiteId = (String JavaDoc) context.get("webSiteId");
766         String JavaDoc https = (String JavaDoc) context.get("https");
767
768         String JavaDoc dataResourceId = dataResource.getString("dataResourceId");
769         String JavaDoc dataResourceTypeId = dataResource.getString("dataResourceTypeId");
770         String JavaDoc dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
771         if (UtilValidate.isEmpty(dataResourceTypeId)) {
772             dataResourceTypeId = "SHORT_TEXT";
773         }
774
775         if (dataResourceTypeId.equals("SHORT_TEXT")) {
776             text = dataResource.getString("objectInfo");
777             writeText(text, dataResourceMimeTypeId, mimeTypeId, outWriter);
778         } else if (dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
779             GenericValue electronicText = delegator.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId));
780             if (electronicText != null) {
781                 text = electronicText.getString("textData");
782                 writeText(text, dataResourceMimeTypeId, mimeTypeId, outWriter);
783             }
784         } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
785             // TODO: Is this where the image (or any binary) object URL is created? looks like it is just returning
786
//the ID, maybe is okay, but maybe should create the whole image tag so that text and images can be
787
//interchanged without changing the wrapping template, and so the wrapping template doesn't have to know what the root is, etc
788
/*
789             // decide how to render based on the mime-types
790             // TODO: put this in a separate method to be re-used for file objects as well...
791             if ("text/html".equals(mimeTypeId)) {
792             } else if ("text/plain".equals(mimeTypeId)) {
793             } else {
794                 throw new GeneralException("The renderDataResourceAsText operation does not yet support the desired mime-type: " + mimeTypeId);
795             }
796             */

797
798             text = (String JavaDoc) dataResource.get("dataResourceId");
799             writeText(text, dataResourceMimeTypeId, mimeTypeId, outWriter);
800         } else if (dataResourceTypeId.equals("LINK")) {
801             text = dataResource.getString("objectInfo");
802             writeText(text, dataResourceMimeTypeId, mimeTypeId, outWriter);
803         } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
804             URL JavaDoc url = new URL JavaDoc(dataResource.getString("objectInfo"));
805             if (url.getHost() != null) { // is absolute
806
InputStream JavaDoc in = url.openStream();
807                 int c;
808                 StringWriter JavaDoc sw = new StringWriter JavaDoc();
809                 while ((c = in.read()) != -1) {
810                     sw.write(c);
811                 }
812                 sw.close();
813                 text = sw.toString();
814             } else {
815                 String JavaDoc prefix = buildRequestPrefix(delegator, locale, webSiteId, https);
816                 String JavaDoc sep = "";
817                 //String s = "";
818
if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
819                     sep = "/";
820                 }
821                 String JavaDoc s2 = prefix + sep + url.toString();
822                 URL JavaDoc url2 = new URL JavaDoc(s2);
823                 text = (String JavaDoc) url2.getContent();
824             }
825             writeText(text, dataResourceMimeTypeId, mimeTypeId, outWriter);
826         } else if (dataResourceTypeId.indexOf("_FILE_BIN") >= 0) {
827             String JavaDoc rootDir = (String JavaDoc) context.get("rootDir");
828             //renderFileBin(dataResourceTypeId, dataResource.getString("objectInfo"), rootDir, outWriter);
829
String JavaDoc objectInfo = dataResource.getString("objectInfo");
830             dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
831             writeText( dataResourceId, dataResourceMimeTypeId, "text/html", outWriter);
832         } else if (dataResourceTypeId.indexOf("_FILE") >= 0) {
833             String JavaDoc rootDir = (String JavaDoc) context.get("rootDir");
834             dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
835             if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text"))
836                 renderFile(dataResourceTypeId, dataResource.getString("objectInfo"), rootDir, outWriter);
837             else
838                 writeText( dataResourceId, dataResourceMimeTypeId, "text/html", outWriter);
839         } else {
840             throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText");
841         }
842     }
843
844     public static void writeText( String JavaDoc textData, String JavaDoc dataResourceMimeType, String JavaDoc targetMimeType, Writer JavaDoc out) throws IOException JavaDoc {
845         if (UtilValidate.isEmpty(targetMimeType))
846             targetMimeType = "text/html";
847         if (UtilValidate.isEmpty(dataResourceMimeType))
848             dataResourceMimeType = "text/html";
849
850         if (dataResourceMimeType.startsWith("text") ) {
851                 out.write(textData);
852         } else {
853             if( targetMimeType.equals("text/html")) {
854                 /*
855                 if (request == null || response == null) {
856                     throw new GeneralException("Request [" + request + "] or response [" + response + "] is null.");
857                 }
858                 ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
859                 RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
860                 boolean fullPath = false;
861                 boolean secure = false;
862                 boolean encode = false;
863                 String url = rh.makeLink(request, response, buf.toString(), fullPath, secure, encode);
864                 */

865                 String JavaDoc img = "<img SRC=\"/content/control/img?imgId=" + textData + "\"/>";
866                 out.write(img);
867             } else if( targetMimeType.equals("text/plain")) {
868                 out.write(textData);
869             }
870         }
871     }
872
873     public static void renderFile(String JavaDoc dataResourceTypeId, String JavaDoc objectInfo, String JavaDoc rootDir, Writer JavaDoc out) throws GeneralException, IOException JavaDoc {
874         // 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
875

876         if (dataResourceTypeId.equals("LOCAL_FILE")) {
877             File JavaDoc file = new File JavaDoc(objectInfo);
878             if (!file.isAbsolute()) {
879                 throw new GeneralException("File (" + objectInfo + ") is not absolute");
880             }
881             int c;
882             FileReader JavaDoc in = new FileReader JavaDoc(file);
883             while ((c = in.read()) != -1) {
884                 out.write(c);
885             }
886         } else if (dataResourceTypeId.equals("OFBIZ_FILE")) {
887             String JavaDoc prefix = System.getProperty("ofbiz.home");
888             String JavaDoc sep = "";
889             if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
890                 sep = "/";
891             }
892             File JavaDoc file = new File JavaDoc(prefix + sep + objectInfo);
893             int c;
894             FileReader JavaDoc in = new FileReader JavaDoc(file);
895             while ((c = in.read()) != -1)
896                 out.write(c);
897         } else if (dataResourceTypeId.equals("CONTEXT_FILE")) {
898             String JavaDoc prefix = rootDir;
899             String JavaDoc sep = "";
900             if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
901                 sep = "/";
902             }
903             File JavaDoc file = new File JavaDoc(prefix + sep + objectInfo);
904             int c;
905             FileReader JavaDoc in = null;
906             try {
907                 in = new FileReader JavaDoc(file);
908                 String JavaDoc enc = in.getEncoding();
909                 if (Debug.infoOn()) Debug.logInfo("in serveImage, encoding:" + enc, module);
910
911             } catch (FileNotFoundException JavaDoc e) {
912                 Debug.logError(e, " in renderDataResourceAsHtml(CONTEXT_FILE), in FNFexception:", module);
913                 throw new GeneralException("Could not find context file to render", e);
914             } catch (Exception JavaDoc e) {
915                 Debug.logError(" in renderDataResourceAsHtml(CONTEXT_FILE), got exception:" + e.getMessage(), module);
916             }
917             while ((c = in.read()) != -1) {
918                 out.write(c);
919             }
920             //out.flush();
921
}
922         return;
923     }
924
925
926     public static String JavaDoc buildRequestPrefix(GenericDelegator delegator, Locale JavaDoc locale, String JavaDoc webSiteId, String JavaDoc https) {
927         String JavaDoc prefix = null;
928         Map JavaDoc prefixValues = new HashMap JavaDoc();
929         NotificationServices.setBaseUrl(delegator, webSiteId, prefixValues);
930         if (https != null && https.equalsIgnoreCase("true")) {
931             prefix = (String JavaDoc) prefixValues.get("baseSecureUrl");
932         } else {
933             prefix = (String JavaDoc) prefixValues.get("baseUrl");
934         }
935         if (UtilValidate.isEmpty(prefix)) {
936             if (https != null && https.equalsIgnoreCase("true")) {
937                 prefix = UtilProperties.getMessage("content", "baseSecureUrl", locale);
938             } else {
939                 prefix = UtilProperties.getMessage("content", "baseUrl", locale);
940             }
941         }
942
943         return prefix;
944     }
945
946     public static File JavaDoc getContentFile(String JavaDoc dataResourceTypeId, String JavaDoc objectInfo, String JavaDoc rootDir) throws GeneralException, FileNotFoundException JavaDoc{
947
948         File JavaDoc file = null;
949         if (dataResourceTypeId.equals("LOCAL_FILE") || dataResourceTypeId.equals("LOCAL_FILE_BIN")) {
950             file = new File JavaDoc(objectInfo);
951             if (!file.isAbsolute()) {
952                 throw new GeneralException("File (" + objectInfo + ") is not absolute");
953             }
954             int c;
955         } else if (dataResourceTypeId.equals("OFBIZ_FILE") || dataResourceTypeId.equals("OFBIZ_FILE_BIN")) {
956             String JavaDoc prefix = System.getProperty("ofbiz.home");
957             String JavaDoc sep = "";
958             if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
959                 sep = "/";
960             }
961             file = new File JavaDoc(prefix + sep + objectInfo);
962         } else if (dataResourceTypeId.equals("CONTEXT_FILE") || dataResourceTypeId.equals("CONTEXT_FILE_BIN")) {
963             String JavaDoc prefix = rootDir;
964             String JavaDoc sep = "";
965             if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
966                 sep = "/";
967             }
968             file = new File JavaDoc(prefix + sep + objectInfo);
969         }
970         return file;
971     }
972
973
974     public static String JavaDoc getDataResourceMimeType(GenericDelegator delegator, String JavaDoc dataResourceId, GenericValue view) throws GenericEntityException {
975
976         String JavaDoc mimeType = null;
977         if (view != null)
978             mimeType = view.getString("drMimeTypeId");
979             //if (Debug.infoOn()) Debug.logInfo("getDataResourceMimeType, mimeType(2):" + mimeType, "");
980
if (UtilValidate.isEmpty(mimeType) && UtilValidate.isNotEmpty(dataResourceId)) {
981                 GenericValue dataResource = delegator.findByPrimaryKeyCache("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
982                 //if (Debug.infoOn()) Debug.logInfo("getDataResourceMimeType, dataResource(2):" + dataResource, "");
983
mimeType = dataResource.getString("mimeTypeId");
984
985         }
986         return mimeType;
987     }
988
989     public static String JavaDoc getDataResourceContentUploadPath() {
990         String JavaDoc initialPath = UtilProperties.getPropertyValue("content.properties", "content.upload.path.prefix");
991         double maxFiles = UtilProperties.getPropertyNumber("content.properties", "content.upload.max.files");
992         if (maxFiles < 1) {
993             maxFiles = 250;
994         }
995         String JavaDoc ofbizHome = System.getProperty("ofbiz.home");
996
997         if (!initialPath.startsWith("/")) {
998             initialPath = "/" + initialPath;
999         }
1000
1001        // descending comparator
1002
Comparator JavaDoc desc = new Comparator JavaDoc() {
1003            public int compare(Object JavaDoc o1, Object JavaDoc o2) {
1004                if (((Long JavaDoc) o1).longValue() > ((Long JavaDoc) o2).longValue()) {
1005                    return -1;
1006                } else if (((Long JavaDoc) o1).longValue() < ((Long JavaDoc) o2).longValue()) {
1007                    return 1;
1008                }
1009                return 0;
1010            }
1011        };
1012
1013        // check for the latest subdirectory
1014
String JavaDoc parentDir = ofbizHome + initialPath;
1015        File JavaDoc parent = new File JavaDoc(parentDir);
1016        TreeMap JavaDoc dirMap = new TreeMap JavaDoc(desc);
1017        if (parent.exists()) {
1018            File JavaDoc[] subs = parent.listFiles();
1019            for (int i = 0; i < subs.length; i++) {
1020                if (subs[i].isDirectory()) {
1021                    dirMap.put(new Long JavaDoc(subs[0].lastModified()), subs[i]);
1022                }
1023            }
1024        } else {
1025            // if the parent doesn't exist; create it now
1026
boolean created = parent.mkdir();
1027            if (!created) {
1028                Debug.logWarning("Unable to create top level upload directory [" + parentDir + "].", module);
1029            }
1030        }
1031
1032        // first item in map is the most current directory
1033
File JavaDoc latestDir = null;
1034        if (dirMap != null && dirMap.size() > 0) {
1035            latestDir = (File JavaDoc) dirMap.values().iterator().next();
1036            if (latestDir != null) {
1037                File JavaDoc[] dirList = latestDir.listFiles();
1038                if (dirList.length >= maxFiles) {
1039                    latestDir = makeNewDirectory(parent);
1040                }
1041            }
1042        } else {
1043            latestDir = makeNewDirectory(parent);
1044        }
1045
1046        Debug.log("Directory Name : " + latestDir.getName(), module);
1047        return latestDir.getAbsolutePath().replace('\\','/');
1048    }
1049
1050    private static File JavaDoc makeNewDirectory(File JavaDoc parent) {
1051        File JavaDoc latestDir = null;
1052        boolean newDir = false;
1053        while (!newDir) {
1054            latestDir = new File JavaDoc(parent, "" + System.currentTimeMillis());
1055            if (!latestDir.exists()) {
1056                latestDir.mkdir();
1057                newDir = true;
1058            }
1059        }
1060        return latestDir;
1061    }
1062
1063    public static void streamDataResource(OutputStream JavaDoc os, GenericDelegator delegator, String JavaDoc dataResourceId, String JavaDoc https, String JavaDoc webSiteId, Locale JavaDoc locale, String JavaDoc rootDir) throws IOException JavaDoc, GeneralException {
1064        try {
1065            GenericValue dataResource = delegator.findByPrimaryKeyCache("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
1066            if (dataResource == null) {
1067                throw new GeneralException("Error in streamDataResource: DataResource with ID [" + dataResourceId + "] was not found.");
1068            }
1069            String JavaDoc dataResourceTypeId = dataResource.getString("dataResourceTypeId");
1070            if (UtilValidate.isEmpty(dataResourceTypeId)) {
1071                dataResourceTypeId = "SHORT_TEXT";
1072            }
1073            String JavaDoc mimeTypeId = dataResource.getString("mimeTypeId");
1074            if (UtilValidate.isEmpty(mimeTypeId)) {
1075                mimeTypeId = "text/html";
1076            }
1077    
1078            if (dataResourceTypeId.equals("SHORT_TEXT")) {
1079                String JavaDoc text = dataResource.getString("objectInfo");
1080                os.write(text.getBytes());
1081            } else if (dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
1082                GenericValue electronicText = delegator.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId));
1083                if (electronicText != null) {
1084                    String JavaDoc text = electronicText.getString("textData");
1085                    if (text != null) os.write(text.getBytes());
1086                }
1087            } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) {
1088                byte[] imageBytes = acquireImage(delegator, dataResource);
1089                if (imageBytes != null) os.write(imageBytes);
1090            } else if (dataResourceTypeId.equals("LINK")) {
1091                String JavaDoc text = dataResource.getString("objectInfo");
1092                os.write(text.getBytes());
1093            } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
1094                URL JavaDoc url = new URL JavaDoc(dataResource.getString("objectInfo"));
1095                if (url.getHost() == null) { // is relative
1096
String JavaDoc prefix = buildRequestPrefix(delegator, locale, webSiteId, https);
1097                    String JavaDoc sep = "";
1098                    //String s = "";
1099
if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
1100                        sep = "/";
1101                    }
1102                    String JavaDoc s2 = prefix + sep + url.toString();
1103                    url = new URL JavaDoc(s2);
1104                }
1105                InputStream JavaDoc in = url.openStream();
1106                int c;
1107                while ((c = in.read()) != -1) {
1108                    os.write(c);
1109                }
1110            } else if (dataResourceTypeId.indexOf("_FILE") >= 0) {
1111                String JavaDoc objectInfo = dataResource.getString("objectInfo");
1112                File JavaDoc inputFile = getContentFile(dataResourceTypeId, objectInfo, rootDir);
1113                //long fileSize = inputFile.length();
1114
FileInputStream JavaDoc fis = new FileInputStream JavaDoc(inputFile);
1115                int c;
1116                while ((c = fis.read()) != -1) {
1117                    os.write(c);
1118                }
1119            } else {
1120                throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in streamDataResource");
1121            }
1122        } catch(GenericEntityException e) {
1123            throw new GeneralException("Error in streamDataResource", e);
1124        }
1125    }
1126    
1127    public static ByteWrapper getContentAsByteWrapper(GenericDelegator delegator, String JavaDoc dataResourceId, String JavaDoc https, String JavaDoc webSiteId, Locale JavaDoc locale, String JavaDoc rootDir) throws IOException JavaDoc, GeneralException {
1128        ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
1129        streamDataResource(baos, delegator, dataResourceId, https, webSiteId, locale, rootDir);
1130        ByteWrapper byteWrapper = new ByteWrapper(baos.toByteArray());
1131        return byteWrapper;
1132    }
1133}
1134
Popular Tags