AbstractJcrCommerceSession.java 56.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  aQute.bnd.annotation.ConsumerType
 *  com.adobe.granite.security.user.UserProperties
 *  com.adobe.granite.security.user.UserPropertiesManager
 *  com.adobe.granite.security.user.UserPropertiesService
 *  com.day.cq.commons.Language
 *  com.day.cq.commons.jcr.JcrUtil
 *  com.day.cq.i18n.I18n
 *  com.day.cq.personalization.ContextSessionPersistence
 *  com.day.cq.personalization.UserPropertiesUtil
 *  com.day.cq.wcm.api.LanguageManager
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Workspace
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  javax.servlet.http.Cookie
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.collections.CollectionUtils
 *  org.apache.commons.collections.Predicate
 *  org.apache.commons.lang.StringUtils
 *  org.apache.jackrabbit.api.JackrabbitSession
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.jackrabbit.api.security.user.UserManager
 *  org.apache.jackrabbit.util.ISO9075
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper
 *  org.apache.sling.api.wrappers.ValueMapDecorator
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.commerce.common;

import aQute.bnd.annotation.ConsumerType;
import com.adobe.cq.commerce.api.CommerceException;
import com.adobe.cq.commerce.api.CommerceSession;
import com.adobe.cq.commerce.api.CommerceSort;
import com.adobe.cq.commerce.api.PaginationInfo;
import com.adobe.cq.commerce.api.PaymentMethod;
import com.adobe.cq.commerce.api.PlacedOrder;
import com.adobe.cq.commerce.api.PlacedOrderResult;
import com.adobe.cq.commerce.api.PriceInfo;
import com.adobe.cq.commerce.api.Product;
import com.adobe.cq.commerce.api.ShippingMethod;
import com.adobe.cq.commerce.api.promotion.Promotion;
import com.adobe.cq.commerce.api.promotion.PromotionHandler;
import com.adobe.cq.commerce.api.promotion.PromotionInfo;
import com.adobe.cq.commerce.api.promotion.PromotionManager;
import com.adobe.cq.commerce.api.promotion.Voucher;
import com.adobe.cq.commerce.api.promotion.VoucherInfo;
import com.adobe.cq.commerce.api.smartlist.SmartListManager;
import com.adobe.cq.commerce.common.AbstractJcrCommerceService;
import com.adobe.cq.commerce.common.DefaultJcrCartEntry;
import com.adobe.cq.commerce.common.DefaultJcrPlacedOrder;
import com.adobe.cq.commerce.common.PriceFilter;
import com.adobe.cq.commerce.common.ServiceContext;
import com.adobe.cq.commerce.common.promotion.AbstractJcrVoucher;
import com.adobe.cq.commerce.impl.promotion.JcrPromotionImpl;
import com.adobe.cq.commerce.impl.promotion.JcrVoucherImpl;
import com.adobe.granite.security.user.UserProperties;
import com.adobe.granite.security.user.UserPropertiesManager;
import com.adobe.granite.security.user.UserPropertiesService;
import com.day.cq.commons.Language;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.i18n.I18n;
import com.day.cq.personalization.ContextSessionPersistence;
import com.day.cq.personalization.UserPropertiesUtil;
import com.day.cq.wcm.api.LanguageManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.util.ISO9075;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.apache.sling.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ConsumerType
public class AbstractJcrCommerceSession
implements CommerceSession {
    protected static final Logger log = LoggerFactory.getLogger(AbstractJcrCommerceSession.class);
    protected SlingHttpServletRequest request;
    protected SlingHttpServletResponse response;
    protected Resource resource;
    protected ResourceResolver resolver;
    protected AbstractJcrCommerceService commerceService;
    protected Locale locale = Locale.US;
    protected Locale userLocale = null;
    protected String PN_UNIT_PRICE = "price";
    protected String PN_ORDER_ID = "orderId";
    protected RoundingMode roundingMode = RoundingMode.HALF_UP;
    protected BigDecimal PRODUCT_TAX_RATE = new BigDecimal("0.06");
    protected BigDecimal SHIPPING_TAX_RATE = BigDecimal.ZERO;
    private String orderId;
    protected static final int COOKIE_SIZE_LIMIT = 4050;
    protected static final String PN_COMMERCE_PERSISTENCE_OVERFLOW = "cpo";
    protected static final String ORDERS_BASE_PATH = "/etc/commerce/orders/";
    protected static final String ORDERS_PATH_DATE_TEMPLATE = "yyyy/MM/dd";
    protected static final String ORDER_NAME = "order";
    protected static final String USER_ORDERS_PATH = "/commerce/orders/";
    protected static final String USER_ORDERS_DATE_TEMPLATE = "'order'-yyyy-MMM-dd";
    protected List<CommerceSession.CartEntry> cart = new ArrayList<CommerceSession.CartEntry>();
    protected List<Voucher> vouchers = new ArrayList<Voucher>();
    protected List<Promotion> promotions = new ArrayList<Promotion>();
    protected Map<String, String> orderDetails = new HashMap<String, String>();
    protected List<PriceInfo> prices;
    @Deprecated
    protected NumberFormat formatter = NumberFormat.getCurrencyInstance(this.locale);

    public AbstractJcrCommerceSession(AbstractJcrCommerceService commerceService, SlingHttpServletRequest request, SlingHttpServletResponse response, Resource resource) throws CommerceException {
        this.request = request;
        this.response = response;
        this.resource = resource;
        this.resolver = resource.getResourceResolver();
        this.commerceService = commerceService;
        Language lang = commerceService.serviceContext().languageManager.getCqLanguage(resource);
        if (lang != null && lang.getLocale().getCountry().length() > 0) {
            this.locale = lang.getLocale();
            this.loadCart();
        } else {
            Resource firstProductPage;
            this.loadCart();
            if (resource.getPath().startsWith("/content")) {
                log.debug("Unable to extract locale from page {}, falling back to default locale {}.", (Object)resource.getPath(), (Object)this.locale);
            } else if (this.cart.size() > 0 && (firstProductPage = this.resolver.getResource(this.cart.get(0).getProduct().getPagePath())) != null && (lang = commerceService.serviceContext().languageManager.getCqLanguage(firstProductPage)) != null && lang.getLocale().getCountry().length() > 0) {
                this.locale = lang.getLocale();
                this.calcOrder();
            }
        }
    }

    AbstractJcrCommerceSession(ResourceResolver resolver) {
        this.resolver = resolver;
    }

    private void loadProduct(String productPath, String quantityString, Map<String, Object> otherProperties) {
        try {
            Product product = this.commerceService.getProduct(productPath);
            if (product == null) {
                throw new CommerceException("product not found");
            }
            int quantity = 0;
            try {
                quantity = Integer.parseInt(quantityString);
            }
            catch (NumberFormatException e) {
                throw new CommerceException("quantity not a number");
            }
            if (quantity > 0) {
                this.doAddCartEntry(product, quantity, otherProperties);
            }
        }
        catch (CommerceException e) {
            log.error("Unable to load product from cookie: " + productPath + "; qty: " + quantityString, (Throwable)e);
        }
    }

    private void loadVoucher(String voucherPath) {
        try {
            Resource voucher = this.resolver.getResource(voucherPath);
            if (voucher == null) {
                throw new CommerceException("voucher not found");
            }
            this.vouchers.add(new JcrVoucherImpl(voucher));
        }
        catch (CommerceException e) {
            log.error("Unable to load voucher from cookie: " + voucherPath, (Throwable)e);
        }
    }

    private void loadPromotion(String promotionPath) {
        try {
            Resource promotion = this.resolver.getResource(promotionPath);
            if (promotion == null) {
                throw new CommerceException("promotion not found");
            }
            this.promotions.add(new JcrPromotionImpl(promotion));
        }
        catch (CommerceException e) {
            log.error("Unable to load promotion from cookie: " + promotionPath);
            log.debug("Promotion not loaded", (Throwable)e);
        }
    }

    protected void loadCart() throws CommerceException {
        String promotionCountString;
        String voucherCountString;
        Map cartStore = ContextSessionPersistence.getStore((SlingHttpServletRequest)this.request, (String)"CART", (String)"CommercePersistence");
        String entryCountString = (String)cartStore.get("entryCount");
        if (entryCountString != null && entryCountString.length() > 0) {
            int entryCount = Integer.parseInt(entryCountString);
            for (int i = 0; i < entryCount; ++i) {
                String product = (String)cartStore.get("product" + i);
                String quantity = (String)cartStore.get("quantity" + i);
                HashMap<String, Object> properties = new HashMap<String, Object>();
                String suffix = "_" + i;
                for (Map.Entry entry : cartStore.entrySet()) {
                    String name = (String)entry.getKey();
                    if (!name.endsWith(suffix)) continue;
                    name = name.substring(0, name.length() - suffix.length());
                    properties.put(name, entry.getValue());
                }
                this.loadProduct(product, quantity, properties);
            }
        }
        if ((voucherCountString = (String)cartStore.get("voucherCount")) != null && voucherCountString.length() > 0) {
            int voucherCount = Integer.parseInt(voucherCountString);
            for (int i = 0; i < voucherCount; ++i) {
                String voucher = (String)cartStore.get("voucher" + i);
                this.loadVoucher(voucher);
            }
        }
        if ((promotionCountString = (String)cartStore.get("promotionCount")) != null && promotionCountString.length() > 0) {
            int promotionCount = Integer.parseInt(promotionCountString);
            for (int i = 0; i < promotionCount; ++i) {
                String promotion = (String)cartStore.get("promotion" + i);
                this.loadPromotion(promotion);
            }
        }
        this.orderDetails = ContextSessionPersistence.getStore((SlingHttpServletRequest)this.request, (String)"ORDER", (String)"CommercePersistence");
        if (this.orderDetails.get(this.PN_ORDER_ID) == null) {
            this.orderDetails.put(this.PN_ORDER_ID, UUID.randomUUID().toString());
        }
        this.calcOrder();
    }

    protected void saveCart() throws CommerceException {
        int i;
        HashMap<String, String> cartStore = new HashMap<String, String>();
        for (CommerceSession.CartEntry entry : this.cart) {
            int entryIndex = entry.getEntryIndex();
            cartStore.put("product" + entryIndex, entry.getProduct().getPath());
            cartStore.put("quantity" + entryIndex, "" + entry.getQuantity());
            ValueMap properties = ((DefaultJcrCartEntry)entry).getProperties();
            for (Map.Entry property : properties.entrySet()) {
                String name = (String)property.getKey();
                String value = String.valueOf(property.getValue());
                if (value == null) continue;
                cartStore.put(name + "_" + entryIndex, value);
            }
        }
        cartStore.put("entryCount", "" + this.getCartEntryCount());
        for (i = 0; i < this.vouchers.size(); ++i) {
            cartStore.put("voucher" + i, this.vouchers.get(i).getPath());
        }
        cartStore.put("voucherCount", String.valueOf(this.vouchers.size()));
        for (i = 0; i < this.promotions.size(); ++i) {
            cartStore.put("promotion" + i, this.promotions.get(i).getPath());
        }
        cartStore.put("promotionCount", String.valueOf(this.promotions.size()));
        HashMap<String, Map<String, String>> stores = new HashMap<String, Map<String, String>>();
        stores.put("CART", cartStore);
        stores.put("ORDER", this.orderDetails);
        this.saveCommerceCookie(stores);
    }

    private void saveCommerceCookie(Map<String, Map<String, String>> stores) {
        String cpl_param;
        class MySlingHttpServletResponseWrapper
        extends SlingHttpServletResponseWrapper {
            private final List<Cookie> cookies;

            MySlingHttpServletResponseWrapper(SlingHttpServletResponse wrappedResponse) {
                super(wrappedResponse);
                this.cookies = new ArrayList<Cookie>();
            }

            public void addCookie(Cookie cookie) {
                super.addCookie(cookie);
                if (cookie != null) {
                    this.cookies.add(cookie);
                }
            }
        }
        Cookie commercePersistence = this.request.getCookie("CommercePersistence");
        String oldValue = commercePersistence == null ? null : commercePersistence.getValue();
        MySlingHttpServletResponseWrapper responseWrapper = new MySlingHttpServletResponseWrapper(this.response);
        ContextSessionPersistence.putStores((SlingHttpServletRequest)this.request, (SlingHttpServletResponse)responseWrapper, stores, (String)"CommercePersistence");
        boolean isCpoSet = false;
        for (Cookie cookie : responseWrapper.cookies) {
            String value;
            if (!"CommercePersistence".equals(cookie.getName()) || (value = cookie.getValue()) == null || value.length() <= 4050) continue;
            if (oldValue != null) {
                cookie.setValue(oldValue);
            } else {
                cookie.setValue("");
            }
            ContextSessionPersistence.put((SlingHttpServletRequest)this.request, (SlingHttpServletResponse)this.response, (String)"cpo", (String)"cpo");
            isCpoSet = true;
            break;
        }
        if (!isCpoSet && (cpl_param = ContextSessionPersistence.get((SlingHttpServletRequest)this.request, (String)"cpo")) != null && cpl_param.trim().length() > 0) {
            ContextSessionPersistence.put((SlingHttpServletRequest)this.request, (SlingHttpServletResponse)this.response, (String)"cpo", (String)"");
        }
    }

    public static boolean hasCookieOverflow(SlingHttpServletRequest request, SlingHttpServletResponse response) {
        boolean error;
        String cpl_param = ContextSessionPersistence.get((SlingHttpServletRequest)request, (String)"cpo");
        boolean bl = error = cpl_param != null && "cpo".equals(cpl_param.trim());
        if (error) {
            ContextSessionPersistence.put((SlingHttpServletRequest)request, (SlingHttpServletResponse)response, (String)"cpo", (String)"");
        }
        return error;
    }

    @Override
    public void logout() throws CommerceException {
    }

    protected Locale getLocale() {
        return this.userLocale != null ? this.userLocale : this.locale;
    }

    @Override
    public void setUserLocale(Locale locale) {
        this.userLocale = locale;
        try {
            this.calcOrder();
        }
        catch (CommerceException e) {
            log.error("Could not recalculate order: ", (Throwable)e);
        }
    }

    @Override
    public Locale getUserLocale() {
        return this.userLocale;
    }

    @Override
    public List<String> getAvailableCountries() throws CommerceException {
        return this.commerceService.getCountries();
    }

    @Override
    public List<ShippingMethod> getAvailableShippingMethods() throws CommerceException {
        return this.commerceService.getAvailableShippingMethods();
    }

    @Override
    public List<PaymentMethod> getAvailablePaymentMethods() throws CommerceException {
        return this.commerceService.getAvailablePaymentMethods();
    }

    @Override
    public List<PriceInfo> getProductPriceInfo(Product product) throws CommerceException {
        return this.getProductPriceInfo(product, null);
    }

    @Override
    public List<PriceInfo> getProductPriceInfo(Product product, Predicate filter) throws CommerceException {
        ArrayList<PriceInfo> prices = new ArrayList<PriceInfo>();
        BigDecimal preTax = product.getProperty(this.PN_UNIT_PRICE, BigDecimal.class);
        if (preTax == null) {
            preTax = BigDecimal.ZERO;
        }
        BigDecimal tax = preTax.multiply(this.PRODUCT_TAX_RATE);
        String currencyCode = Currency.getInstance(this.getLocale()).getCurrencyCode();
        PriceInfo price = new PriceInfo(preTax, this.getLocale());
        price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("UNIT", "PRE_TAX", currencyCode)));
        prices.add(price);
        price = new PriceInfo(tax, this.getLocale());
        price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("UNIT", "TAX", currencyCode)));
        prices.add(price);
        price = new PriceInfo(preTax.add(tax), this.getLocale());
        price.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(Arrays.asList("UNIT", "POST_TAX", currencyCode)));
        prices.add(price);
        CollectionUtils.filter(prices, (Predicate)filter);
        return prices;
    }

    @Override
    public String getProductPrice(Product product) throws CommerceException {
        return this.getProductPrice(product, null);
    }

    @Override
    public String getProductPrice(Product product, Predicate filter) throws CommerceException {
        List<PriceInfo> prices = this.getProductPriceInfo(product, filter);
        return prices.size() > 0 ? prices.get(0).getFormattedString() : null;
    }

    @Override
    public int getCartEntryCount() {
        return this.cart.size();
    }

    @Override
    public List<CommerceSession.CartEntry> getCartEntries() {
        return this.cart;
    }

    @Override
    public List<PriceInfo> getCartPriceInfo(Predicate filter) {
        if (filter != null) {
            ArrayList<PriceInfo> filteredPrices = new ArrayList<PriceInfo>();
            CollectionUtils.select(this.prices, (Predicate)filter, filteredPrices);
            return filteredPrices;
        }
        return this.prices;
    }

    @Override
    public String getCartPrice(Predicate filter) throws CommerceException {
        List<PriceInfo> prices = this.getCartPriceInfo(filter);
        return prices.isEmpty() ? "" : prices.get(0).getFormattedString();
    }

    @Override
    public void addCartEntry(Product product, int quantity) throws CommerceException {
        this.addCartEntry(product, quantity, null);
    }

    @Override
    public void addCartEntry(Product product, int quantity, Map<String, Object> properties) throws CommerceException {
        this.doAddCartEntry(product, quantity, properties);
        this.calcCart();
        this.saveCart();
    }

    protected void doAddCartEntry(Product product, int quantity, Map<String, Object> properties) throws CommerceException {
        for (CommerceSession.CartEntry existingEntry : this.cart) {
            DefaultJcrCartEntry existingEntryImpl = (DefaultJcrCartEntry)existingEntry;
            if (!existingEntryImpl.getProduct().getPath().equals(product.getPath())) continue;
            existingEntryImpl.setQuantity(existingEntryImpl.getQuantity() + quantity);
            existingEntryImpl.updateProperties(properties);
            this.calcEntry(existingEntryImpl.getEntryIndex());
            return;
        }
        DefaultJcrCartEntry newEntry = this.commerceService.newCartEntryImpl(this.cart.size(), product, quantity);
        newEntry.updateProperties(properties);
        this.cart.add(newEntry);
        this.doCalcEntry(newEntry, null, this.getLocale());
    }

    @Override
    public void modifyCartEntry(int entryNumber, int quantity) throws CommerceException {
        this.doModifyCartEntry(entryNumber, quantity, null);
    }

    @Override
    public void modifyCartEntry(int entryNumber, Map<String, Object> delta) throws CommerceException {
        this.doModifyCartEntry(entryNumber, null, delta);
        this.calcCart();
        this.saveCart();
    }

    protected void doModifyCartEntry(int entryNumber, Integer quantity, Map<String, Object> delta) throws CommerceException {
        if (entryNumber < this.cart.size()) {
            DefaultJcrCartEntry entry = (DefaultJcrCartEntry)this.cart.get(entryNumber);
            if (quantity != null) {
                entry.setQuantity(quantity);
            }
            entry.updateProperties(delta);
            this.calcEntry(entryNumber);
        }
    }

    @Override
    public void deleteCartEntry(int entryNumber) throws CommerceException {
        if (entryNumber < this.cart.size()) {
            this.cart.remove(entryNumber);
        }
        for (int i = 0; i < this.cart.size(); ++i) {
            DefaultJcrCartEntry entry = (DefaultJcrCartEntry)this.cart.get(i);
            entry.setEntryIndex(i);
        }
        this.calcCart();
        this.saveCart();
    }

    public void calcEntry(int index) throws CommerceException {
        this.doCalcEntry((DefaultJcrCartEntry)this.cart.get(index), null, this.getLocale());
    }

    protected void doCalcEntry(DefaultJcrCartEntry entry, BigDecimal discount, Locale locale) throws CommerceException {
        BigDecimal totalPrice;
        BigDecimal preTaxPrice;
        BigDecimal tax;
        BigDecimal unitPrice = entry.getProduct().getProperty(this.PN_UNIT_PRICE, BigDecimal.class);
        if (unitPrice == null) {
            unitPrice = BigDecimal.ZERO;
            preTaxPrice = BigDecimal.ZERO;
            tax = BigDecimal.ZERO;
            totalPrice = BigDecimal.ZERO;
        } else {
            preTaxPrice = unitPrice.multiply(new BigDecimal(entry.getQuantity()));
            if (discount != null) {
                preTaxPrice = preTaxPrice.subtract(discount);
            }
            tax = preTaxPrice.multiply(this.PRODUCT_TAX_RATE).setScale(2, this.roundingMode);
            totalPrice = preTaxPrice.add(tax);
        }
        entry.setPrice(new PriceInfo(preTaxPrice, locale), "LINE", "PRE_TAX");
        entry.setPrice(new PriceInfo(tax, locale), "LINE", "TAX");
        entry.setPrice(new PriceInfo(totalPrice, locale), "LINE", "POST_TAX");
        entry.setPrice(new PriceInfo(unitPrice, locale), "UNIT", "PRE_TAX");
    }

    protected /* varargs */ void setPrice(PriceInfo priceInfo, String ... types) {
        if (this.prices == null) {
            this.prices = new ArrayList<PriceInfo>();
        }
        ArrayList<String> typeList = new ArrayList<String>(Arrays.asList(types));
        typeList.add(priceInfo.getCurrency().getCurrencyCode());
        int index = this.prices.size();
        for (int i = 0; i < this.prices.size(); ++i) {
            PriceInfo price = this.prices.get(i);
            Set priceTypes = (Set)price.get((Object)"com.adobe.cq.commerce.common.PriceFilter.types");
            if (!CollectionUtils.isEqualCollection((Collection)priceTypes, typeList)) continue;
            index = i;
            break;
        }
        priceInfo.put("com.adobe.cq.commerce.common.PriceFilter.types", new HashSet<String>(typeList));
        if (index == this.prices.size()) {
            this.prices.add(priceInfo);
        } else {
            this.prices.set(index, priceInfo);
        }
    }

    protected void calcCart() {
        String currencyCode = Currency.getInstance(this.getLocale()).getCurrencyCode();
        BigDecimal cartPreTaxPrice = BigDecimal.ZERO;
        BigDecimal cartTax = BigDecimal.ZERO;
        BigDecimal cartTotalPrice = BigDecimal.ZERO;
        BigDecimal cartDiscount = BigDecimal.ZERO;
        List<Promotion> promotions = this.getActivePromotions();
        try {
            for (CommerceSession.CartEntry cartEntry : this.cart) {
                this.doCalcEntry((DefaultJcrCartEntry)cartEntry, null, this.getLocale());
                BigDecimal entryDiscount = BigDecimal.ZERO;
                for (Promotion p : promotions) {
                    try {
                        PromotionHandler ph = (PromotionHandler)p.adaptTo(PromotionHandler.class);
                        PriceInfo discount = ph.applyCartEntryPromotion(this, p, cartEntry);
                        if (discount == null || discount.getAmount().compareTo(BigDecimal.ZERO) <= 0) continue;
                        entryDiscount = entryDiscount.add(discount.getAmount());
                    }
                    catch (Exception e) {
                        log.error("Applying cart line item promotion failed: ", (Throwable)e);
                    }
                }
                this.doCalcEntry((DefaultJcrCartEntry)cartEntry, entryDiscount, this.getLocale());
                cartDiscount = cartDiscount.add(entryDiscount);
                cartPreTaxPrice = cartPreTaxPrice.add(cartEntry.getPriceInfo(new PriceFilter("PRE_TAX", currencyCode)).get(0).getAmount());
                cartTax = cartTax.add(cartEntry.getPriceInfo(new PriceFilter("TAX", currencyCode)).get(0).getAmount());
                cartTotalPrice = cartTotalPrice.add(cartEntry.getPriceInfo(new PriceFilter("POST_TAX", currencyCode)).get(0).getAmount());
            }
            this.setPrice(new PriceInfo(cartPreTaxPrice, this.getLocale()), "CART", "PRE_TAX");
            this.setPrice(new PriceInfo(cartTax, this.getLocale()), "CART", "TAX");
            this.setPrice(new PriceInfo(cartTotalPrice, this.getLocale()), "CART", "POST_TAX");
            this.setPrice(new PriceInfo(cartDiscount, this.getLocale()), "DISCOUNT", "PRODUCTS");
        }
        catch (CommerceException e) {
            log.error("Calculating cart failed: ", (Throwable)e);
        }
    }

    public List<Promotion> getActivePromotions() {
        ArrayList<Promotion> activePromotions = new ArrayList<Promotion>(this.promotions.size());
        for (Promotion promotion : this.promotions) {
            if (!promotion.isValid()) continue;
            activePromotions.add(promotion);
        }
        for (Voucher voucher : this.vouchers) {
            Promotion promotion2;
            if (!voucher.isValid(this.request)) continue;
            String path = (String)voucher.getConfig().get("promotion", String.class);
            Resource resource = path == null ? null : this.resolver.getResource(path);
            Promotion promotion3 = promotion2 = resource == null ? null : (Promotion)resource.adaptTo(Promotion.class);
            if (promotion2 == null || !promotion2.isValid()) {
                log.error("Cart contains voucher with invalid promotion: " + voucher.getPath());
                continue;
            }
            activePromotions.add(promotion2);
        }
        Collections.sort(activePromotions, new Comparator<Promotion>(){

            @Override
            public int compare(Promotion p1, Promotion p2) {
                return Long.valueOf(p2.getPriority()).compareTo(p1.getPriority());
            }
        });
        return activePromotions;
    }

    @Override
    public boolean supportsClientsidePromotionResolution() {
        return true;
    }

    @Override
    public void addPromotion(String path) throws CommerceException {
        Promotion p = this.commerceService.getPromotion(path);
        if (p == null) {
            throw new CommerceException("Invalid promotion: " + path);
        }
        this.promotions.add(p);
        this.calcCart();
        this.saveCart();
    }

    @Override
    public void removePromotion(String path) throws CommerceException {
        for (int i = 0; i < this.promotions.size(); ++i) {
            if (!this.promotions.get(i).getPath().equals(path)) continue;
            this.promotions.remove(i--);
        }
        this.calcCart();
        this.saveCart();
    }

    @Override
    public List<PromotionInfo> getPromotions() throws CommerceException {
        ArrayList<PromotionInfo> promotionInfos = new ArrayList<PromotionInfo>(0);
        for (Promotion p : this.promotions) {
            String description = null;
            Map<Integer, String> messages = null;
            PromotionHandler handler = (PromotionHandler)p.adaptTo(PromotionHandler.class);
            if (handler != null) {
                description = handler.getDescription(this.request, this, p);
                messages = handler.getMessages(this.request, this, p);
            }
            if (description == null || description.length() == 0) {
                description = p.getDescription();
            }
            if (messages != null) {
                for (Map.Entry message : messages.entrySet()) {
                    Integer key = (Integer)message.getKey();
                    if (key == -1) continue;
                    promotionInfos.add(new PromotionInfo(p.getPath(), p.getTitle(), PromotionInfo.PromotionStatus.FIRED, null, (String)message.getValue(), key));
                }
            }
            promotionInfos.add(new PromotionInfo(p.getPath(), p.getTitle(), PromotionInfo.PromotionStatus.FIRED, description, messages != null ? messages.get(-1) : null, null));
        }
        return promotionInfos;
    }

    protected BigDecimal getShipping(String method) {
        throw new UnsupportedOperationException();
    }

    protected void calcOrder() throws CommerceException {
        BigDecimal orderShipping;
        this.calcCart();
        String currencyCode = Currency.getInstance(this.getLocale()).getCurrencyCode();
        PriceInfo cartTax = this.getCartPriceInfo(new PriceFilter("TAX", currencyCode)).get(0);
        PriceInfo cartPreTaxPrice = this.getCartPriceInfo(null).get(0);
        BigDecimal orderSubTotal = cartPreTaxPrice.getAmount();
        try {
            String shippingMethod = this.orderDetails.get("shipping-option");
            orderShipping = this.getShipping(shippingMethod);
        }
        catch (Exception e) {
            log.error("Shipping calculation failed", (Throwable)e);
            orderShipping = BigDecimal.ZERO;
        }
        BigDecimal orderShippingTax = orderShipping.multiply(this.SHIPPING_TAX_RATE).setScale(2, this.roundingMode);
        BigDecimal orderTotalTax = cartTax.getAmount().add(orderShippingTax);
        BigDecimal orderTotalPrice = orderSubTotal.add(orderTotalTax.add(orderShipping));
        this.setPrice(new PriceInfo(orderShipping, this.getLocale()), "SHIPPING", "PRE_TAX");
        this.setPrice(new PriceInfo(orderShippingTax, this.getLocale()), "SHIPPING", "TAX");
        this.setPrice(new PriceInfo(orderShipping.add(orderShippingTax), this.getLocale()), "SHIPPING", "POST_TAX");
        this.setPrice(new PriceInfo(orderShipping, this.getLocale()), "SHIPPING", "PRE_PROMO");
        this.setPrice(new PriceInfo(orderTotalPrice, this.getLocale()), "ORDER", "TOTAL");
        this.setPrice(new PriceInfo(orderSubTotal, this.getLocale()), "ORDER", "SUB_TOTAL");
        this.setPrice(new PriceInfo(orderTotalTax, this.getLocale()), "ORDER", "TAX");
        BigDecimal orderDiscount = BigDecimal.ZERO;
        List<Promotion> promotions = this.getActivePromotions();
        for (Promotion p : promotions) {
            try {
                PromotionHandler ph = (PromotionHandler)p.adaptTo(PromotionHandler.class);
                PriceInfo discount = ph.applyOrderPromotion(this, p);
                if (discount == null || discount.getAmount().compareTo(BigDecimal.ZERO) <= 0) continue;
                orderSubTotal = orderSubTotal.subtract(discount.getAmount());
                orderDiscount = orderDiscount.add(discount.getAmount());
                break;
            }
            catch (Exception e) {
                log.error("Applying order-level promotion failed: ", (Throwable)e);
                continue;
            }
        }
        BigDecimal shippingDiscount = BigDecimal.ZERO;
        for (Promotion p2 : promotions) {
            try {
                PromotionHandler ph = (PromotionHandler)p2.adaptTo(PromotionHandler.class);
                PriceInfo discount = ph.applyShippingPromotion(this, p2);
                if (discount == null || discount.getAmount().compareTo(BigDecimal.ZERO) <= 0) continue;
                orderShipping = orderShipping.subtract(discount.getAmount());
                shippingDiscount = shippingDiscount.add(discount.getAmount());
                break;
            }
            catch (Exception e) {
                log.error("Applying shipping promotion failed: ", (Throwable)e);
                continue;
            }
        }
        PriceInfo productDiscount = this.getCartPriceInfo(new PriceFilter("DISCOUNT", "PRODUCTS", currencyCode)).get(0);
        BigDecimal totalDiscount = orderDiscount.add(shippingDiscount).add(productDiscount.getAmount());
        orderShippingTax = orderShipping.multiply(this.SHIPPING_TAX_RATE).setScale(2, this.roundingMode);
        orderTotalTax = cartTax.getAmount().add(orderShippingTax);
        orderTotalPrice = orderSubTotal.add(orderTotalTax.add(orderShipping));
        this.setPrice(new PriceInfo(orderShipping, this.getLocale()), "SHIPPING", "PRE_TAX");
        this.setPrice(new PriceInfo(orderShippingTax, this.getLocale()), "SHIPPING", "TAX");
        this.setPrice(new PriceInfo(orderShipping.add(orderShippingTax), this.getLocale()), "SHIPPING", "POST_TAX");
        this.setPrice(new PriceInfo(orderTotalPrice, this.getLocale()), "ORDER", "TOTAL");
        this.setPrice(new PriceInfo(orderSubTotal, this.getLocale()), "ORDER", "SUB_TOTAL");
        this.setPrice(new PriceInfo(orderTotalTax, this.getLocale()), "ORDER", "TAX");
        this.setPrice(new PriceInfo(totalDiscount, this.getLocale()), "DISCOUNT", "TOTAL");
        this.setPrice(new PriceInfo(orderDiscount, this.getLocale()), "DISCOUNT", "ORDER");
        this.setPrice(new PriceInfo(shippingDiscount, this.getLocale()), "DISCOUNT", "SHIPPING");
        List<ShippingMethod> shippingMethods = this.getAvailableShippingMethods();
        for (ShippingMethod shippingMethod : shippingMethods) {
            String method = shippingMethod.getPath();
            this.setPrice(new PriceInfo(this.getShipping(method), this.getLocale()), "shipping-option", method);
        }
    }

    @Override
    public List<VoucherInfo> getVoucherInfos() throws CommerceException {
        ArrayList<VoucherInfo> list = new ArrayList<VoucherInfo>();
        for (Voucher voucher : this.vouchers) {
            list.add(new VoucherInfo(voucher.getCode(), voucher.getPath(), voucher.getTitle(), voucher.getDescription(), voucher.isValid(this.request), voucher.getMessage(this.request)));
        }
        return list;
    }

    @Override
    public void addVoucher(String code) throws CommerceException {
        PromotionManager pm = (PromotionManager)this.resolver.adaptTo(PromotionManager.class);
        Voucher voucher = pm.findVoucher(this.request, code);
        if (voucher == null) {
            I18n i18n = new I18n((HttpServletRequest)this.request);
            throw new CommerceException(i18n.get("Invalid voucher code."));
        }
        if (!voucher.isValid(this.request)) {
            throw new CommerceException(voucher.getMessage(this.request));
        }
        for (Voucher existingVoucher : this.vouchers) {
            if (!existingVoucher.getCode().equals(voucher.getCode())) continue;
            I18n i18n = new I18n((HttpServletRequest)this.request);
            throw new CommerceException(i18n.get("Voucher already added."));
        }
        this.vouchers.add(voucher);
        this.calcCart();
        this.saveCart();
    }

    @Override
    public void removeVoucher(String code) throws CommerceException {
        for (int i = 0; i < this.vouchers.size(); ++i) {
            if (!this.vouchers.get(i).getCode().equals(code)) continue;
            this.vouchers.remove(i--);
        }
        this.calcCart();
        this.saveCart();
    }

    @Override
    public String getOrderId() throws CommerceException {
        if (this.orderId == null) {
            return this.orderDetails.get(this.PN_ORDER_ID);
        }
        return this.orderId;
    }

    protected void doUpdateOrderDetails(Map<String, String> delta) throws CommerceException {
        HashMap<String, String> paymentDetails = new HashMap<String, String>();
        boolean shippingAddressSame = StringUtils.isNotEmpty((String)delta.get("shippingAddressSameAsBilling"));
        PaymentMethod paymentMethod = this.getPaymentMethod(delta);
        String paymentPrefix = paymentMethod != null ? paymentMethod.getPredicate() + "." : "payment.";
        for (Map.Entry<String, String> entry : delta.entrySet()) {
            String key = entry.getKey();
            if (key.equals("shippingAddressSameAsBilling")) continue;
            if (key.startsWith(paymentPrefix)) {
                paymentDetails.put(key, entry.getValue());
                continue;
            }
            this.orderDetails.put(key, entry.getValue());
            if (!shippingAddressSame || !key.startsWith("billing.")) continue;
            String shippingKey = key.replace("billing", "billing");
            this.orderDetails.put(shippingKey, entry.getValue());
        }
        if (!paymentDetails.isEmpty()) {
            this.orderDetails.put("paymentToken", this.tokenizePaymentInfo(paymentDetails));
        }
    }

    protected PaymentMethod getPaymentMethod(Map<String, String> delta) {
        Resource resource;
        String paymentOption = delta.get("payment-option");
        if (paymentOption != null && (resource = this.resolver.getResource(paymentOption)) != null) {
            return (PaymentMethod)resource.adaptTo(PaymentMethod.class);
        }
        return null;
    }

    @Override
    public void updateOrder(Map<String, Object> delta) throws CommerceException {
        HashMap<String, String> newDelta = new HashMap<String, String>();
        ValueMapDecorator vm = new ValueMapDecorator(delta);
        for (String key : vm.keySet()) {
            String value = (String)vm.get(key, String.class);
            if (value == null) continue;
            newDelta.put(key, value);
        }
        this.doUpdateOrderDetails(newDelta);
        this.saveCart();
    }

    protected void doUpdateOrderDetails(Map<String, Object> delta, String predicate) throws CommerceException {
        if (StringUtils.isNotEmpty((String)predicate)) {
            predicate = "." + predicate;
        }
        HashMap<String, String> newDelta = new HashMap<String, String>();
        ValueMapDecorator vm = new ValueMapDecorator(delta);
        for (String key : vm.keySet()) {
            String value = (String)vm.get(key, String.class);
            if (value == null) continue;
            newDelta.put(predicate + "." + key, value);
        }
        this.doUpdateOrderDetails(newDelta);
    }

    @Override
    public void updateOrderDetails(Map<String, Object> details, String predicate) throws CommerceException {
        this.doUpdateOrderDetails(details, predicate);
        this.saveCart();
    }

    @Override
    public Map<String, String> getOrderDetails() throws CommerceException {
        if (this.orderDetails.isEmpty() || this.orderDetails.size() == 1 && this.orderDetails.containsKey(this.PN_ORDER_ID)) {
            try {
                Session userSession = (Session)this.resolver.adaptTo(Session.class);
                UserProperties userProperties = (UserProperties)this.request.adaptTo(UserProperties.class);
                if (userProperties != null && !UserPropertiesUtil.isAnonymous((UserProperties)userProperties)) {
                    UserManager um = ((JackrabbitSession)userSession).getUserManager();
                    Authorizable authorizable = um.getAuthorizable(userProperties.getAuthorizableID());
                    UserPropertiesManager upm = this.commerceService.serviceContext().userPropertiesService.createUserPropertiesManager(this.resolver);
                    UserProperties profile = upm.getUserProperties(authorizable.getID(), "profile");
                    HashMap<String, Object> address = new HashMap<String, Object>();
                    address.put("firstname", profile.getProperty("givenName"));
                    address.put("lastname", profile.getProperty("familyName"));
                    address.put("street1", profile.getProperty("streetAddress"));
                    address.put("city", profile.getProperty("city"));
                    address.put("state", profile.getProperty("region"));
                    address.put("zip", profile.getProperty("postalCode"));
                    this.doUpdateOrderDetails(address, "billing");
                    this.doUpdateOrderDetails(address, "shipping");
                }
            }
            catch (RepositoryException e) {
                // empty catch block
            }
        }
        return this.orderDetails;
    }

    @Override
    public Map<String, Object> getOrder() throws CommerceException {
        return new HashMap<String, Object>(this.getOrderDetails());
    }

    @Override
    public Map<String, Object> getOrderDetails(String predicate) throws CommerceException {
        Map<String, String> fullDetails = this.getOrderDetails();
        HashMap<String, Object> returnDetails = new HashMap<String, Object>();
        for (Map.Entry<String, String> detail : fullDetails.entrySet()) {
            String key = detail.getKey();
            if (!key.startsWith(predicate + ".")) continue;
            returnDetails.put(key.substring(predicate.length() + 1), detail.getValue());
        }
        return returnDetails;
    }

    protected String tokenizePaymentInfo(Map<String, String> paymentDetails) throws CommerceException {
        return UUID.randomUUID().toString();
    }

    protected void doPlaceOrder(Map<String, String> orderDetailsDelta) throws CommerceException {
        this.doUpdateOrderDetails(orderDetailsDelta);
        String orderPath = this.savePlacedOrderVendorRecord();
        this.savePlacedOrderShopperRecord();
        this.orderId = this.getOrderId();
        this.cart.clear();
        this.vouchers.clear();
        this.orderDetails.clear();
        this.saveCart();
        this.initiateOrderProcessing(orderPath);
    }

    protected void initiateOrderProcessing(String orderPath) throws CommerceException {
    }

    protected String getOrderStatus(String orderId) throws CommerceException {
        return "";
    }

    @Override
    public void placeOrder(Map<String, Object> delta) throws CommerceException {
        HashMap<String, String> newDelta = new HashMap<String, String>();
        ValueMapDecorator vm = new ValueMapDecorator(delta);
        for (String key : vm.keySet()) {
            String value = (String)vm.get(key, String.class);
            if (value == null) continue;
            newDelta.put(key, value);
        }
        this.doPlaceOrder(newDelta);
    }

    protected void initializeOrderStorage(Session session) throws RepositoryException {
        String ordersNodePath = "/etc/commerce/orders/".substring(0, "/etc/commerce/orders/".length() - 1);
        if (!session.nodeExists(ordersNodePath)) {
            JcrUtil.createPath((String)ordersNodePath, (String)"nt:unstructured", (Session)session);
            session.save();
        }
    }

    protected String savePlacedOrderVendorRecord() throws CommerceException {
        String vendorRecordPath = null;
        Calendar now = Calendar.getInstance(this.locale);
        Session serviceSession = null;
        try {
            serviceSession = this.commerceService.serviceContext().slingRepository.loginService("orders", null);
            Node ordersBaseNode = serviceSession.getNode("/etc/commerce/orders/");
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd");
            String relativeOrderPath = dateFormatter.format(now.getTime()) + "/" + "order";
            Node vendorRecord = JcrUtil.createPath((Node)ordersBaseNode, (String)relativeOrderPath, (boolean)true, (String)"sling:Folder", (String)"nt:unstructured", (Session)serviceSession, (boolean)true);
            this.writeOrder(vendorRecord, now, serviceSession);
            serviceSession.save();
            vendorRecordPath = vendorRecord.getPath();
        }
        catch (RepositoryException e) {
            throw new CommerceException("Failed to save completed order: ", (Throwable)e);
        }
        finally {
            if (serviceSession != null) {
                serviceSession.logout();
            }
        }
        return vendorRecordPath;
    }

    protected void savePlacedOrderShopperRecord() throws CommerceException {
        Calendar now = Calendar.getInstance(this.locale);
        try {
            Session userSession = (Session)this.resolver.adaptTo(Session.class);
            UserProperties userProperties = (UserProperties)this.request.adaptTo(UserProperties.class);
            if (userProperties != null && !UserPropertiesUtil.isAnonymous((UserProperties)userProperties)) {
                UserManager um = ((JackrabbitSession)userSession).getUserManager();
                Authorizable user = um.getAuthorizable(userProperties.getAuthorizableID());
                SimpleDateFormat dateFormatter = new SimpleDateFormat("'order'-yyyy-MMM-dd");
                String userOrderPath = user.getPath() + "/commerce/orders/" + dateFormatter.format(now.getTime());
                Node shopperRecord = JcrUtil.createPath((String)userOrderPath, (boolean)true, (String)"sling:Folder", (String)"nt:unstructured", (Session)userSession, (boolean)false);
                this.writeOrder(shopperRecord, now, userSession);
                userSession.save();
            }
        }
        catch (RepositoryException e) {
            throw new CommerceException("Failed to save completed order to user's home: ", (Throwable)e);
        }
    }

    protected void writeOrder(Node orderNode, Calendar placedTime, Session session) throws CommerceException, RepositoryException {
        String info;
        ArrayList<String> entries = new ArrayList<String>();
        for (CommerceSession.CartEntry entry : this.cart) {
            entries.add(this.serializeCartEntry(entry));
        }
        orderNode.setProperty("cartItems", entries.toArray(new String[entries.size()]));
        String currencyCode = Currency.getInstance(this.getLocale()).getCurrencyCode();
        BigDecimal cartPreTaxPrice = this.getCartPriceInfo(new PriceFilter("PRE_TAX", currencyCode)).get(0).getAmount();
        BigDecimal orderShipping = this.getCartPriceInfo(new PriceFilter("SHIPPING", currencyCode)).get(0).getAmount();
        BigDecimal orderTotalTax = this.getCartPriceInfo(new PriceFilter("ORDER", "TAX", currencyCode)).get(0).getAmount();
        BigDecimal orderTotalPrice = this.getCartPriceInfo(new PriceFilter("ORDER", "TOTAL", currencyCode)).get(0).getAmount();
        orderNode.setProperty("jcr:language", this.getLocale().toString());
        orderNode.setProperty("currencyCode", currencyCode);
        orderNode.setProperty("cartSubtotal", cartPreTaxPrice);
        orderNode.setProperty("orderShipping", orderShipping);
        orderNode.setProperty("orderTotalTax", orderTotalTax);
        orderNode.setProperty("orderTotalPrice", orderTotalPrice);
        orderNode.setProperty("orderPlaced", placedTime);
        orderNode.setProperty("orderId", this.orderDetails.get(this.PN_ORDER_ID));
        Node orderDetailsNode = JcrUtil.createUniqueNode((Node)orderNode, (String)"order-details", (String)"nt:unstructured", (Session)session);
        for (Map.Entry<String, String> entry2 : this.orderDetails.entrySet()) {
            String[] parts;
            String detail = this.serializeOrderDetail(entry2.getKey(), entry2.getValue());
            if (detail == null || (parts = detail.split("=")).length != 2) continue;
            orderDetailsNode.setProperty(parts[0], parts[1]);
        }
        ArrayList<String> infos = new ArrayList<String>();
        for (PromotionInfo promotionInfo : this.getPromotions()) {
            info = this.serializePromotionInfo(promotionInfo);
            if (info == null) continue;
            infos.add(info);
        }
        orderNode.setProperty("promotions", infos.toArray(new String[infos.size()]));
        infos = new ArrayList();
        for (VoucherInfo voucherInfo : this.getVoucherInfos()) {
            info = this.serializeVoucherInfo(voucherInfo);
            if (info == null) continue;
            infos.add(info);
        }
        orderNode.setProperty("vouchers", infos.toArray(new String[infos.size()]));
    }

    protected String serializeCartEntry(CommerceSession.CartEntry entry) throws CommerceException {
        String str = this.commerceService.serializeCartEntryData(entry.getProduct().getPath(), entry.getQuantity(), ((DefaultJcrCartEntry)entry).getProperties());
        return str;
    }

    protected CommerceSession.CartEntry deserializeCartEntry(String str, int index) throws CommerceException {
        Object[] entryData = this.commerceService.deserializeCartEntryData(str);
        Product product = (Product)entryData[0];
        int quantity = (Integer)entryData[1];
        DefaultJcrCartEntry entry = this.commerceService.newCartEntryImpl(index, product, quantity);
        if (entryData[2] == null) {
            return entry;
        }
        Map properties = (Map)entryData[2];
        entry.updateProperties(properties);
        return entry;
    }

    protected String serializeOrderDetail(String key, String value) throws CommerceException {
        if (key.equals(this.PN_ORDER_ID)) {
            return null;
        }
        if (key.contains("primary-account-number")) {
            if (value.length() > 4) {
                value = value.substring(0, value.length() - 4).replaceAll("[0-9]", "x") + value.substring(value.length() - 4);
            }
        } else if (key.contains("ccv")) {
            return null;
        }
        return key + "=" + value;
    }

    protected String serializeVoucherInfo(VoucherInfo voucherInfo) {
        if (voucherInfo.getIsValid()) {
            return voucherInfo.getCode() + ";" + voucherInfo.getPath() + ";" + voucherInfo.getMessage();
        }
        return null;
    }

    protected String serializePromotionInfo(PromotionInfo promotionInfo) {
        if (promotionInfo.getStatus() == PromotionInfo.PromotionStatus.FIRED) {
            Integer entryIndex = promotionInfo.getCartEntryIndex();
            return promotionInfo.getPath() + ";" + entryIndex + ";" + promotionInfo.getMessage();
        }
        return null;
    }

    @Override
    public PlacedOrderResult getPlacedOrders(String predicate, int pageNumber, int pageSize, String sortId) throws CommerceException {
        ArrayList<PlacedOrder> orders = new ArrayList<PlacedOrder>();
        try {
            Session userSession = (Session)this.resolver.adaptTo(Session.class);
            UserProperties userProperties = (UserProperties)this.request.adaptTo(UserProperties.class);
            if (userProperties != null && !UserPropertiesUtil.isAnonymous((UserProperties)userProperties)) {
                UserManager um = ((JackrabbitSession)userSession).getUserManager();
                Authorizable user = um.getAuthorizable(userProperties.getAuthorizableID());
                StringBuilder buffer = new StringBuilder();
                buffer.append("/jcr:root").append(ISO9075.encodePath((String)(user.getPath() + "/commerce/orders/"))).append("/element(*)[@orderId]");
                Query query = userSession.getWorkspace().getQueryManager().createQuery(buffer.toString(), "xpath");
                NodeIterator nodeIterator = query.execute().getNodes();
                Predicate filter = this.getPredicate(predicate);
                while (nodeIterator.hasNext()) {
                    DefaultJcrPlacedOrder order = this.newPlacedOrderImpl(nodeIterator.nextNode().getPath());
                    if (filter != null && !filter.evaluate((Object)order)) continue;
                    orders.add(order);
                }
            }
        }
        catch (Exception e) {
            log.error("Error while fetching orders", (Throwable)e);
        }
        return new PlacedOrderResult(orders, null, null);
    }

    protected Predicate getPredicate(String predicateName) {
        return null;
    }

    public DefaultJcrPlacedOrder newPlacedOrderImpl(String orderId) {
        return new DefaultJcrPlacedOrder(this, orderId);
    }

    @Override
    public PlacedOrder getPlacedOrder(String orderId) throws CommerceException {
        return this.newPlacedOrderImpl(orderId);
    }

    @Override
    public SmartListManager getSmartListManager() {
        return this.request != null ? (SmartListManager)this.request.adaptTo(SmartListManager.class) : null;
    }

    @Deprecated
    @Override
    public String getPriceInfo(Product product) throws CommerceException {
        List<PriceInfo> prices = this.getProductPriceInfo(product);
        return prices.size() > 0 ? prices.get(0).getFormattedString() : null;
    }

    @Deprecated
    @Override
    public String getCartPreTaxPrice() throws CommerceException {
        return this.getCartPrice(null);
    }

    @Deprecated
    @Override
    public String getCartTax() throws CommerceException {
        return this.getCartPrice(new PriceFilter("TAX"));
    }

    @Deprecated
    @Override
    public String getCartTotalPrice() throws CommerceException {
        return this.getCartPrice(new PriceFilter("POST_TAX"));
    }

    @Deprecated
    @Override
    public String getOrderShipping() throws CommerceException {
        return this.getCartPrice(new PriceFilter("SHIPPING"));
    }

    @Deprecated
    @Override
    public String getOrderTotalTax() throws CommerceException {
        return this.getCartPrice(new PriceFilter("ORDER", "TAX"));
    }

    @Deprecated
    @Override
    public String getOrderTotalPrice() throws CommerceException {
        return this.getCartPrice(new PriceFilter("ORDER"));
    }

    @Deprecated
    public String getShippingPrice(String method) {
        return new PriceInfo(this.getShipping(method), this.userLocale != null ? this.userLocale : this.locale).getFormattedString();
    }

    @Deprecated
    protected String formatPrice(BigDecimal price) {
        if (price == null) {
            return "";
        }
        return this.formatter.format(price.doubleValue());
    }

    @Deprecated
    @Override
    public List<Voucher> getVouchers() throws CommerceException {
        ArrayList<Voucher> vouchers = new ArrayList<Voucher>();
        for (Voucher voucher : this.vouchers) {
            vouchers.add(new AbstractJcrVoucher(this.resolver.getResource(voucher.getPath())));
        }
        return vouchers;
    }

    @Deprecated
    @Override
    public void updateOrderDetails(Map<String, String> delta) throws CommerceException {
        this.doUpdateOrderDetails(delta);
        this.saveCart();
    }

    @Deprecated
    @Override
    public void submitOrder(Map<String, String> orderDetailsDelta) throws CommerceException {
        this.doPlaceOrder(orderDetailsDelta);
    }

    @Deprecated
    public DefaultJcrCartEntry newCartEntryImpl(int index, Product product, int quantity) {
        return this.commerceService.newCartEntryImpl(index, product, quantity);
    }

    @Deprecated
    protected void doAddCartEntry(Product product, int quantity) throws CommerceException {
        this.doAddCartEntry(product, quantity, null);
    }

}