1 24 package org.ofbiz.content.data; 25 26 import java.io.ByteArrayOutputStream ; 27 import java.io.File ; 28 import java.io.FileInputStream ; 29 import java.io.FileNotFoundException ; 30 import java.io.FileReader ; 31 import java.io.IOException ; 32 import java.io.InputStream ; 33 import java.io.OutputStream ; 34 import java.io.StringWriter ; 35 import java.io.Writer ; 36 import java.net.URL ; 37 import java.util.ArrayList ; 38 import java.util.Comparator ; 39 import java.util.HashMap ; 40 import java.util.List ; 41 import java.util.Locale ; 42 import java.util.Map ; 43 import java.util.TreeMap ; 44 45 import javax.servlet.http.HttpServletRequest ; 46 import javax.servlet.http.HttpSession ; 47 import javax.xml.parsers.ParserConfigurationException ; 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 ; 75 76 import freemarker.template.Template; 77 import freemarker.template.TemplateException; 78 79 81 90 public class DataResourceWorker { 91 92 public static final String module = DataResourceWorker.class.getName(); 93 public static final String err_resource = "ContentErrorUiLabel"; 94 95 101 public static String getDataCategoryMap(GenericDelegator delegator, int depth, Map categoryNode, List categoryTypeIds, boolean getAll) throws GenericEntityException { 102 String errorMsg = null; 103 String parentCategoryId = (String ) categoryNode.get("id"); 104 String currentDataCategoryId = null; 105 int sz = categoryTypeIds.size(); 106 107 if (depth >= 0 && (sz - depth) > 0) { 111 currentDataCategoryId = (String ) categoryTypeIds.get(sz - depth - 1); 112 } 113 114 String matchValue = null; 116 if (parentCategoryId != null) { 117 matchValue = parentCategoryId; 118 } else { 119 matchValue = null; 120 } 121 List categoryValues = delegator.findByAndCache("DataCategory", UtilMisc.toMap("parentCategoryId", matchValue)); 122 categoryNode.put("count", new Integer (categoryValues.size())); 123 List subCategoryIds = new ArrayList (); 124 for (int i = 0; i < categoryValues.size(); i++) { 125 GenericValue category = (GenericValue) categoryValues.get(i); 126 String id = (String ) category.get("dataCategoryId"); 127 String categoryName = (String ) category.get("categoryName"); 128 Map newNode = new HashMap (); 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 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 155 public static void getDataCategoryAncestry(GenericDelegator delegator, String dataCategoryId, List 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 parentCategoryId = (String ) dataCategoryValue.get("parentCategoryId"); 161 if (parentCategoryId != null) { 162 getDataCategoryAncestry(delegator, parentCategoryId, categoryTypeIds); 163 } 164 return; 165 } 166 167 171 public static void buildList(HashMap nd, List lst, int depth) { 172 String id = (String ) nd.get("id"); 173 String nm = (String ) nd.get("name"); 174 String spc = ""; 175 for (int i = 0; i < depth; i++) 176 spc += " "; 177 HashMap map = new HashMap (); 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 kids = (List ) nd.get("kids"); 184 int sz = kids.size(); 185 for (int i = 0; i < sz; i++) { 186 HashMap kidNode = (HashMap ) kids.get(i); 187 buildList(kidNode, lst, depth + 1); 188 } 189 } 190 191 195 public static String uploadAndStoreImage(HttpServletRequest request, String idField, String uploadField) { 197 199 DiskFileUpload fu = new DiskFileUpload(); 201 List lst = null; 202 Locale 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 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 FileItem fi = null; 220 FileItem imageFi = null; 221 String imageFileName = null; 222 Map passedParams = new HashMap (); 223 HttpSession 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 fieldName = fi.getFieldName(); 231 if (fi.isFormField()) { 232 String 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 mimeType = getMimeTypeFromImageFileName(imageFileName); 246 if (UtilValidate.isNotEmpty(mimeType)) { 247 passedParams.put("drMimeTypeId", mimeType); 248 try { 249 String 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 getMimeTypeFromImageFileName(String imageFileName) { 266 String 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 suffix = imageFileName.substring(pos + 1); 275 String 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 287 public static String callDataResourcePermissionCheck(GenericDelegator delegator, LocalDispatcher dispatcher, Map context) { 288 Map permResults = callDataResourcePermissionCheckResult(delegator, dispatcher, context); 289 String permissionStatus = (String ) permResults.get("permissionStatus"); 290 return permissionStatus; 291 } 292 293 296 public static Map callDataResourcePermissionCheckResult(GenericDelegator delegator, LocalDispatcher dispatcher, Map context) { 297 298 Map permResults = new HashMap (); 299 String skipPermissionCheck = (String ) 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 serviceInMap = new HashMap (); 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 String ownerContentId = (String ) 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 338 public static byte[] acquireImage(GenericDelegator delegator, String 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 dataResourceTypeId = dataResource.getString("dataResourceTypeId"); 352 String dataResourceId = dataResource.getString("dataResourceId"); 353 GenericValue imageDataResource = delegator.findByPrimaryKey("ImageDataResource", UtilMisc.toMap("dataResourceId", dataResourceId)); 354 if (imageDataResource != null) { 355 b = imageDataResource.getBytes("imageData"); 357 } 358 return b; 359 } 360 361 364 public static String getImageType(GenericDelegator delegator, String dataResourceId) throws GenericEntityException { 365 GenericValue dataResource = delegator.findByPrimaryKey("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId)); 366 String imageType = getImageType(delegator, dataResource); 367 return imageType; 368 } 369 370 public static String getMimeType(GenericValue dataResource) { 371 String mimeTypeId = null; 372 if (dataResource != null) { 373 mimeTypeId = (String ) dataResource.get("mimeTypeId"); 374 if (UtilValidate.isEmpty(mimeTypeId)) { 375 String fileName = (String ) dataResource.get("objectInfo"); 376 if (fileName != null && fileName.indexOf('.') > -1) { 377 String 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 if (UtilValidate.isEmpty(mimeTypeId)) { 394 mimeTypeId = "application/octet-stream"; 396 } 397 } 398 } 399 return mimeTypeId; 400 } 401 402 403 public static String getImageType(GenericDelegator delegator, GenericValue dataResource) { 404 String imageType = null; 405 if (dataResource != null) { 406 imageType = (String ) dataResource.get("mimeTypeId"); 407 if (UtilValidate.isEmpty(imageType)) { 408 String imageFileNameExt = null; 409 String imageFileName = (String )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 renderDataResourceAsText(GenericDelegator delegator, String dataResourceId, Map templateContext, GenericValue view, Locale locale, String mimeTypeId) throws GeneralException, IOException { 422 Writer outWriter = new StringWriter (); 423 renderDataResourceAsText(delegator, dataResourceId, outWriter, templateContext, view, locale, mimeTypeId); 424 return outWriter.toString(); 425 } 426 427 public static void renderDataResourceAsText(GenericDelegator delegator, String dataResourceId, Writer out, Map templateContext, GenericValue view, Locale locale, String mimeTypeId) throws GeneralException, IOException { 428 if (templateContext == null) { 429 templateContext = new HashMap (); 430 } 431 432 433 438 if (UtilValidate.isEmpty(mimeTypeId)) { 439 mimeTypeId = "text/html"; 440 } 441 442 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 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 drMimeTypeId = dataResource.getString("mimeTypeId"); 473 if (UtilValidate.isEmpty(drMimeTypeId)) { 474 drMimeTypeId = "text/plain"; 475 } 476 477 String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId"); 478 479 if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) { 481 writeDataResourceText(dataResource, mimeTypeId, locale, templateContext, delegator, out); 482 } else { 483 String subContentId = (String )templateContext.get("subContentId"); 484 if (UtilValidate.isNotEmpty(subContentId)) { 487 templateContext.put("contentId", subContentId); 490 templateContext.put("subContentId", null); 491 } 492 493 494 String templateText = getDataResourceText(dataResource, mimeTypeId, locale, templateContext, delegator); 496 497 499 templateContext.put("mimeTypeId", null); 501 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 renderDataResourceAsTextCache(GenericDelegator delegator, String dataResourceId, Map templateContext, GenericValue view, Locale locale, String mimeTypeId) throws GeneralException, IOException { 516 Writer outWriter = new StringWriter (); 517 renderDataResourceAsTextCache(delegator, dataResourceId, outWriter, templateContext, view, locale, mimeTypeId); 518 return outWriter.toString(); 519 } 520 521 522 public static void renderDataResourceAsTextCache(GenericDelegator delegator, String dataResourceId, Writer out, Map templateRoot, GenericValue view, Locale locale, String mimeTypeId) throws GeneralException, IOException { 523 524 if (templateRoot == null) { 525 templateRoot = new HashMap (); 526 } 527 528 533 String 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 subContentId = (String )templateRoot.get("subContentId"); 539 if (UtilValidate.isNotEmpty(subContentId)) { 540 templateRoot.put("contentId", subContentId); 541 templateRoot.put("subContentId", null); 542 templateRoot.put("globalNodeTrail", null); } 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 (!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 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 thisDataResourceId = null; 572 try { 573 thisDataResourceId = (String ) view.get("drDataResourceId"); 574 } catch (Exception e) { 575 thisDataResourceId = (String ) view.get("dataResourceId"); 576 } 577 if (UtilValidate.isEmpty(thisDataResourceId)) { 578 if (UtilValidate.isNotEmpty(dataResourceId)) 579 view = null; 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 drMimeTypeId = dataResource.getString("mimeTypeId"); 596 if (UtilValidate.isEmpty(drMimeTypeId)) { 597 drMimeTypeId = "text/plain"; 598 } 599 600 String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId"); 601 603 if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) { 605 writeDataResourceTextCache(dataResource, mimeTypeId, locale, templateRoot, delegator, out); 606 } else { 607 String subContentId = (String )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 templateRoot.put("contentId", subContentId); 620 templateRoot.put("subContentId", null); 621 templateRoot.put("globalNodeTrail", null); String templateText = getDataResourceTextCache(dataResource, mimeTypeId, locale, templateRoot, delegator); 626 FreeMarkerWorker.renderTemplate("DataResource:" + dataResourceId, templateText, templateRoot, out); 627 } catch (TemplateException e) { 631 throw new GeneralException("Error rendering FTL template", e); 632 } 633 } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) { 634 try { 635 Map 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 combinedName = (String )dataResource.get("objectInfo"); 647 ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(combinedName); 648 modelScreen.renderScreenString(out, context, screenStringRenderer); 649 650 } catch (SAXException e) { 651 throw new GeneralException("Error rendering Screen template", e); 652 } catch(ParserConfigurationException 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 getDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map context, GenericDelegator delegator) throws IOException , GeneralException { 662 Writer outWriter = new StringWriter (); 663 writeDataResourceText(dataResource, mimeTypeId, locale, context, delegator, outWriter); 664 return outWriter.toString(); 665 } 666 667 public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map templateContext, GenericDelegator delegator, Writer outWriter) throws IOException , GeneralException { 668 669 Map context = (Map )templateContext.get("context"); 670 String webSiteId = (String ) templateContext.get("webSiteId"); 671 if (UtilValidate.isEmpty(webSiteId)) { 672 if (context != null) 673 webSiteId = (String ) context.get("webSiteId"); 674 } 675 String https = (String ) templateContext.get("https"); 676 if (UtilValidate.isEmpty(https)) { 677 if (context != null) 678 https = (String ) context.get("https"); 679 } 680 681 String dataResourceId = dataResource.getString("dataResourceId"); 682 String dataResourceTypeId = dataResource.getString("dataResourceTypeId"); 683 if (UtilValidate.isEmpty(dataResourceTypeId)) { 684 dataResourceTypeId = "SHORT_TEXT"; 685 } 686 687 if (dataResourceTypeId.equals("SHORT_TEXT")) { 688 String 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 text = electronicText.getString("textData"); 693 outWriter.write(text); 694 } else if (dataResourceTypeId.equals("IMAGE_OBJECT")) { 695 707 708 String text = (String ) dataResource.get("dataResourceId"); 709 outWriter.write(text); 710 } else if (dataResourceTypeId.equals("LINK")) { 711 String text = dataResource.getString("objectInfo"); 712 outWriter.write(text); 713 } else if (dataResourceTypeId.equals("URL_RESOURCE")) { 714 String text = null; 715 URL url = new URL (dataResource.getString("objectInfo")); 716 if (url.getHost() != null) { InputStream in = url.openStream(); 718 int c; 719 StringWriter sw = new StringWriter (); 720 while ((c = in.read()) != -1) { 721 sw.write(c); 722 } 723 sw.close(); 724 text = sw.toString(); 725 } else { 726 String prefix = buildRequestPrefix(delegator, locale, webSiteId, https); 727 String sep = ""; 728 if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { 730 sep = "/"; 731 } 732 String s2 = prefix + sep + url.toString(); 733 URL url2 = new URL (s2); 734 text = (String ) url2.getContent(); 735 } 736 outWriter.write(text); 737 } else if (dataResourceTypeId.indexOf("_FILE") >= 0) { 738 String rootDir = (String ) templateContext.get("rootDir"); 739 if (UtilValidate.isEmpty(rootDir)) { 740 if (context != null) 741 rootDir = (String ) 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 getDataResourceTextCache(GenericValue dataResource, String mimeTypeId, Locale locale, Map context, GenericDelegator delegator) throws IOException , GeneralException { 754 Writer outWriter = new StringWriter (); 755 writeDataResourceText(dataResource, mimeTypeId, locale, context, delegator, outWriter); 756 return outWriter.toString(); 757 } 758 759 public static void writeDataResourceTextCache(GenericValue dataResource, String mimeTypeId, Locale locale, Map context, GenericDelegator delegator, Writer outWriter) throws IOException , GeneralException { 760 761 if (context == null) 762 context = new HashMap (); 763 764 String text = null; 765 String webSiteId = (String ) context.get("webSiteId"); 766 String https = (String ) context.get("https"); 767 768 String dataResourceId = dataResource.getString("dataResourceId"); 769 String dataResourceTypeId = dataResource.getString("dataResourceTypeId"); 770 String 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 797 798 text = (String ) 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 url = new URL (dataResource.getString("objectInfo")); 805 if (url.getHost() != null) { InputStream in = url.openStream(); 807 int c; 808 StringWriter sw = new StringWriter (); 809 while ((c = in.read()) != -1) { 810 sw.write(c); 811 } 812 sw.close(); 813 text = sw.toString(); 814 } else { 815 String prefix = buildRequestPrefix(delegator, locale, webSiteId, https); 816 String sep = ""; 817 if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { 819 sep = "/"; 820 } 821 String s2 = prefix + sep + url.toString(); 822 URL url2 = new URL (s2); 823 text = (String ) url2.getContent(); 824 } 825 writeText(text, dataResourceMimeTypeId, mimeTypeId, outWriter); 826 } else if (dataResourceTypeId.indexOf("_FILE_BIN") >= 0) { 827 String rootDir = (String ) context.get("rootDir"); 828 String 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 rootDir = (String ) 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 textData, String dataResourceMimeType, String targetMimeType, Writer out) throws IOException { 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 865 String 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 dataResourceTypeId, String objectInfo, String rootDir, Writer out) throws GeneralException, IOException { 874 876 if (dataResourceTypeId.equals("LOCAL_FILE")) { 877 File file = new File (objectInfo); 878 if (!file.isAbsolute()) { 879 throw new GeneralException("File (" + objectInfo + ") is not absolute"); 880 } 881 int c; 882 FileReader in = new FileReader (file); 883 while ((c = in.read()) != -1) { 884 out.write(c); 885 } 886 } else if (dataResourceTypeId.equals("OFBIZ_FILE")) { 887 String prefix = System.getProperty("ofbiz.home"); 888 String sep = ""; 889 if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { 890 sep = "/"; 891 } 892 File file = new File (prefix + sep + objectInfo); 893 int c; 894 FileReader in = new FileReader (file); 895 while ((c = in.read()) != -1) 896 out.write(c); 897 } else if (dataResourceTypeId.equals("CONTEXT_FILE")) { 898 String prefix = rootDir; 899 String sep = ""; 900 if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { 901 sep = "/"; 902 } 903 File file = new File (prefix + sep + objectInfo); 904 int c; 905 FileReader in = null; 906 try { 907 in = new FileReader (file); 908 String enc = in.getEncoding(); 909 if (Debug.infoOn()) Debug.logInfo("in serveImage, encoding:" + enc, module); 910 911 } catch (FileNotFoundException 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 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 } 922 return; 923 } 924 925 926 public static String buildRequestPrefix(GenericDelegator delegator, Locale locale, String webSiteId, String https) { 927 String prefix = null; 928 Map prefixValues = new HashMap (); 929 NotificationServices.setBaseUrl(delegator, webSiteId, prefixValues); 930 if (https != null && https.equalsIgnoreCase("true")) { 931 prefix = (String ) prefixValues.get("baseSecureUrl"); 932 } else { 933 prefix = (String ) 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 getContentFile(String dataResourceTypeId, String objectInfo, String rootDir) throws GeneralException, FileNotFoundException { 947 948 File file = null; 949 if (dataResourceTypeId.equals("LOCAL_FILE") || dataResourceTypeId.equals("LOCAL_FILE_BIN")) { 950 file = new File (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 prefix = System.getProperty("ofbiz.home"); 957 String sep = ""; 958 if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { 959 sep = "/"; 960 } 961 file = new File (prefix + sep + objectInfo); 962 } else if (dataResourceTypeId.equals("CONTEXT_FILE") || dataResourceTypeId.equals("CONTEXT_FILE_BIN")) { 963 String prefix = rootDir; 964 String sep = ""; 965 if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { 966 sep = "/"; 967 } 968 file = new File (prefix + sep + objectInfo); 969 } 970 return file; 971 } 972 973 974 public static String getDataResourceMimeType(GenericDelegator delegator, String dataResourceId, GenericValue view) throws GenericEntityException { 975 976 String mimeType = null; 977 if (view != null) 978 mimeType = view.getString("drMimeTypeId"); 979 if (UtilValidate.isEmpty(mimeType) && UtilValidate.isNotEmpty(dataResourceId)) { 981 GenericValue dataResource = delegator.findByPrimaryKeyCache("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId)); 982 mimeType = dataResource.getString("mimeTypeId"); 984 985 } 986 return mimeType; 987 } 988 989 public static String getDataResourceContentUploadPath() { 990 String 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 ofbizHome = System.getProperty("ofbiz.home"); 996 997 if (!initialPath.startsWith("/")) { 998 initialPath = "/" + initialPath; 999 } 1000 1001 Comparator desc = new Comparator () { 1003 public int compare(Object o1, Object o2) { 1004 if (((Long ) o1).longValue() > ((Long ) o2).longValue()) { 1005 return -1; 1006 } else if (((Long ) o1).longValue() < ((Long ) o2).longValue()) { 1007 return 1; 1008 } 1009 return 0; 1010 } 1011 }; 1012 1013 String parentDir = ofbizHome + initialPath; 1015 File parent = new File (parentDir); 1016 TreeMap dirMap = new TreeMap (desc); 1017 if (parent.exists()) { 1018 File [] subs = parent.listFiles(); 1019 for (int i = 0; i < subs.length; i++) { 1020 if (subs[i].isDirectory()) { 1021 dirMap.put(new Long (subs[0].lastModified()), subs[i]); 1022 } 1023 } 1024 } else { 1025 boolean created = parent.mkdir(); 1027 if (!created) { 1028 Debug.logWarning("Unable to create top level upload directory [" + parentDir + "].", module); 1029 } 1030 } 1031 1032 File latestDir = null; 1034 if (dirMap != null && dirMap.size() > 0) { 1035 latestDir = (File ) dirMap.values().iterator().next(); 1036 if (latestDir != null) { 1037 File [] 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 makeNewDirectory(File parent) { 1051 File latestDir = null; 1052 boolean newDir = false; 1053 while (!newDir) { 1054 latestDir = new File (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 os, GenericDelegator delegator, String dataResourceId, String https, String webSiteId, Locale locale, String rootDir) throws IOException , 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 dataResourceTypeId = dataResource.getString("dataResourceTypeId"); 1070 if (UtilValidate.isEmpty(dataResourceTypeId)) { 1071 dataResourceTypeId = "SHORT_TEXT"; 1072 } 1073 String mimeTypeId = dataResource.getString("mimeTypeId"); 1074 if (UtilValidate.isEmpty(mimeTypeId)) { 1075 mimeTypeId = "text/html"; 1076 } 1077 1078 if (dataResourceTypeId.equals("SHORT_TEXT")) { 1079 String 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 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 text = dataResource.getString("objectInfo"); 1092 os.write(text.getBytes()); 1093 } else if (dataResourceTypeId.equals("URL_RESOURCE")) { 1094 URL url = new URL (dataResource.getString("objectInfo")); 1095 if (url.getHost() == null) { String prefix = buildRequestPrefix(delegator, locale, webSiteId, https); 1097 String sep = ""; 1098 if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { 1100 sep = "/"; 1101 } 1102 String s2 = prefix + sep + url.toString(); 1103 url = new URL (s2); 1104 } 1105 InputStream 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 objectInfo = dataResource.getString("objectInfo"); 1112 File inputFile = getContentFile(dataResourceTypeId, objectInfo, rootDir); 1113 FileInputStream fis = new FileInputStream (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 dataResourceId, String https, String webSiteId, Locale locale, String rootDir) throws IOException , GeneralException { 1128 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 1129 streamDataResource(baos, delegator, dataResourceId, https, webSiteId, locale, rootDir); 1130 ByteWrapper byteWrapper = new ByteWrapper(baos.toByteArray()); 1131 return byteWrapper; 1132 } 1133} 1134 | Popular Tags |