| 1 6 package com.dotmarketing.util; 7 8 import java.io.BufferedReader ; 9 import java.io.File ; 10 import java.io.IOException ; 11 import java.io.InputStreamReader ; 12 import java.io.LineNumberReader ; 13 import java.io.Reader ; 14 import java.net.URL ; 15 import java.net.URLEncoder ; 16 import java.text.NumberFormat ; 17 import java.text.SimpleDateFormat ; 18 import java.util.ArrayList ; 19 import java.util.Date ; 20 import java.util.GregorianCalendar ; 21 import java.util.HashMap ; 22 import java.util.HashSet ; 23 import java.util.Iterator ; 24 import java.util.List ; 25 import java.util.NoSuchElementException ; 26 import java.util.Random ; 27 import java.util.Set ; 28 import java.util.StringTokenizer ; 29 import java.util.TimeZone ; 30 31 import javax.servlet.http.Cookie ; 32 import javax.servlet.http.HttpServletRequest ; 33 34 import org.apache.velocity.Template; 35 import org.apache.velocity.app.Velocity; 36 37 import com.dotmarketing.beans.Host; 38 import com.dotmarketing.beans.Identifier; 39 import com.dotmarketing.beans.UserProxy; 40 import com.dotmarketing.beans.WebAsset; 41 import com.dotmarketing.cache.LiveCache; 42 import com.dotmarketing.cache.PageNotFoundCache; 43 import com.dotmarketing.cache.WorkingCache; 44 import com.dotmarketing.cms.factories.PublicUserFactory; 45 import com.dotmarketing.factories.IdentifierFactory; 46 import com.dotmarketing.factories.InodeFactory; 47 import com.dotmarketing.factories.UserProxyFactory; 48 import com.dotmarketing.factories.WebAssetFactory; 49 import com.dotmarketing.menubuilders.RefreshMenus; 50 import com.dotmarketing.portlets.categories.model.Category; 51 import com.dotmarketing.portlets.containers.model.Container; 52 import com.dotmarketing.portlets.contentlet.factories.ContentletFactory; 53 import com.dotmarketing.portlets.contentlet.model.Contentlet; 54 import com.dotmarketing.portlets.discountcode.factories.DiscountCodeFactory; 55 import com.dotmarketing.portlets.discountcode.model.DiscountCode; 56 import com.dotmarketing.portlets.folders.factories.FolderFactory; 57 import com.dotmarketing.portlets.folders.model.Folder; 58 import com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory; 59 import com.dotmarketing.portlets.htmlpages.model.HTMLPage; 60 import com.dotmarketing.portlets.order_manager.factories.OrderFactory; 61 import com.dotmarketing.portlets.order_manager.factories.OrderItemFactory; 62 import com.dotmarketing.portlets.order_manager.model.Order; 63 import com.dotmarketing.portlets.order_manager.model.OrderItem; 64 import com.dotmarketing.portlets.order_manager.struts.OrderForm; 65 import com.dotmarketing.portlets.order_manager.struts.OrderItemForm; 66 import com.dotmarketing.portlets.organization.model.Organization; 67 import com.dotmarketing.portlets.product.factories.ProductFactory; 68 import com.dotmarketing.portlets.product.factories.ProductFormatFactory; 69 import com.dotmarketing.portlets.product.model.Product; 70 import com.dotmarketing.portlets.product.model.ProductFormat; 71 import com.dotmarketing.services.PageServices; 72 import com.liferay.portal.model.User; 73 import com.liferay.util.Randomizer; 74 75 79 public class UtilMethods { 80 private static final java.text.SimpleDateFormat DATE_TO_INT_TIME = new java.text.SimpleDateFormat ( 81 "Hmm"); 82 83 private static final java.text.SimpleDateFormat JDBC_TO_DATE = new java.text.SimpleDateFormat ( 84 "yyyy-M-d H:mm:ss"); 85 86 private static final java.text.SimpleDateFormat DATE_TO_HTML_TIME = new java.text.SimpleDateFormat ( 87 "h:mma"); 88 89 private static final java.text.SimpleDateFormat DATE_TO_JS_TIME = new java.text.SimpleDateFormat ( 90 "H:mm"); 91 92 private static final java.text.SimpleDateFormat DATE_TO_JDBC = new java.text.SimpleDateFormat ( 93 "yyyy-MM-dd H:mm:ss"); 94 95 private static final java.text.SimpleDateFormat DATE_TO_SHORT_JDBC = new java.text.SimpleDateFormat ( 96 "yyyy-MM-dd"); 97 98 private static final java.text.SimpleDateFormat DATE_TO_YEAR = new java.text.SimpleDateFormat ( 99 "yyyy"); 100 101 private static final java.text.SimpleDateFormat DATE_TO_HTML_DATE = new java.text.SimpleDateFormat ( 102 "M/d/yyyy"); 103 104 private static final java.text.SimpleDateFormat DATE_TO_DAY_VIEW_DATE = new java.text.SimpleDateFormat ( 105 "MMMM d"); 106 107 private static final java.text.SimpleDateFormat HTML_DATETIME_TO_DATE = new java.text.SimpleDateFormat ( 108 "M/d/yyyy h:mm a"); 109 110 private static final java.text.SimpleDateFormat HTML_DATETIME24_TO_DATE = new java.text.SimpleDateFormat ( 111 "M/d/yyyy H:mm"); 112 113 private static final java.text.SimpleDateFormat DATE_TO_CONTENT_EXPIRES_DATE = new java.text.SimpleDateFormat ( 114 "EEE, d MMM yyyy HH:mm:ss"); 115 116 private static final java.text.SimpleDateFormat DATE_TO_PRETTY_HTML_DATE = new java.text.SimpleDateFormat ( 117 "EEE, MMMM d yyyy"); 118 119 private static final java.util.Map <String , String > _CC_MAPPINGS = new HashMap <String , String >(); 120 121 private static final java.text.SimpleDateFormat PIDMS_TEXT_TO_DATE = new java.text.SimpleDateFormat ( 122 "yyyy/MM/dd h:mm a"); 123 124 private static final java.text.SimpleDateFormat DATE_TO_LONG_PRETTY_HTML_DATE = new java.text.SimpleDateFormat ( 125 "EEE, d MMM yyyy hh:mm a"); 126 127 private static final java.text.SimpleDateFormat DATE_TO_PRETTY_HTML_DATE_2 = new java.text.SimpleDateFormat ( 128 "MMMM d, yyyy"); 129 130 static { 131 _CC_MAPPINGS.put("AMEX", "American Express"); 132 _CC_MAPPINGS.put("VISA", "Master Card / Visa"); 133 _CC_MAPPINGS.put("CHPW-AMEX", "American Express"); 134 _CC_MAPPINGS.put("CHPW-VISA-MC", "Master Card / Visa"); 135 } 136 137 static HashMap <String , String > daysOfWeek = null; 138 139 public static final java.util.Date pidmsToDate(String d) { 140 java.text.ParsePosition pos = new java.text.ParsePosition (0); 141 142 return PIDMS_TEXT_TO_DATE.parse(d, pos); 143 } 144 145 public static final String join(String [] strArray, String separator) { 146 StringBuffer strBuff = new StringBuffer (); 147 148 for (int k = 0; k < strArray.length; k++) { 149 strBuff.append((String ) strArray[k]).append(separator); 150 } 151 152 return strBuff.toString(); 153 } 154 155 public static final String getCookieValue( 156 javax.servlet.http.Cookie [] cookies, String cookieName) { 157 if (cookies != null) { 158 for (int i = 0; i < cookies.length; i++) { 159 javax.servlet.http.Cookie cookie = cookies[i]; 160 161 if (cookieName.equals(cookie.getName())) { 162 return (cookie.getValue()); 163 } 164 } 165 } 166 167 return null; 168 } 169 170 public static final Cookie getCookie(javax.servlet.http.Cookie [] cookies, String cookieName) { 171 if (cookies != null) { 172 for (int i = 0; i < cookies.length; i++) { 173 javax.servlet.http.Cookie cookie = cookies[i]; 174 175 if (cookieName.equals(cookie.getName())) { 176 return cookie; 177 } 178 } 179 } 180 181 return null; 182 } 183 184 public static final String dateToHTMLTimeRange(java.util.Date x, 185 java.util.Date y) { 186 String k = dateToHTMLTime(x); 187 String l = dateToHTMLTime(y); 188 189 if (k.equals(l)) { 190 return k; 191 } else { 192 return k + "-" + l; 193 } 194 } 195 196 public static final boolean isImage(String x) { 197 if (x == null) 198 return false; 199 return (x.toLowerCase().endsWith(".gif") 200 || x.toLowerCase().endsWith(".jpg") 201 || x.toLowerCase().endsWith(".jpe") 202 || x.toLowerCase().endsWith(".png") 203 || x.toLowerCase().endsWith(".png") || x.toLowerCase() 204 .endsWith(".jpeg")); 205 } 206 207 public static final String getMonthFromNow() { 208 java.util.GregorianCalendar cal = new java.util.GregorianCalendar (); 209 cal.roll(java.util.Calendar.MONTH, 1); 210 211 return DATE_TO_CONTENT_EXPIRES_DATE.format(cal.getTime()); 212 } 213 214 public static String escapeSingleQuotes(String fixme) { 215 fixme = fixme.replaceAll("'", "\\\\'"); 216 return fixme; 217 } 218 219 public static final String getMonthName(int x) { 220 if ((x < 1) || (x > 12)) { 221 x = 1; 222 } 223 224 String [] arr = {"", "January", "February", "March", "April", "May", 225 "June", "July", "August", "September", "October", "November", 226 "December"}; 227 228 return arr[x]; 229 } 230 231 public static final String getNextMonthName(int month) { 232 if ((month < 1) || (month > 12)) { 233 month = 1; 234 } 235 236 String [] arr = {"", "February", "March", "April", "May", "June", 237 "July", "August", "September", "October", "November", 238 "December", "January"}; 239 240 return arr[month]; 241 } 242 243 public static final int getNextMonthNumber(int month) { 244 return ((month < 1) || (month > 11)) ? (month = 1) : (month + 1); 245 } 246 247 public static final String getPreviousMonthName(int x) { 248 if ((x < 1) || (x > 12)) { 249 x = 1; 250 } 251 252 String [] arr = {"", "December", "January", "February", "March", 253 "April", "May", "June", "July", "August", "September", 254 "October", "November"}; 255 256 return arr[x]; 257 } 258 259 public static final int getPreviousMonthNumber(int month) { 260 return ((month < 2) || (month > 12)) ? (month = 12) : (month - 1); 261 } 262 263 public static final boolean isSet(String x) { 264 if (x == null) { 265 return false; 266 } 267 268 x = x.toLowerCase(); 269 270 if (x.indexOf("null") > -1) { 271 x = x.replaceAll("null", ""); 272 } 273 274 return (x.trim().length() > 0); 275 } 276 277 public static final boolean isSet(java.util.Date x) { 278 return ((x != null) && (x.getTime() > 0)); 279 } 280 281 public static final boolean isSet(Float x) { 282 return (x != null); 283 } 284 285 public static final boolean isSetCrumb(String x) { 286 return (isSet(x) && !x.equals("index")); 287 } 288 289 public static final boolean isSetHTML(String x) { 290 if (x == null) { 291 return false; 292 } 293 294 x = x.toLowerCase(); 295 x = x.replaceAll("null", ""); 296 x = x.replaceAll("<[^>]*>", ""); 297 x = x.replace('\0', ' '); 298 Logger.debug(UtilMethods.class, "X:" + x + ":X"); 299 300 return (x.trim().length() > 1); 301 } 302 303 public static final boolean isValidEmail(String email) { 304 if (email == null) { 305 return false; 306 } 307 308 return java.util.regex.Pattern.matches( 309 "^[\\w-\\.]{1,}\\@([\\da-zA-Z-]{1,}\\.){1,}[\\da-zA-Z-]{2,3}$", 310 email); 311 } 312 313 public static final boolean isValidURL(String url) { 314 if (url == null) { 315 return false; 316 } 317 318 return java.util.regex.Pattern 319 .matches( 320 "((http|ftp|https):\\/\\/w{3}[\\d]*.|(http|ftp|https):\\/\\/|w{3}[\\d]*.)([\\w\\d\\._\\-#\\(\\)\\[\\]\\\\,;:]+@[\\w\\d\\._\\-#\\(\\)\\[\\]\\\\,;:])?([a-z0-9]+.)*[a-z\\-0-9]+.([a-z]{2,3})?[a-z]{2,6}(:[0-9]+)?(\\/[\\/a-z0-9\\._\\-,]+)*[a-z0-9\\-_\\.\\s\\%]+(\\?[a-z0-9=%&\\.\\-,#]+)?", 321 url); 322 325 } 326 327 public static final boolean isValidEmail(Object email) { 328 if (email == null) { 329 return false; 330 } 331 332 return isValidEmail((String ) email); 333 } 334 335 342 public static final String CmdExec(String cmdline) { 343 StringBuffer sb = new StringBuffer (); 344 345 try { 346 String line; 347 Process p = Runtime.getRuntime().exec(cmdline); 348 BufferedReader input = new BufferedReader (new InputStreamReader (p 349 .getInputStream())); 350 351 while ((line = input.readLine()) != null) { 352 sb.append(line); 353 } 354 355 input.close(); 356 } catch (Exception err) { 357 sb.append(err); 358 } 359 360 return sb.toString(); 361 } 362 363 public static final String dateToDayViewDate(java.util.Date x) { 364 if (x == null) { 365 return ""; 366 } 367 368 return DATE_TO_DAY_VIEW_DATE.format(x); 369 } 370 371 public static final String dateToHTMLDateTimeRange(java.util.Date x, 372 java.util.Date y, TimeZone tz) { 373 String i = dateToHTMLDate(x, tz); 374 String j = dateToHTMLDate(y, tz); 375 String k = dateToHTMLTime(x, tz); 376 String l = dateToHTMLTime(y, tz); 377 378 if (i.equals(j) && k.equals(l)) { 379 return i + " " + k; 380 } else if (i.equals(j)) { 381 return i + " " + k + "-" + l; 382 } else { 383 return i + " - " + j; 384 } 385 } 386 387 public static final String dateToHTMLDate(java.util.Date x) { 388 if (x == null) { 389 return ""; 390 } 391 return DATE_TO_HTML_DATE.format(x); 392 } 393 394 public static final String dateToHTMLDate(java.util.Date x, String format) { 395 if (x == null) { 396 return ""; 397 } 398 java.text.SimpleDateFormat mySimpleFormat = new java.text.SimpleDateFormat ( 399 format); 400 return mySimpleFormat.format(x); 401 } 402 403 public static final String dateToHTMLDate(java.util.Date x, TimeZone tz) { 404 if (x == null) { 405 return ""; 406 } 407 java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat ( 408 "M/d/yyyy"); 409 formatter.setTimeZone(tz); 410 return formatter.format(x); 411 } 412 413 public static final String dateToHTMLDateRange(java.util.Date x, 414 java.util.Date y) { 415 String i = dateToHTMLDate(x); 416 String j = dateToHTMLDate(y); 417 418 if (i.equals(j)) { 419 return i; 420 } else { 421 return i + " - " + j; 422 } 423 } 424 425 public static final String dateToHTMLDateRange(java.util.Date x, 426 java.util.Date y, TimeZone tz) { 427 String i = dateToHTMLDate(x, tz); 428 String j = dateToHTMLDate(y, tz); 429 430 if (i.equals(j)) { 431 return i; 432 } else { 433 return i + " - " + j; 434 } 435 } 436 437 public static final String dateToHTMLDateTimeRange(java.util.Date x, 438 java.util.Date y) { 439 String i = dateToHTMLDate(x); 440 String j = dateToHTMLDate(y); 441 String k = dateToHTMLTime(x); 442 String l = dateToHTMLTime(y); 443 444 if (i.equals(j) && k.equals(l)) { 445 return i + " " + k; 446 } else if (i.equals(j)) { 447 return i + " " + k + "-" + l; 448 } else { 449 return i + " - " + j; 450 } 451 } 452 453 public static final String dateToHTMLTime(java.util.Date x) { 454 if (x == null) { 455 return ""; 456 } 457 458 return DATE_TO_HTML_TIME.format(x); 459 } 460 461 public static final String dateToHTMLTime(java.util.Date x, TimeZone tz) { 462 if (x == null) { 463 return ""; 464 } 465 466 java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat ( 467 "h:mm a"); 468 formatter.setTimeZone(tz); 469 return formatter.format(x); 470 } 471 472 public static final int dateToIntTime(java.util.Date x) { 473 return Integer.parseInt(DATE_TO_INT_TIME.format(x)); 474 } 475 476 public static final String dateToJDBC(java.util.Date x) { 477 return DATE_TO_JDBC.format(x); 478 } 479 480 public static final String dateToShortJDBC(java.util.Date x) { 481 return DATE_TO_SHORT_JDBC.format(x); 482 } 483 484 public static final String dateToJSTime(java.util.Date x) { 485 return DATE_TO_JS_TIME.format(x); 486 } 487 488 public static final String dateToPrettyHTMLDate(java.util.Date x) { 489 if (x == null) { 490 return ""; 491 } 492 493 return DATE_TO_PRETTY_HTML_DATE.format(x); 494 } 495 496 public static final String dateToPrettyHTMLDate(java.util.Date x, 497 TimeZone tz) { 498 if (x == null) { 499 return ""; 500 } 501 java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat ( 502 "EEE, MMMM d yyyy"); 503 formatter.setTimeZone(tz); 504 return formatter.format(x); 505 } 506 507 public static final String dateToYear(java.util.Date x) { 508 return DATE_TO_YEAR.format(x); 509 } 510 511 public static final String dollarFormat(float f) { 512 if (f == 0) { 513 return "0.00"; 514 } 515 516 java.text.DecimalFormat cf = new java.text.DecimalFormat ("########.00"); 517 518 return cf.format(f); 519 } 520 521 526 public static final String formatter(String original, String from, String to) { 527 return replace(original, from, to); 528 } 529 530 public static final StringBuffer formatterStringBuffer( 531 StringBuffer original, String from, String to) { 532 return replaceStringBuffer(original, from, to); 533 } 534 535 public static final StringBuffer replaceStringBuffer(StringBuffer original, 536 String from, String to) { 537 StringBuffer finished = new StringBuffer (); 538 539 if (original == null) { 540 return finished; 541 } 542 543 int start = 0; 546 int index = original.indexOf(from); 547 548 while (index != -1) { 549 finished.append(original.substring(start, index)); 550 finished.append(to); 551 start = index + from.length(); 552 index = original.indexOf(from, start); 553 } 554 555 finished.append(original.substring(start)); 556 557 return finished; 558 } 559 560 public static final java.util.Date htmlDateTimeToDate(String d) { 561 java.util.Date rDate = null; 562 java.text.ParsePosition pos = new java.text.ParsePosition (0); 563 rDate = HTML_DATETIME_TO_DATE.parse(d, pos); 564 565 if (rDate == null) { 566 rDate = HTML_DATETIME24_TO_DATE.parse(d, pos); 567 } 568 569 if (rDate == null) { 570 rDate = new java.util.Date (); 571 } 572 573 return rDate; 574 } 575 576 public static final String htmlLineBreak(String original) { 577 if (original == null) { 580 return ""; 581 } 582 583 return original.replaceAll("\r", "").replaceAll("\n\n", 584 "<BR> <BR>").replaceAll("\n", "<BR>"); 585 586 } 588 589 public static final java.util.Date htmlToDate(String d) { 590 java.util.Date rDate = null; 591 java.text.ParsePosition pos = new java.text.ParsePosition (0); 592 DATE_TO_HTML_DATE.setLenient(true); 593 rDate = (java.util.Date ) DATE_TO_HTML_DATE.parse(d, pos); 594 595 return rDate; 598 } 599 600 public static final java.util.Date jdbcToDate(String d) { 601 java.util.Date rDate = null; 602 java.text.ParsePosition pos = new java.text.ParsePosition (0); 603 rDate = JDBC_TO_DATE.parse(d, pos); 604 605 if (rDate == null) { 606 rDate = new java.util.Date (); 607 } 608 609 return rDate; 610 } 611 612 616 public static String jdbcDateToHtml(String jdbcdate) { 617 if (!isSet(jdbcdate)) { 618 return ""; 619 } 620 621 if (jdbcdate.indexOf("/") > 0) { 622 return jdbcdate; 623 } 624 625 StringBuffer out = new StringBuffer (""); 626 627 if ((jdbcdate.indexOf("-") > 0) 628 && (jdbcdate.lastIndexOf("-") > jdbcdate.indexOf("-"))) { 629 String [] parts = jdbcdate.split("-"); 631 String day = parts[2]; 632 633 if (day.indexOf(" ") > 0) { 634 day = day.substring(0, day.indexOf(" ")); 635 } 636 637 out.append(parts[1]); 638 out.append("/"); 639 out.append(day); 640 out.append("/"); 641 out.append(parts[0]); 642 } 643 644 return out.toString(); 645 } 646 647 public static final String obfuscateEmail(String email) { 648 if (email == null) { 651 return ""; 652 } 653 654 StringTokenizer st = new StringTokenizer (email, "@"); 655 656 if (st.countTokens() < 2) { 657 return ""; 658 } 659 660 StringBuffer sb = new StringBuffer (); 661 sb.append("<script>document.write('" + st.nextToken() + "');"); 662 sb.append("document.write('@');"); 663 sb.append("document.write('" + st.nextToken() + "');</script>"); 664 665 return sb.toString(); 666 } 667 668 public static final String obfuscateEmailHref(String email) { 669 if (email == null) { 672 return ""; 673 } 674 675 StringTokenizer st = new StringTokenizer (email, "@"); 676 677 if (st.countTokens() < 2) { 678 return ""; 679 } 680 681 StringBuffer sb = new StringBuffer (); 682 sb.append("<script>document.write('<a HREF=\"mailto:" + st.nextToken() 683 + "');"); 684 sb.append("document.write('@');"); 685 sb.append("document.write('" + st.nextToken() + "\">');</script>"); 686 687 return sb.toString(); 688 } 689 690 public static final String obfuscateEmailHrefClass(String email, 691 String className) { 692 if (email == null) { 695 return ""; 696 } 697 698 StringTokenizer st = new StringTokenizer (email, "@"); 699 700 if (st.countTokens() < 2) { 701 return ""; 702 } 703 704 StringBuffer sb = new StringBuffer (); 705 sb.append("<script>document.write('<a HREF=\"mailto:" + st.nextToken() 706 + "');"); 707 sb.append("document.write('@');"); 708 sb.append("document.write('" + st.nextToken() + "\" class=\"" 709 + className + "\">');</script>"); 710 711 return sb.toString(); 712 } 713 714 public static String prettyShortenString(String text, int maxLength) { 715 if (text == null) { 716 return ""; 717 718 } 719 StringBuffer sb = new StringBuffer (); 720 StringTokenizer st = new StringTokenizer (text, " ,-\n&()=;_", true); 721 722 while (st.hasMoreTokens()) { 723 String token = st.nextToken(); 724 725 if ((sb.length() + token.length()) > maxLength) { 726 sb.append("..."); 727 728 break; 729 } 730 731 sb.append(token); 732 } 733 734 return sb.toString(); 735 } 736 737 public static final String replace(String original, String from, String to) { 738 if (original == null) { 739 return ""; 740 } 741 742 StringBuffer finished = new StringBuffer (); 745 int start = 0; 746 int index = original.indexOf(from); 747 748 while (index != -1) { 749 finished.append(original.substring(start, index)); 750 finished.append(to); 751 start = index + from.length(); 752 index = original.indexOf(from, start); 753 } 754 755 finished.append(original.substring(start)); 756 757 return finished.toString(); 758 } 759 760 public static final String shortenString(String s, int l) { 761 s = webifyString(s); 762 763 return (s.length() < l) ? s : (s.substring(0, l) + "..."); 764 } 765 766 public static final boolean similarStrings(String a, String b) { 767 if (a == null) { 768 a = ""; 769 } 770 771 if (b == null) { 772 b = ""; 773 } 774 775 a = ((a.length() < 15) ? a : a.substring(0, 15)).replaceAll("\\W", ""); 776 b = ((b.length() < 15) ? b : b.substring(0, 15)).replaceAll("\\W", ""); 777 778 return a.equals(b); 779 } 780 781 public static final String webifyString(String x) { 782 if ((x == null) || x.trim().equals("") || x.trim().equals("null")) { 783 return ""; 784 } else { 785 x = x.replaceAll("\"", """); 786 } 787 788 return x.trim(); 789 } 790 791 public static final String xmlifyString(String x) { 792 if ((x == null) || x.trim().equals("") || x.trim().equals("null")) { 793 return ""; 794 } else { 795 x = x.replaceAll("&", "and"); 796 x = x.replaceAll("<", ""); 797 x = x.replaceAll(">", ""); 798 x = x.replaceAll("\"", ""); 799 x = x.replaceAll("'", ""); 800 } 801 802 return x.trim(); 803 } 804 805 public static final String wrapLines(String original, int wrap) { 806 if (original == null) { 809 return ""; 810 } 811 812 StringBuffer sb = new StringBuffer (); 813 String [] words = original.split(" "); 814 int charCount = 0; 815 816 for (int i = 0; i < words.length; i++) { 817 if (words[i].indexOf("\r\n\r\n") > -1) { 818 sb.append("<BR> <BR>"); 819 } 820 821 sb.append(words[i] + " "); 822 charCount = charCount + words[i].length() + 1; 823 824 if (charCount > wrap) { 825 sb.append("<BR>"); 826 charCount = 0; 827 } 828 } 829 830 return sb.toString(); 831 } 832 833 public static String getFileExtension(String x) { 834 try { 835 if (x.lastIndexOf(".") != -1) { 836 return x.substring(x.lastIndexOf(".") + 1).toLowerCase(); 837 } else { 838 return x; 839 } 840 } catch (Exception e) { 841 return "ukn"; 842 } 843 } 844 845 public static String getFileName(String x) { 846 try { 847 if (x.lastIndexOf("/") > -1 || x.lastIndexOf("\\") > -1) { 848 int idx = (x.lastIndexOf("/") > x.lastIndexOf("\\") ? x 849 .lastIndexOf("/") : x.lastIndexOf("\\")) + 1; 850 x = x.substring(idx, x.length()); 851 } 852 if (x.lastIndexOf(".") != -1) { 853 int begin = 0; 854 if (x.lastIndexOf("/") != -1) { 855 begin = x.lastIndexOf("/") + 1; 856 } 857 return x.substring(begin, x.lastIndexOf(".")); 858 } else { 859 return x; 860 } 861 } catch (Exception e) { 862 return ""; 863 } 864 } 865 866 public static java.util.List getTimeList(int start, int duration) { 867 java.util.Calendar cal = new java.util.GregorianCalendar (); 868 List <String > out = new ArrayList <String >(); 869 cal.set(java.util.Calendar.HOUR, start); 870 cal.set(java.util.Calendar.MINUTE, 0); 871 872 if (start >= 12) { 873 cal.set(java.util.Calendar.AM_PM, java.util.Calendar.PM); 874 } else { 875 cal.set(java.util.Calendar.AM_PM, java.util.Calendar.AM); 876 } 877 878 java.text.SimpleDateFormat format = new java.text.SimpleDateFormat ( 879 "hh:mm a"); 880 881 for (int i = 0; i < ((duration * 4) + 1); i++) { 882 out.add(format.format(cal.getTime())); 883 cal.add(java.util.Calendar.MINUTE, 15); 884 } 885 886 return out; 887 } 888 889 public static StringBuffer getURL(String URI) { 890 StringBuffer html = new StringBuffer (); 891 html.append(""); 892 893 try { 894 java.net.URL dbrNewsletter = new java.net.URL (URI); 895 java.net.URLConnection dbrn = dbrNewsletter.openConnection(); 896 BufferedReader in = new BufferedReader (new InputStreamReader (dbrn 897 .getInputStream())); 898 String inputLine; 899 900 while ((inputLine = in.readLine()) != null) { 901 html.append(inputLine + "\n"); 902 } 903 904 in.close(); 905 } catch (Exception e) { 906 Logger.warn(UtilMethods.class, "Browser class failed to get page: " 907 +URI+" - "+e, e); 908 } 909 910 return html; 911 } 912 913 public static String capitalize(String s) { 914 if (s == null) { 915 return ""; 916 } 917 918 if (s.indexOf(".") > -1) { 919 s = s.substring(0, s.lastIndexOf(".")); 920 } 921 922 char[] chars = s.toLowerCase().toCharArray(); 923 924 boolean capitalNext = true; 926 927 for (int i = 0; i < chars.length; i++) { 928 char x = chars[i]; 929 930 if (capitalNext) { 931 x = Character.toUpperCase(chars[i]); 932 capitalNext = false; 933 } 934 935 if ((x < 64) || (x > 123) || ((x > 90) && (x < 97))) { 936 x = ' '; 937 capitalNext = true; 938 } 939 940 chars[i] = x; 941 } 942 943 return new String (chars); 944 } 945 946 public static String capitalize(Object s) { 947 try { 948 return capitalize(s.toString()); 949 } catch (Exception e) { 950 return ""; 951 } 952 } 953 954 public static String csvifyString(String x) { 955 return webifyString(x).replace(',', ' '); 956 } 957 958 public static String htmlifyString(String x) { 959 return webifyString(x).replaceAll("<", "<").replaceAll(">", ">"); 960 } 961 962 967 public static String httpifyString(String x) { 968 if (x == null) { 969 return null; 970 } 971 972 String testString = x.trim().toLowerCase(); 973 974 if (testString.startsWith("http://") 975 || testString.startsWith("https://") 976 || testString.startsWith("mailto:") 977 || testString.startsWith("ftp://")) { 978 return x; 979 } else { 980 return ("http://" + x); 981 } 982 } 983 984 public static String javaScriptify(String x) { 985 if (x == null) { 986 return ""; 987 } else { 988 return x.replace('\r', ' ').replace('\n', ' '); 989 } 990 } 991 992 public static String javaScriptifyVariable(String x) { 993 if (x == null) { 994 return ""; 995 } else { 996 x = x.replaceAll("[^A-Za-z0-9_]", ""); 997 return x; 998 } 999 } 1000 1001 public static String truncatify(String x) { 1002 if (x.length() > 15) { 1003 java.util.StringTokenizer st2 = new java.util.StringTokenizer (x, 1004 "_- ;,.", true); 1005 StringBuffer buffer = new StringBuffer (); 1006 1007 while (st2.hasMoreTokens()) { 1008 buffer.append(st2.nextToken()); 1009 1010 if (buffer.length() > 15) { 1011 if (st2.hasMoreTokens()) { 1012 buffer.append("..."); 1013 } 1014 1015 break; 1016 } 1017 } 1018 1019 return buffer.toString(); 1020 } else { 1021 return x; 1022 } 1023 } 1024 1025 public static String truncatify(String x, int len) { 1026 if (x.length() > len) { 1027 java.util.StringTokenizer st2 = new java.util.StringTokenizer (x, 1028 "_- ;,.", true); 1029 StringBuffer buffer = new StringBuffer (); 1030 1031 while (st2.hasMoreTokens()) { 1032 buffer.append(st2.nextToken()); 1033 1034 if (buffer.length() > len) { 1035 if (st2.hasMoreTokens()) { 1036 buffer.append("..."); 1037 } 1038 1039 break; 1040 } 1041 } 1042 1043 return buffer.toString(); 1044 } else { 1045 return x; 1046 } 1047 } 1048 1049 public static String prettyByteify(long x) { 1050 String myBytes = "0b"; 1051 1052 if (x > (1024 * 1024)) { 1053 myBytes = ((x / (1024 * 1024)) + 1) + "Mb"; 1054 } else if (x > 1024) { 1055 myBytes = ((x / (1024)) + 1) + "kb"; 1056 } else { 1057 myBytes = x + "b"; 1058 } 1059 1060 return myBytes; 1061 } 1062 1063 public static String cleanURI(String uri) { 1064 if (uri.indexOf(".") < 0) { 1066 if (!uri.endsWith("/")) { 1067 uri += "/"; 1068 } 1069 1070 uri += "index.html"; 1071 } 1072 1073 return uri; 1074 } 1075 1076 public static String cleanFileSystemPathURI(String path) { 1077 if (path.indexOf("..") != -1 && path.indexOf("WEB-INF") != -1 1078 && path.indexOf("META-INF") != -1 && path.indexOf("!") != -1 1079 && path.indexOf(":") != -1 && path.indexOf(";") != -1 1080 && path.indexOf(";") != -1 && path.indexOf("&") != -1 1081 && path.indexOf("?") != -1 && path.indexOf("$") != -1 1082 && path.indexOf("*") != -1 && path.indexOf("\"") != -1 1083 && path.indexOf("/") != -1 && path.indexOf("[") != -1 1084 && path.indexOf("]") != -1 && path.indexOf("=") != -1 1085 && path.indexOf("|") != -1 && path.indexOf(",") != -1) { 1086 return null; 1087 1088 } else { 1089 return path; 1090 1091 } 1092 1093 } 1094 1095 public static String getPageChannel(String uri) { 1096 java.util.StringTokenizer st = new java.util.StringTokenizer (String 1097 .valueOf(uri), "/"); 1098 String pageChannel = null; 1099 1100 if (st.hasMoreTokens()) { 1101 pageChannel = st.nextToken(); 1102 } 1103 1104 return pageChannel; 1105 } 1106 1107 public static String espaceForVelocity(String text) { 1108 if (isSet(text)) { 1109 text = replace(text, "\"", "${quote}"); 1110 text = replace(text, "\n", "${return}"); 1111 text = replace(text, "##", "${pounds}"); 1112 text = replace(text, "\r", ""); 1113 text = replace(text, "’", "'"); 1114 text = replace(text, "–", "-"); 1115 return text.trim(); 1116 } 1117 1118 return ""; 1119 } 1120 1121 public static String escapeHTMLSpecialChars(String valueSt) { 1122 1123 valueSt = valueSt.replaceAll("&", "&"); 1125 valueSt = valueSt.replaceAll("\\xA1", "¡"); 1127 valueSt = valueSt.replaceAll("\\xA2", "¢"); 1129 valueSt = valueSt.replaceAll("\\xA3", "£"); 1131 valueSt = valueSt.replaceAll("\\xA4", "¤"); 1133 valueSt = valueSt.replaceAll("\\xA5", "¥"); 1135 valueSt = valueSt.replaceAll("\\xA6", "¦"); 1137 valueSt = valueSt.replaceAll("\\xA7", "§"); 1139 valueSt = valueSt.replaceAll("\\xA8", "¨"); 1141 valueSt = valueSt.replaceAll("\\xA9", "©"); 1143 valueSt = valueSt.replaceAll("\\xAA", "ª"); 1145 valueSt = valueSt.replaceAll("\\xAB", "«"); 1147 valueSt = valueSt.replaceAll("\\xAC", "¬"); 1149 valueSt = valueSt.replaceAll("\\xAD", "­"); 1151 valueSt = valueSt.replaceAll("\\xAE", "®"); 1153 valueSt = valueSt.replaceAll("\\xAF", "¯"); 1155 valueSt = valueSt.replaceAll("\\xB0", "°"); 1157 valueSt = valueSt.replaceAll("\\xB1", "±"); 1159 valueSt = valueSt.replaceAll("\\xB2", "²"); 1161 valueSt = valueSt.replaceAll("\\xB3", "³"); 1163 valueSt = valueSt.replaceAll("\\xB4", "´"); 1165 valueSt = valueSt.replaceAll("\\xB5", "µ"); 1167 valueSt = valueSt.replaceAll("\\xB6", "¶"); 1169 valueSt = valueSt.replaceAll("\\xB7", "·"); 1171 valueSt = valueSt.replaceAll("\\xB8", "¸"); 1173 valueSt = valueSt.replaceAll("\\xB9", "¹"); 1175 valueSt = valueSt.replaceAll("\\xBA", "º"); 1177 valueSt = valueSt.replaceAll("\\xBB", "»"); 1179 valueSt = valueSt.replaceAll("\\xBC", "¼"); 1181 valueSt = valueSt.replaceAll("\\xBD", "½"); 1183 valueSt = valueSt.replaceAll("\\xBE", "¾"); 1185 valueSt = valueSt.replaceAll("\\xBF", "¿"); 1187 valueSt = valueSt.replaceAll("\\xC0", "À"); 1189 valueSt = valueSt.replaceAll("\\xC1", "Á"); 1191 valueSt = valueSt.replaceAll("\\xC2", "Â"); 1193 valueSt = valueSt.replaceAll("\\xC3", "Ã"); 1195 valueSt = valueSt.replaceAll("\\xC4", "Ä"); 1197 valueSt = valueSt.replaceAll("\\xC5", "Å"); 1199 valueSt = valueSt.replaceAll("\\xC6", "Æ"); 1201 valueSt = valueSt.replaceAll("\\xC7", "Ç"); 1203 valueSt = valueSt.replaceAll("\\xC8", "È"); 1205 valueSt = valueSt.replaceAll("\\xC9", "É"); 1207 valueSt = valueSt.replaceAll("\\xCA", "Ê"); 1209 valueSt = valueSt.replaceAll("\\xCB", "Ë"); 1211 valueSt = valueSt.replaceAll("\\xCC", "Ì"); 1213 valueSt = valueSt.replaceAll("\\xCD", "Í"); 1215 valueSt = valueSt.replaceAll("\\xCE", "Î"); 1217 valueSt = valueSt.replaceAll("\\xCF", "Ï"); 1219 valueSt = valueSt.replaceAll("\\xD0", "Ð"); 1221 valueSt = valueSt.replaceAll("\\xD1", "Ñ"); 1223 valueSt = valueSt.replaceAll("\\xD2", "Ò"); 1225 valueSt = valueSt.replaceAll("\\xD3", "Ó"); 1227 valueSt = valueSt.replaceAll("\\xD4", "Ô"); 1229 valueSt = valueSt.replaceAll("\\xD5", "Õ"); 1231 valueSt = valueSt.replaceAll("\\xD6", "Ö"); 1233 valueSt = valueSt.replaceAll("\\xD7", "×"); 1235 valueSt = valueSt.replaceAll("\\xD8", "Ø"); 1237 valueSt = valueSt.replaceAll("\\xD9", "Ù"); 1239 valueSt = valueSt.replaceAll("\\xDA", "Ú"); 1241 valueSt = valueSt.replaceAll("\\xDB", "Û"); 1243 valueSt = valueSt.replaceAll("\\xDC", "Ü"); 1245 valueSt = valueSt.replaceAll("\\xDD", "Ý"); 1247 valueSt = valueSt.replaceAll("\\xDE", "Þ"); 1249 valueSt = valueSt.replaceAll("\\xDF", "ß"); 1251 valueSt = valueSt.replaceAll("\\xE0", "à"); 1253 valueSt = valueSt.replaceAll("\\xE1", "á"); 1255 valueSt = valueSt.replaceAll("\\xE2", "â"); 1257 valueSt = valueSt.replaceAll("\\xE3", "ã"); 1259 valueSt = valueSt.replaceAll("\\xE4", "ä"); 1261 valueSt = valueSt.replaceAll("\\xE5", "å"); 1263 valueSt = valueSt.replaceAll("\\xE6", "æ"); 1265 valueSt = valueSt.replaceAll("\\xE7", "ç"); 1267 valueSt = valueSt.replaceAll("\\xE8", "è"); 1269 valueSt = valueSt.replaceAll("\\xE9", "é"); 1271 valueSt = valueSt.replaceAll("\\xEA", "ê"); 1273 valueSt = valueSt.replaceAll("\\xEB", "ë"); 1275 valueSt = valueSt.replaceAll("\\xEC", "ì"); 1277 valueSt = valueSt.replaceAll("\\xED", "í"); 1279 valueSt = valueSt.replaceAll("\\xEE", "î"); 1281 valueSt = valueSt.replaceAll("\\xEF", "ï"); 1283 valueSt = valueSt.replaceAll("\\xF0", "ð"); 1285 valueSt = valueSt.replaceAll("\\xF1", "ñ"); 1287 valueSt = valueSt.replaceAll("\\xF2", "ò"); 1289 valueSt = valueSt.replaceAll("\\xF3", "ó"); 1291 valueSt = valueSt.replaceAll("\\xF4", "ô"); 1293 valueSt = valueSt.replaceAll("\\xF5", "õ"); 1295 valueSt = valueSt.replaceAll("\\xF6", "ö"); 1297 valueSt = valueSt.replaceAll("\\xF7", "÷"); 1299 valueSt = valueSt.replaceAll("\\xF8", "ø"); 1301 valueSt = valueSt.replaceAll("\\xF9", "ù"); 1303 valueSt = valueSt.replaceAll("\\xFA", "ú"); 1305 valueSt = valueSt.replaceAll("\\xFB", "û"); 1307 valueSt = valueSt.replaceAll("\\xFC", "ü"); 1309 valueSt = valueSt.replaceAll("\\xFD", "ý"); 1311 valueSt = valueSt.replaceAll("\\xFE", "þ"); 1313 valueSt = valueSt.replaceAll("\\xFF", "ÿ"); 1315 1316 1318 valueSt = valueSt.replaceAll("\\x82", "‚"); 1320 valueSt = valueSt.replaceAll("\\x83", "ƒ"); 1322 valueSt = valueSt.replaceAll("\\x84", "„"); 1324 valueSt = valueSt.replaceAll("\\x85", "…"); 1326 valueSt = valueSt.replaceAll("\\x86", "†"); 1328 valueSt = valueSt.replaceAll("\\x87", "‡"); 1330 valueSt = valueSt.replaceAll("\\x8A", "Š"); 1332 valueSt = valueSt.replaceAll("\\x8C", "Œ"); 1334 valueSt = valueSt.replaceAll("\\x8D", ""); 1336 valueSt = valueSt.replaceAll("\\x8E", ""); 1338 valueSt = valueSt.replaceAll("\\x8F", ""); 1340 valueSt = valueSt.replaceAll("\\x90", ""); 1342 valueSt = valueSt.replaceAll("\\x91", "‘"); 1344 valueSt = valueSt.replaceAll("\\x92", "’"); 1346 valueSt = valueSt.replaceAll("\\x93", "“"); 1348 valueSt = valueSt.replaceAll("\\x94", "”"); 1350 valueSt = valueSt.replaceAll("\\x95", "•"); 1352 valueSt = valueSt.replaceAll("\\x96", "–"); 1354 valueSt = valueSt.replaceAll("\\x97", "—"); 1356 valueSt = valueSt.replaceAll("\\x98", "˜"); 1358 valueSt = valueSt.replaceAll("\\x99", "™"); 1360 valueSt = valueSt.replaceAll("\\x9A", "š"); 1362 valueSt = valueSt.replaceAll("\\x9C", "œ"); 1364 valueSt = valueSt.replaceAll("\\x9D", ""); 1366 valueSt = valueSt.replaceAll("\\x9E", ""); 1368 valueSt = valueSt.replaceAll("\\x9F", "Ÿ"); 1370 1371 return valueSt; 1372 } 1373 1374 public static String fixBreaks(String fixme) { 1375 if (isSet(fixme)) { 1376 fixme = replace(fixme, "${return}", "\n"); 1377 return fixme; 1378 } 1379 return ""; 1380 } 1381 1382 1385 public static String escapeQuotes(String fixme) { 1386 String doubleQuote = "\""; 1387 1388 String singleQuote = "'"; 1389 String escapedSingleQuote = "\\'"; 1390 1391 if (fixme != null) { 1392 fixme = fixme.trim(); 1393 1394 try { 1395 fixme = fixme.replaceAll(doubleQuote, doubleQuote); 1397 1398 fixme = fixme.replaceAll(singleQuote, escapedSingleQuote); 1400 1401 return fixme; 1402 } catch (Exception e) { 1403 Logger.error(UtilMethods.class, "Could not parse string [" 1404 + fixme + "] for escaping quotes: " + e.toString(), e); 1405 return ""; 1406 } 1407 } else { 1408 return ""; 1409 } 1410 } 1411 1412 1415 public static String sqlify(String fixme) { 1416 String singleQuote = "'"; 1417 String escapedSingleQuote = "''"; 1418 1419 if (fixme != null) { 1420 fixme = fixme.trim(); 1421 1422 try { 1423 fixme = fixme.replaceAll(singleQuote, escapedSingleQuote); 1425 1426 return fixme; 1427 } catch (Exception e) { 1428 Logger.error(UtilMethods.class, "Could not parse string [" 1429 + fixme + "] for escaping single quotes: " 1430 + e.toString(), e); 1431 return ""; 1432 } 1433 } else { 1434 return ""; 1435 } 1436 } 1437 1438 public static boolean inString(String haystack, String needle) { 1439 if ((haystack == null) || (needle == null)) { 1440 return false; 1441 } 1442 1443 return (haystack.indexOf(needle) > -1); 1444 } 1445 1446 public static String dayify(String x) { 1447 StringBuffer sb = new StringBuffer (); 1448 1449 if (daysOfWeek == null) { 1450 daysOfWeek = new HashMap <String , String >(); 1451 daysOfWeek.put("M", "Monday"); 1452 daysOfWeek.put("T", "Tuesday"); 1453 daysOfWeek.put("W", "Wednesday"); 1454 daysOfWeek.put("R", "Thursday"); 1455 daysOfWeek.put("F", "Friday"); 1456 daysOfWeek.put("S", "Saturday"); 1457 daysOfWeek.put("&", "Sunday"); 1458 } 1459 1460 if (x.indexOf("ARR") > -1) { 1461 return "to be arranged"; 1462 } 1463 1464 char[] chrs = x.toCharArray(); 1465 1466 for (int i = 0; i < chrs.length; i++) { 1467 if (daysOfWeek.get(String.valueOf(chrs[i])) != null) { 1468 if (sb.length() > 0) 1469 sb.append(", "); 1470 sb.append(daysOfWeek.get(String.valueOf(chrs[i]))); 1471 } 1472 } 1473 1474 return sb.toString(); 1475 } 1476 1477 static final String [] MONTH_NAME = {"Jan", "Feb", "Mar", "Apr", "May", 1478 "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; 1479 1480 public static String getShortMonthName(int month) { 1481 try { 1482 return MONTH_NAME[month]; 1483 } catch (Exception e) { 1484 return ""; 1485 } 1486 } 1487 1488 public static String getShortMonthName(String month) { 1489 try { 1490 return MONTH_NAME[Integer.parseInt(month)]; 1491 } catch (Exception e) { 1492 return ""; 1493 } 1494 } 1495 1496 public static boolean isUrlLive(String url, Host host) { 1497 return isUrlLive(url, host.getInode()); 1498 } 1499 1500 public static boolean isUrlLive(String url, long hostId) { 1501 return (LiveCache.getPathFromCache(url, hostId) != null); 1502 } 1503 1504 public static boolean isUrlPreview(String url, Host host) { 1505 return isUrlPreview(url, host.getInode()); 1506 } 1507 1508 public static boolean isUrlPreview(String url, long hostId) { 1509 return (WorkingCache.getPathFromCache(url, hostId) != null); 1510 } 1511 1512 public static String stripUnicode(String x) { 1513 return (x == null) ? x : x.replaceAll("([^\000-\177áéíóúÁÉÍÓÚñÑÇç€])", 1514 " "); 1515 1516 } 1517 1518 public static String obfuscateCreditCard(String ccnum) { 1519 if (ccnum != null && ccnum.length() > 4) { 1520 ccnum = ccnum.substring(ccnum.length() - 4, ccnum.length()); 1521 ccnum = "************" + ccnum; 1522 return ccnum; 1523 } 1524 return ""; 1525 } 1526 1527 1539 public static List specialSplit(LineNumberReader reader, String delim, 1540 String textQualifier) throws IOException { 1541 ArrayList <String []> ret = new ArrayList <String []>(); 1542 String text = ""; 1543 while ((text = reader.readLine()) != null) { 1544 ArrayList <String > tokens = new ArrayList <String >(); 1545 StringTokenizer tok = new StringTokenizer (text, delim, true); 1546 boolean delimFound = false; 1547 String lastToken = ""; 1548 try { 1549 while (true) { 1550 String nt = tok.nextToken(delim); 1551 lastToken = nt; 1552 if (nt.equals(textQualifier)) { 1553 delimFound = false; 1554 continue; 1555 } 1556 if (nt.equals(",") && delimFound) { 1557 tokens.add(""); 1558 continue; 1559 } else if (nt.equals(",")) { 1560 delimFound = true; 1561 continue; 1562 } else { 1563 delimFound = false; 1564 } 1565 if (nt.trim().startsWith(textQualifier) 1566 && (!nt.trim().endsWith(textQualifier))) { 1567 boolean endFound = false; 1568 while (!endFound) { 1569 try { 1570 nt += tok.nextToken(textQualifier); 1571 if (nt.trim().endsWith("\"")) 1572 endFound = true; 1573 } catch (NoSuchElementException e) { 1574 text = reader.readLine(); 1575 if (text == null) 1576 endFound = true; 1577 tok = new StringTokenizer (text, delim, true); 1578 } 1579 } 1580 } 1581 nt = nt.trim(); 1582 if (nt.startsWith(textQualifier)) 1583 nt = nt.substring(textQualifier.length(), nt.length()); 1584 if (nt.endsWith(textQualifier)) 1585 nt = nt.substring(0, nt.length() 1586 - textQualifier.length()); 1587 nt = nt.trim(); 1588 tokens.add(nt); 1589 } 1590 } catch (NoSuchElementException e) { 1591 if (lastToken.equals(delim)) 1592 tokens.add(""); 1593 } 1594 String [] values = (String []) tokens.toArray(new String [0]); 1595 ret.add(values); 1596 } 1597 return ret; 1598 } 1599 1600 public static final String dateToLongPrettyHTMLDate(java.util.Date x) { 1601 if (x == null) { 1602 return ""; 1603 } 1604 return DATE_TO_LONG_PRETTY_HTML_DATE.format(x); 1605 } 1606 1607 public static final boolean hasValue(String selectedValues, String value) { 1608 String [] values = selectedValues.split(","); 1609 for (String val : values) { 1610 if (val.trim().equals(value)) 1611 return true; 1612 } 1613 return false; 1614 } 1615 1616 public static final String convertToNumbers(String st) { 1617 String result = ""; 1618 for (int i = 0; i < st.length(); i++) { 1619 if (Character.isDigit(st.charAt(i))) 1620 result += st.charAt(i); 1621 } 1622 return result; 1623 } 1624 1625 public static final String convertToFolderName(String st) { 1626 return st.replaceAll("\\/", "_"); 1627 } 1628 1629 public static String encodeURL(String url) { 1630 try { 1631 return URLEncoder.encode(url, "UTF-8"); 1632 } catch (Exception e) { 1633 } 1634 return ""; 1635 } 1636 1637 public static boolean revomeDir(String path) { 1638 File dir = new File (path); 1639 if (!dir.isDirectory()) { 1640 return false; 1641 } 1642 File [] children = dir.listFiles(); 1643 for (File child : children) { 1644 boolean ok = true; 1645 if (child.isDirectory()) 1646 ok = revomeDir(child.getAbsolutePath()); 1647 if (ok) 1648 ok = child.delete(); 1649 if (!ok) 1650 return ok; 1651 } 1652 1653 return dir.delete(); 1654 } 1655 1656 public static String getUserFullName(String userId) { 1658 User usr = PublicUserFactory.findUserByUserId(userId); 1659 if (usr == null) 1660 return userId; 1661 if (!isSet(usr.getFirstName()) || !isSet(usr.getLastName())) 1662 return usr.getEmailAddress(); 1663 return usr.getFullName(); 1664 } 1665 1666 public static String getUserEmailAddress(String userId) { 1667 User usr = PublicUserFactory.findUserByUserId(userId); 1668 if (usr == null) 1669 return "none"; 1670 return usr.getEmailAddress(); 1671 } 1672 1673 public static String getValidDirectoryName(String phrase) { 1674 if (phrase == null) { 1675 return null; 1676 } 1677 StringBuffer sb = new StringBuffer (); 1678 char[] chars = phrase.toCharArray(); 1679 for (int i = 0; i < chars.length; i++) { 1680 char x = chars[i]; 1681 1682 if ((x > 64 && x < 91) || (x > 96 && x < 123) || (x > 47 && x < 58)) { 1683 sb.append(x); 1684 } 1685 if (x == 32) { 1686 sb.append('_'); 1687 } 1688 1689 } 1690 return sb.toString().toLowerCase(); 1691 } 1692 1693 public static boolean isInt(String intString) { 1694 try { 1695 Integer.parseInt(intString); 1696 return true; 1697 } catch (Exception ex) { 1698 return false; 1699 } 1700 } 1701 1702 public static Date addDate(Date date, int amount, int field) { 1703 GregorianCalendar gc = new GregorianCalendar (); 1704 gc.setTime(date); 1705 gc.add(field, amount); 1706 return gc.getTime(); 1707 } 1708 1709 public static Date addDays(Date date, int amount) { 1710 int field = GregorianCalendar.DAY_OF_MONTH; 1711 GregorianCalendar gc = new GregorianCalendar (); 1712 gc.setTime(date); 1713 gc.add(field, amount); 1714 return gc.getTime(); 1715 } 1716 1717 public static String elapsedTimeToString(long milliseconds) { 1718 1719 String time = ""; 1720 1721 long seconds = milliseconds / 1000; 1722 if (seconds > 0) { 1723 String sec; 1724 sec = "" + (seconds % 60) + "s"; 1725 String min; 1726 if (seconds > 60) { 1727 min = "" + (seconds / 60 % 60) + "m"; 1728 } else { 1729 min = ""; 1730 } 1731 String hours; 1732 if (seconds / 60 > 60) { 1733 hours = "" + (seconds / 60 / 60) + "h"; 1734 } else { 1735 hours = ""; 1736 } 1737 1738 time = "" + hours + " " + min + " " + sec; 1739 1740 } else { 1741 time = "0 s"; 1742 } 1743 return time; 1744 } 1745 1746 1754 public static List <String []> specialSplit(Reader reader, char delim, 1755 char textQualifier) throws IOException { 1756 List <String []> ret = new ArrayList <String []>(); 1757 1758 List <String > lineFields = new ArrayList <String >(); 1759 StringBuffer fieldBuffer = new StringBuffer (); 1760 boolean end = false; 1761 boolean insideTextQualifiers = false; 1762 int nextRead = reader.read(); 1763 int read = -1; 1764 while (!end) { 1765 read = nextRead; 1766 nextRead = reader.read(); 1767 if (read == -1) { 1768 end = true; 1769 } 1770 if (!end) { 1771 char charRead = (char) read; 1772 char nextCharRead = (char) nextRead; 1773 if (charRead == textQualifier && nextCharRead != textQualifier 1774 && !insideTextQualifiers) 1775 insideTextQualifiers = true; 1776 else if (charRead == textQualifier 1777 && nextCharRead != textQualifier 1778 && insideTextQualifiers) { 1779 insideTextQualifiers = false; 1780 } else if (charRead == textQualifier 1781 && nextCharRead == textQualifier 1782 && insideTextQualifiers) { 1783 fieldBuffer.append(charRead); 1784 nextRead = reader.read(); 1785 } else if (!insideTextQualifiers && charRead == delim) { 1786 lineFields.add(fieldBuffer.toString()); 1787 fieldBuffer = new StringBuffer (); 1788 } else if (!insideTextQualifiers 1789 && ((charRead == '\r' && nextCharRead == '\n') || charRead == '\n')) { 1790 lineFields.add(fieldBuffer.toString()); 1791 fieldBuffer = new StringBuffer (); 1792 ret.add(lineFields.toArray(new String [0])); 1793 lineFields = new ArrayList <String >(); 1794 if (charRead == '\r') 1795 nextRead = reader.read(); 1796 } else 1797 fieldBuffer.append(charRead); 1798 1799 } else { 1800 if (lineFields.size() > 0) { 1801 ret.add(lineFields.toArray(new String [0])); 1802 } 1803 } 1804 } 1805 1806 return ret; 1807 } 1808 1809 public static Folder getParentFolder(String childPath, Host host) { 1810 Folder childFolder = FolderFactory.getFolderByPath(childPath, host); 1811 return (Folder) InodeFactory 1812 .getParentOfClass(childFolder, Folder.class); 1813 } 1814 1815 1821 public static int compareDates(Date date1, Date date2) { 1822 1823 GregorianCalendar cal1 = new GregorianCalendar (); 1824 cal1.set(GregorianCalendar.DAY_OF_MONTH, date1.getDate()); 1825 cal1.set(GregorianCalendar.MONTH, date1.getMonth()); 1826 cal1.set(GregorianCalendar.YEAR, date1.getYear()); 1827 cal1.set(GregorianCalendar.HOUR_OF_DAY, 0); 1828 cal1.set(GregorianCalendar.MINUTE, 0); 1829 cal1.set(GregorianCalendar.SECOND, 0); 1830 cal1.set(GregorianCalendar.MILLISECOND, 0); 1831 1832 GregorianCalendar cal2 = new GregorianCalendar (); 1833 cal2.set(GregorianCalendar.DAY_OF_MONTH, date2.getDate()); 1834 cal2.set(GregorianCalendar.MONTH, date2.getMonth()); 1835 cal2.set(GregorianCalendar.YEAR, date2.getYear()); 1836 cal2.set(GregorianCalendar.HOUR_OF_DAY, 0); 1837 cal2.set(GregorianCalendar.MINUTE, 0); 1838 cal2.set(GregorianCalendar.SECOND, 0); 1839 cal2.set(GregorianCalendar.MILLISECOND, 0); 1840 Logger.debug(UtilMethods.class, "cal1:" + cal1.getTime().toString() 1841 + " - cal2:" + cal2.getTime().toString()); 1842 return cal1.compareTo(cal2); 1843 } 1844 1845 1851 public static int mod(Integer x, Integer y) { 1852 1853 return x % y; 1854 } 1855 1856 public static final String dateToPrettyHTMLDate2(java.util.Date x) { 1857 if (x == null) { 1858 return ""; 1859 } 1860 1861 return DATE_TO_PRETTY_HTML_DATE_2.format(x); 1862 } 1863 1864 public static final String dateToLongHTMLDateRange(java.util.Date x, 1865 java.util.Date y) { 1866 1867 String i = dateToPrettyHTMLDate2(x); 1868 String j = dateToPrettyHTMLDate2(y); 1869 1870 if (i.equals(j)) { 1871 return i; 1872 } else { 1873 return i + " - " + j; 1874 } 1875 } 1876 1877 public static boolean isLong(String longString) { 1878 try { 1879 Long.parseLong(longString); 1880 return true; 1881 } catch (Exception ex) { 1882 return false; 1883 } 1884 } 1885 1886 public static String toPriceFormat(double price) { 1887 int decimals = 2; 1888 return toXNumberFormat(price, decimals); 1889 } 1890 1891 public static String toPriceFormat(float price) { 1892 return toPriceFormat((double) price); 1893 } 1894 1895 public static String toXNumberFormat(double number, int decimals) { 1896 try { 1897 NumberFormat nf = NumberFormat.getInstance(); 1898 nf.setMinimumFractionDigits(decimals); 1899 nf.setMaximumFractionDigits(decimals); 1900 String numberS = nf.format(number); 1901 return numberS; 1902 } catch (Exception ex) { 1903 Logger.debug(UtilMethods.class, ex.toString()); 1904 return "NAN"; 1905 } 1906 } 1907 1908 public static float getItemPriceWithDiscount(OrderItem orderItem, 1909 List <DiscountCode> discounts) { 1910 float totalDiscount = 0; 1911 for (DiscountCode discount : discounts) { 1912 if (DiscountCodeFactory._potentialDiscount(orderItem, discount)) { 1913 if (discount.getDiscountType() == 1) { 1914 totalDiscount += (discount.getDiscountAmount() / 100) 1915 * orderItem.getItemPrice(); 1916 } else { 1917 totalDiscount += discount.getDiscountAmount(); 1918 } 1919 } 1920 } 1921 return orderItem.getItemPrice() - totalDiscount; 1922 } 1923 1924 public static float getItemPriceWithDiscount(ProductFormat productFormat, 1925 float itemPrice, List <DiscountCode> discounts) { 1926 float totalDiscount = 0; 1927 for (DiscountCode discount : discounts) { 1928 if (DiscountCodeFactory._potentialDiscount(productFormat, discount)) { 1929 if (discount.getDiscountType() == 1) { 1930 totalDiscount += (discount.getDiscountAmount() / 100) 1931 * itemPrice; 1932 } else { 1933 totalDiscount += discount.getDiscountAmount(); 1934 } 1935 } 1936 } 1937 return itemPrice - totalDiscount; 1938 } 1939 1940 public static float getItemPriceWithDiscount(OrderItemForm orderItemForm, 1941 List <DiscountCode> discounts) { 1942 float totalDiscount = 0; 1943 for (DiscountCode discount : discounts) { 1944 if (DiscountCodeFactory._potentialDiscount(orderItemForm, discount)) { 1945 if (discount.getDiscountType() == 1) { 1946 totalDiscount += (discount.getDiscountAmount() / 100) 1947 * orderItemForm.getItemPrice(); 1948 } else { 1949 totalDiscount += discount.getDiscountAmount(); 1950 } 1951 } 1952 } 1953 return orderItemForm.getItemPrice() - totalDiscount; 1954 } 1955 1956 public static Product getProduct(String inode) { 1957 return (Product) ProductFactory.getProduct(inode); 1958 } 1959 1960 public static Product getProduct(long inode) { 1961 return (Product) ProductFactory.getProduct(inode); 1962 } 1963 1964 public static List <DiscountCode> getDiscountsByOrder(OrderForm orderForm) { 1965 List <DiscountCode> discounts = new ArrayList <DiscountCode>(); 1966 String discountsString = orderForm.getDiscountCodes(); 1967 if (discountsString != null) { 1968 String [] discountsStrings = discountsString.split(":"); 1969 for (String discountString : discountsStrings) { 1970 discountString = discountString.trim(); 1971 if (UtilMethods.isSet(discountString)) { 1972 DiscountCode discountCode = DiscountCodeFactory 1973 .getDiscountCodeById(discountString); 1974 discounts.add(discountCode); 1975 } 1976 } 1977 } 1978 return discounts; 1979 } 1980 1981 public static List <DiscountCode> getDiscountsByOrder(Order order) { 1982 List <DiscountCode> discounts = new ArrayList <DiscountCode>(); 1983 String discountsString = order.getDiscountCodes(); 1984 if (discountsString != null) { 1985 String [] discountsStrings = discountsString.split(":"); 1986 for (String discountString : discountsStrings) { 1987 discountString = discountString.trim(); 1988 if (UtilMethods.isSet(discountString)) { 1989 DiscountCode discountCode = DiscountCodeFactory 1990 .getDiscountCodeById(discountString); 1991 discounts.add(discountCode); 1992 } 1993 } 1994 } 1995 return discounts; 1996 } 1997 1998 public static String getShippingTypeName(int shippingType) { 1999 2000 String typeName = ""; 2001 switch (shippingType) { 2002 case 0 : 2003 typeName = "Ground"; 2004 break; 2005 case 1 : 2006 typeName = "Second Day"; 2007 break; 2008 case 2 : 2009 typeName = "Next Day"; 2010 break; 2011 2012 } 2013 2014 return typeName; 2015 } 2016 2017 public static String getPaymentTypeName(int paymentType) { 2018 2019 String typeName = ""; 2020 switch (paymentType) { 2021 case 1 : 2022 typeName = "Credit Card"; 2023 break; 2024 case 2 : 2025 typeName = "Check"; 2026 break; 2027 case 3 : 2028 typeName = "Purchase Order"; 2029 break; 2030 } 2031 return typeName; 2032 } 2033 2034 public static OrderForm loadOrderForm(HttpServletRequest request) { 2035 OrderForm orderForm = new OrderForm(); 2036 try { 2037 String orderInode = request.getParameter("orderInode"); 2038 Order order = OrderFactory.getOrderById(orderInode); 2040 orderForm.setInode(order.getInode()); 2041 orderForm.setUserInode(order.getUserInode()); 2042 orderForm.setDatePosted(order.getDatePosted()); 2043 orderForm.setLastModDate(order.getLastModDate()); 2044 orderForm.setBillingAddress1(order.getBillingAddress1()); 2046 orderForm.setBillingAddress2(order.getBillingAddress2()); 2047 orderForm.setBillingCity(order.getBillingCity()); 2048 orderForm.setBillingState(order.getBillingState()); 2049 orderForm.setBillingZip(order.getBillingZip()); 2050 orderForm.setBillingCountry(order.getBillingCountry()); 2051 orderForm.setBillingPhone(order.getBillingPhone()); 2052 orderForm.setBillingFax(order.getBillingFax()); 2053 orderForm.setBillingContactName(order.getBillingContactName()); 2054 orderForm.setBillingContactPhone(order.getBillingContactPhone()); 2055 orderForm.setBillingContactEmail(order.getBillingContactEmail()); 2056 orderForm.setShippingAddress1(order.getShippingAddress1()); 2058 orderForm.setShippingAddress2(order.getShippingAddress2()); 2059 orderForm.setShippingCity(order.getShippingCity()); 2060 2061 orderForm.setShippingState(order.getShippingState()); 2062 orderForm.setShippingZip(order.getShippingZip()); 2063 orderForm.setShippingCountry(order.getShippingCountry()); 2064 orderForm.setShippingPhone(order.getShippingPhone()); 2065 orderForm.setShippingFax(order.getShippingFax()); 2066 orderForm.setOrderTotal(order.getOrderTotal()); 2068 orderForm.setOrderShipping(order.getOrderShipping()); 2069 orderForm.setOrderTax(order.getOrderTax()); 2070 orderForm.setOrderDiscount(order.getOrderDiscount()); 2071 orderForm.setOrderSubTotal(order.getOrderSubTotal()); 2072 orderForm.setOrderSubTotalDiscount(order.getOrderSubTotal() 2073 - order.getOrderDiscount()); 2074 orderForm.setDiscountCodes(order.getDiscountCodes()); 2075 if (order.getPaymentType().trim().equals( 2076 Config.getStringProperty("ECOM_CREDIT_CARD"))) { 2077 orderForm.setCardNumber(order.getCardNumber()); 2079 orderForm.setPaymentType("cc"); 2080 } else if (order.getPaymentType().trim().equals( 2081 Config.getStringProperty("ECOM_CHECK"))) { 2082 orderForm.setCheckNumber(order.getCheckNumber()); 2084 orderForm.setCheckBankName(order.getCheckBankName()); 2085 orderForm.setPaymentType("ch"); 2086 } else if (order.getPaymentType().trim().equals( 2087 Config.getStringProperty("ECOM_PURCHASE_ORDER"))) { 2088 orderForm.setPoNumber(order.getPoNumber()); 2090 orderForm.setPaymentType("po"); 2091 } 2092 2093 List <OrderItem> orderItems = (List <OrderItem>) OrderItemFactory 2095 .getAllOrderItemsByParentOrder(order); 2096 List <OrderItemForm> orderItemsForm = new ArrayList <OrderItemForm>(); 2097 for (OrderItem orderItem : orderItems) { 2098 ProductFormat format = ProductFormatFactory 2099 .getProductFormat(orderItem.getProductInode()); 2100 OrderItemForm orderItemForm = new OrderItemForm(); 2101 orderItemForm.setInode(orderItem.getInode()); 2102 orderItemForm.setItemPrice(orderItem.getItemPrice()); 2103 orderItemForm.setItemQty(orderItem.getItemQty()); 2104 orderItemForm.setOrderInode(orderItem.getOrderInode()); 2105 orderItemForm.setProductInode(orderItem.getProductInode()); 2106 orderItemsForm.add(orderItemForm); 2107 orderItemForm.setFormatName(format.getFormat()); 2108 } 2109 orderForm.setOrderItemList(orderItemsForm); 2110 } catch (Exception ex) { 2111 Logger.debug(UtilMethods.class, ex.getMessage()); 2112 System.out.println(ex.getMessage()); 2113 } 2114 return orderForm; 2115 } 2116 2117 public static String getUserFullName(OrderForm orderForm) { 2118 String fullName = ""; 2119 try { 2120 UserProxy userProxy = UserProxyFactory.getUserProxy(orderForm 2121 .getUserInode()); 2122 User user = PublicUserFactory 2123 .getUserByUserId(userProxy.getUserId()); 2124 fullName = user.getFullName(); 2125 } catch (Exception ex) { 2126 Logger.debug(UtilMethods.class, ex.toString()); 2127 } 2128 return fullName; 2129 } 2130 2131 public static String getUserCompanyName(HttpServletRequest request, 2132 OrderForm orderForm) { 2133 String companyName = ""; 2134 if (request.getSession().getAttribute(WebKeys.CMS_USER) != null) { 2135 UserProxy userProxy = UserProxyFactory.getUserProxy(orderForm 2136 .getUserInode()); 2137 Organization organization = (Organization) InodeFactory 2138 .getParentOfClass(userProxy, Organization.class); 2139 if (organization.getInode() != 0) { 2140 companyName = organization.getTitle(); 2141 } 2142 } 2143 return companyName; 2144 } 2145 2146 public static String getUserCompanyName(HttpServletRequest request) { 2147 String companyName = ""; 2148 if (request.getSession().getAttribute(WebKeys.CMS_USER) != null) { 2149 User user = (User) request.getSession().getAttribute( 2150 WebKeys.CMS_USER); 2151 UserProxy userProxy = UserProxyFactory.getUserProxy(user); 2152 Organization organization = (Organization) InodeFactory 2153 .getParentOfClass(userProxy, Organization.class); 2154 if (organization.getInode() != 0) { 2155 companyName = organization.getTitle(); 2156 } 2157 } 2158 return companyName; 2159 } 2160 2161 public static Product getProductbyProductFormaId(String productFormatInode) { 2162 2163 ProductFormat productF = (ProductFormat) ProductFormatFactory 2164 .getProductFormat(productFormatInode); 2165 return getProductById(productF.getProductInode()); 2166 } 2167 2168 public static Product getProductbyProductFormaId(long productFormatInode) 2169 throws Exception { 2170 ProductFormat productF = (ProductFormat) ProductFormatFactory 2171 .getProductFormat(productFormatInode); 2172 return getProductById(productF.getProductInode()); 2173 } 2174 2175 public static Product getProductById(long productInode) { 2176 2177 Product product = getProduct(productInode); 2178 return product; 2179 } 2180 2181 public static String getUserEmail(User user) { 2182 String email = ""; 2183 if (user != null) { 2184 email = user.getEmailAddress(); 2185 } 2186 return email; 2187 } 2188 2189 public static String toPercentageFormat(double weight) { 2190 int decimals = 3; 2191 return toXNumberFormat(weight, decimals); 2192 } 2193 2194 public static String toPercentageFormat(float weight) { 2195 return toWeightFormat((double) weight); 2196 } 2197 public static String toWeightFormat(double weight) { 2198 int decimals = 3; 2199 return toXNumberFormat(weight, decimals); 2200 } 2201 2202 public static String toWeightFormat(float weight) { 2203 return toWeightFormat((double) weight); 2204 } 2205 2206 public static String getActualYear() { 2207 GregorianCalendar calendar = new GregorianCalendar (); 2208 return String.valueOf(calendar.get(GregorianCalendar.YEAR)); 2209 } 2210 2211 public static String getEventDateRange(Date date1, Date date2) { 2212 if (date1 == null) 2213 return ""; 2214 if (date2 == null) 2215 date2 = date1; 2216 2217 String dateRet = ""; 2218 GregorianCalendar cal = new GregorianCalendar (); 2219 GregorianCalendar cal2 = new GregorianCalendar (); 2220 cal.setTime(date1); 2221 cal2.setTime(date2); 2222 if (cal.get(GregorianCalendar.MONTH) == cal2 2223 .get(GregorianCalendar.MONTH) 2224 && cal.get(GregorianCalendar.YEAR) == cal2 2225 .get(GregorianCalendar.YEAR)) { 2226 dateRet += new SimpleDateFormat ("MMMM").format(date1) + " "; 2227 if (cal.get(GregorianCalendar.DATE) == cal2 2228 .get(GregorianCalendar.DATE)) { 2229 dateRet += cal.get(GregorianCalendar.DATE) + " "; 2230 } else { 2231 dateRet += cal.get(GregorianCalendar.DATE) + " - " 2232 + cal2.get(GregorianCalendar.DATE) + " "; 2233 } 2234 dateRet += cal.get(GregorianCalendar.YEAR); 2235 } else { 2236 if (cal.get(GregorianCalendar.YEAR) == cal2 2237 .get(GregorianCalendar.YEAR)) { 2238 dateRet += new SimpleDateFormat ("MMMM").format(date1) + " "; 2239 dateRet += cal.get(GregorianCalendar.DATE) + " - "; 2240 dateRet += new SimpleDateFormat ("MMMM").format(date2) + " "; 2241 dateRet += cal2.get(GregorianCalendar.DATE) + " "; 2242 dateRet += cal.get(GregorianCalendar.YEAR); 2243 } else { 2244 dateRet += new SimpleDateFormat ("MMMM").format(date1) + " "; 2245 dateRet += cal.get(GregorianCalendar.DATE) + " "; 2246 dateRet += cal.get(GregorianCalendar.YEAR) + " - "; 2247 dateRet += new SimpleDateFormat ("MMMM").format(date2) + " "; 2248 dateRet += cal2.get(GregorianCalendar.DATE) + " "; 2249 dateRet += cal2.get(GregorianCalendar.YEAR); 2250 } 2251 } 2252 return dateRet; 2253 } 2254 2255 public static final String htmlDateToHTMLTime(java.util.Date x) { 2256 if (x == null) { 2257 return ""; 2258 } 2259 2260 return HTML_DATETIME_TO_DATE.format(x); 2261 } 2262 2263 public static List <Object > randomList(List <Object > list) { 2264 return randomList(list, list.size()); 2265 } 2266 2267 public static List <Object > randomList(List <Object > list, int number) { 2268 List <Object > randomList = new ArrayList <Object >(); 2269 try { 2270 if (list.size() > 0) { 2271 ArrayList <Integer > numbers = new ArrayList <Integer >(); 2272 Randomizer random = new Randomizer(); 2273 for (int i = 0; i < number; i++) { 2274 int randomInt = random.nextInt(list.size()); 2275 int j = 0; 2276 while (numbers.contains(randomInt) && j < 20) { 2277 randomInt = random.nextInt(list.size()); 2278 j++; 2279 } 2280 numbers.add(randomInt); 2281 randomList.add(list.get(randomInt)); 2282 } 2283 } 2284 } catch (Exception ex) { 2285 Logger.debug(UtilMethods.class, ex.toString()); 2286 } 2287 return randomList; 2288 } 2289 2290 public String toString(Object obj) { 2291 return obj.toString(); 2292 } 2293 2294 public String toString(int num) { 2295 return Integer.toString(num); 2296 } 2297 2298 public String toString(long num) { 2299 return Long.toString(num); 2300 } 2301 2302 2308 public static String listToString(String stringList) { 2309 StringBuffer result = new StringBuffer (); 2310 StringTokenizer token = new StringTokenizer (stringList, ","); 2311 while (token.hasMoreElements()) { 2312 result.append(token.nextToken() + " "); 2313 } 2314 return result.toString(); 2315 } 2316 2317 2322 public static int getRandomNumber(int maxRange) { 2323 2324 Random r = new Random (); 2325 int randInt = Math.abs(r.nextInt()) % (maxRange + 1); 2326 return randInt; 2327 2328 } 2329 2330 2336 @SuppressWarnings ({"deprecation", "unchecked"}) 2337 public static Template getVelocityTemplate(String liveUrl) { 2338 2339 try { 2340 try { 2341 URL url = Thread.currentThread().getContextClassLoader() 2342 .getResource("system-ext.properties"); 2343 Velocity.init(url.getPath()); 2344 2345 } catch (Exception s) { 2346 Logger.warn(UtilMethods.class, s.toString(), s); 2347 } 2348 2349 Template template = Velocity.getTemplate(liveUrl); 2350 return template; 2351 2352 } catch (Exception e) { 2353 2354 @SuppressWarnings ("unused") 2355 String idStr = liveUrl.substring(liveUrl.indexOf("/") + 1, liveUrl 2356 .indexOf(".")); 2357 long idInode = Long.parseLong(idStr); 2358 HTMLPage htmlPage = (HTMLPage) IdentifierFactory 2359 .getLiveChildOfClass(InodeFactory.getInode(idInode, 2360 Identifier.class), HTMLPage.class); 2361 2362 republishHTMLPage(htmlPage); 2363 2364 return getVelocityTemplate(liveUrl); 2365 } 2366 2367 } 2368 2369 2373 public static void republishHTMLPage(HTMLPage htmlPage) { 2374 2375 com.dotmarketing.portlets.templates.model.Template templateParent = HTMLPageFactory 2376 .getHTMLPageTemplate(htmlPage, true); 2377 2378 if (templateParent.getInode() > 0) { 2379 2380 WebAssetFactory.publishAsset(templateParent); 2382 2383 java.util.List identifiers = InodeFactory.getChildrenClass( 2385 templateParent, Identifier.class); 2386 java.util.Iterator identifiersIter = identifiers.iterator(); 2387 while (identifiersIter.hasNext()) { 2388 2389 Identifier identifier = (Identifier) identifiersIter.next(); 2390 Container container = (Container) IdentifierFactory 2391 .getWorkingChildOfClass(identifier, Container.class); 2392 2393 List categories = InodeFactory.getParentsOfClass(container, 2394 Category.class); 2395 List contentlets = null; 2396 2397 if (categories.size() == 0) { 2398 Identifier idenHtmlPage = IdentifierFactory 2399 .getIdentifierByInode(htmlPage); 2400 Identifier idenContainer = IdentifierFactory 2401 .getIdentifierByInode(container); 2402 contentlets = ContentletFactory 2403 .getWorkingContentletsByOrderAndParents( 2404 idenHtmlPage.getInode(), idenContainer 2405 .getInode()); 2406 } else { 2407 2408 Iterator catsIter = categories.iterator(); 2409 Set contentletSet = new HashSet (); 2410 2411 String condition = "working=" 2412 + com.dotmarketing.db.DbConnectionFactory 2413 .getDBTrue() 2414 + " and deleted=" 2415 + com.dotmarketing.db.DbConnectionFactory 2416 .getDBFalse(); 2417 String sort = (container.getSortContentletsBy() == null) 2418 ? "sort_order" 2419 : container.getSortContentletsBy(); 2420 2421 while (catsIter.hasNext()) { 2422 Category category = (Category) catsIter.next(); 2423 List contentletsChildren = InodeFactory 2424 .getChildrenClassByConditionAndOrderBy( 2425 category, Contentlet.class, condition, 2426 sort); 2427 if (contentletsChildren != null 2428 && contentletsChildren.size() > 0) { 2429 contentletSet.addAll(contentletsChildren); 2430 } 2431 } 2432 contentlets = new ArrayList (); 2433 contentlets.addAll(contentletSet); 2434 } 2435 java.util.Iterator contentletsIter = contentlets.iterator(); 2437 while (contentletsIter.hasNext()) { 2438 Contentlet contentlet = (Contentlet) contentletsIter.next(); 2440 WebAssetFactory.publishAsset(contentlet); 2441 } 2442 } 2443 2444 } 2445 2446 LiveCache.addToLiveAssetToCache((WebAsset) htmlPage); 2447 WorkingCache.addToWorkingAssetToCache((WebAsset) htmlPage); 2448 PageServices.publishPageToFile(htmlPage); 2450 2451 RefreshMenus.deleteMenus(); 2453 2454 PageNotFoundCache.removePageFromCache(htmlPage); 2457 2458 } 2459 2460 2465 public static Date getCurrentDate(){ 2466 2467 try{ 2468 GregorianCalendar cal = new GregorianCalendar (); 2469 return cal.getTime(); 2470 2471 }catch(Exception e){ 2472 2473 } 2474 return null; 2475 } 2476 2477 public static String truncFull(String x, int len) 2478 { 2479 len -= 3; 2480 if (x.length() >= len) 2481 { 2482 x = x.substring(0,len); 2483 x += "..."; 2484 } 2485 return x; 2486 } 2487 2488} | Popular Tags |