public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    try {
      int custId;

      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      custId = this.loggedIn(request, response, kkAppEng, null);

      // Force the user to login if configured to do so
      if (custId < 0 && kkAppEng.isForceLogin()) {
        return KKLOGIN;
      }

      // Ensure we are using the correct protocol. Redirect if not.
      String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */ false);
      if (redirForward != null) {
        setupResponseForSSLRedirect(response, redirForward);
        return null;
      }

      kkAppEng.getNav().set(kkAppEng.getMsg("header.advanced.navigation"), request);
      return SUCCESS;

    } catch (Exception e) {
      return super.handleException(request, e);
    }
  }
  @Override
  public void manageCookieLogout(
      @Nonnull HttpServletRequest request,
      @Nonnull HttpServletResponse response,
      @Nonnull KKAppEng kkAppEng)
      throws HstComponentException {

    if (!kkAppEng.isKkCookieEnabled()) {
      return;
    }

    CustomerIf currentCustomer = kkAppEng.getCustomerMgr().getCurrentCustomer();
    if (currentCustomer != null) {
      String guestCustomerIdStr = getKKCookie(GUEST_CUSTOMER_ID, request, response, kkAppEng);
      // Only get the basket items if we can retrieve a temporary customer from the cookie
      if (guestCustomerIdStr != null) {
        try {
          currentCustomer.setId(Integer.parseInt(guestCustomerIdStr));
          kkAppEng.getBasketMgr().getBasketItemsPerCustomer();
        } catch (NumberFormatException e) {
          // do nothing
        } catch (KKException e) {
          throw new HstComponentException(e);
        } catch (KKAppException e) {
          throw new HstComponentException(e);
        }
      }
    }
  }
  /**
   * When we log out, ensure that the new guest customer that is created has the id saved in the
   * browser cookie.
   *
   * @param request
   * @param response
   * @param kkAppEng
   * @throws KKException
   * @throws KKAppException
   */
  protected void manageCookieLogout(
      HttpServletRequest request, HttpServletResponse response, KKAppEng kkAppEng)
      throws KKException, KKAppException {
    if (!kkAppEng.isKkCookieEnabled()) {
      return;
    }

    CustomerIf currentCustomer = kkAppEng.getCustomerMgr().getCurrentCustomer();
    if (currentCustomer != null) {
      String guestCustomerIdStr = getKKCookie(GUEST_CUSTOMER_ID, request, response, kkAppEng);
      // Only get the basket items if we can retrieve a temporary customer from the cookie
      if (guestCustomerIdStr != null) {
        try {
          currentCustomer.setId(Integer.parseInt(guestCustomerIdStr));
          kkAppEng.getBasketMgr().getBasketItemsPerCustomer();
        } catch (NumberFormatException e) {

        }
      }
    }

    /*
     * Call class where you can place custom code
     */
    CustomCookieAction cca = new CustomCookieAction();
    cca.manageCookiesAfterLogout(request, response, kkAppEng);
  }
  /**
   * A common method that contains the code to deal with exceptions
   *
   * @param request
   * @param e
   * @return Returns a string
   */
  protected String handleException(HttpServletRequest request, Exception e) {

    if (e != null && e.getClass().getName().equals("com.konakart.app.KKException")) {
      KKException ex = (KKException) e;

      switch (ex.getCode()) {
        case KKException.KK_STORE_DELETED:
          if (appEng != null) {
            addActionError(appEng.getMsg("unavailable.deleted"));
          }
          return new String("Unavailable");
        case KKException.KK_STORE_DISABLED:
          if (appEng != null) {
            addActionError(appEng.getMsg("unavailable.disabled"));
          }
          return new String("Unavailable");
        case KKException.KK_STORE_UNDER_MAINTENANCE:
          if (appEng != null) {
            addActionError(appEng.getMsg("unavailable.maintenance"));
          }
          return new String("Unavailable");
      }
    }

    Long time = System.currentTimeMillis();
    log.error("A customer has received the following exception ( ref: " + time + " )", e);
    if (appEng != null) {
      addActionError(Long.toString(time));
    }
    return new String("Exception");
  }
 /**
  * Returns a customer event object with the action and customer id attributes populated. If events
  * aren't enabled, then null is returned.
  *
  * @param kkAppEng App eng instance
  * @param action Event action
  * @return Returns a customer event object or null if events aren't enabled
  */
 protected CustomerEventIf getCustomerEvent(KKAppEng kkAppEng, int action) {
   String enabled = kkAppEng.getConfig(ConfigConstants.ENABLE_CUSTOMER_EVENTS);
   if (enabled != null && enabled.equalsIgnoreCase("true")) {
     CustomerEventIf event = new CustomerEvent();
     event.setAction(action);
     CustomerIf currentCust = kkAppEng.getCustomerMgr().getCurrentCustomer();
     if (currentCust != null) {
       event.setCustomerId(currentCust.getId());
     }
     return event;
   }
   return null;
 }
  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    try {
      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      // Set the cookie so that we don't display the message again
      kkAppEng.setAgreedCookies(true);
      setKKCookie(AGREED_COOKIES, "1", request, response, kkAppEng);

      return SUCCESS;

    } catch (Exception e) {
      return super.handleException(request, e);
    }
  }
 /**
  * Utility method to set a KKCookie when we have the customerUuid
  *
  * @param customerUuid
  * @param attrId
  * @param attrValue
  * @param kkAppEng
  * @throws KKException
  */
 protected void setKKCookie(
     String customerUuid, String attrId, String attrValue, KKAppEng kkAppEng) throws KKException {
   if (customerUuid != null) {
     KKCookieIf kkCookie = new KKCookie();
     kkCookie.setCustomerUuid(customerUuid);
     kkCookie.setAttributeId(attrId);
     kkCookie.setAttributeValue(attrValue);
     kkAppEng.getEng().setCookie(kkCookie);
   }
 }
  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    try {
      int custId;

      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      custId = this.loggedIn(request, response, kkAppEng, null);

      // Ensure we are using the correct protocol. Redirect if not.
      String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */ false);
      if (redirForward != null) {
        setupResponseForSSLRedirect(response, redirForward);
        return null;
      }

      String navDir = request.getParameter("navDir");
      if (log.isDebugEnabled()) {
        log.debug("Navigation direction from application = " + navDir);
      }
      if (navDir == null) {
        return WELCOME;
      }

      // The timestamp which connects the navigation links to a result set
      String timestampStr = request.getParameter("t");
      long timestamp = 0;
      try {
        timestamp = Long.parseLong(timestampStr);
      } catch (Exception e) {
      }

      kkAppEng.getProductMgr().navigateCurrentProducts(navDir, timestamp);

      return SUCCESS;

    } catch (Exception e) {
      return super.handleException(request, e);
    }
  }
  /**
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {

    try {
      int custId;

      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      // Check to see whether the user is logged in
      custId = this.loggedIn(request, response, kkAppEng, "ShowOrderDetails");
      if (custId < 0) {
        return mapping.findForward(loginForward);
      }

      // Ensure we are using the correct protocol. Redirect if not.
      ActionForward redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */ false);
      if (redirForward != null) {
        return redirForward;
      }

      String orderId = request.getParameter("orderId");
      if (orderId == null) {
        return mapping.findForward("MyAccount");
      }

      if (log.isDebugEnabled()) {
        log.debug("Order Id from application = " + orderId);
      }

      kkAppEng.getOrderMgr().getOrder(new Integer(orderId).intValue());

      kkAppEng.nav.add(getCatMessage(request, "header.order"), request);

      return mapping.findForward("ShowOrderDetails");

    } catch (Exception e) {
      return mapping.findForward(super.handleException(request, e));
    }
  }
Exemple #10
0
  /**
   * Checks to see whether we are logged in.
   *
   * @param kkAppEng The KonaKart client engine instance
   * @param forwardAfterLogin tells us which page to forward to after login.
   * @param request
   * @param response
   * @param checkXSRF
   * @param xsrfToken
   * @return Returns the CustomerId if logged in. Otherwise a negative number.
   * @throws KKException
   * @throws KKAppException
   */
  protected int loggedIn(
      HttpServletRequest request,
      HttpServletResponse response,
      KKAppEng kkAppEng,
      String forwardAfterLogin,
      boolean checkXSRF,
      String xsrfToken)
      throws KKException, KKAppException {
    // If the session is null, set the forward and return a negative number.
    if ((kkAppEng.getSessionId() == null)) {
      if (forwardAfterLogin != null) {
        kkAppEng.setForwardAfterLogin(forwardAfterLogin);
      }
      return -1;
    }

    // If an exception is thrown, set the forward and return it
    int custId;
    try {
      custId = kkAppEng.getEng().checkSession(kkAppEng.getSessionId());
    } catch (KKException e) {
      log.debug(e.getMessage());
      if (forwardAfterLogin != null) {
        kkAppEng.setForwardAfterLogin(forwardAfterLogin);
      }

      kkAppEng.getCustomerMgr().logout();

      // Ensure that the guest customer is the one in the cookie
      manageCookieLogout(request, response, kkAppEng);

      return -1;
    }

    // Check the XSRF token for a post. Don't check anything we are redirected to after a login
    // since the token wasn't available at the time of the post
    if (kkAppEng.getXsrfToken() != null
        && checkXSRF
        && !request.getServletPath().contains("LoginSubmit")) {
      String method = request.getMethod();
      if (method != null && method.equalsIgnoreCase("POST")) {
        String token = (xsrfToken != null) ? xsrfToken : request.getParameter("xsrf_token");
        if (token == null || !token.equals(kkAppEng.getXsrfToken())) {
          log.warn("Possible XSRF attack for customer with id = " + custId);
          return -1;
        }
      }
    }

    // At this point we return a valid customer Id
    return custId;
  }
Exemple #11
0
  /**
   * Sets the variable kkAppEng to the KKAppEng instance saved in the session. If cannot be found,
   * then it is instantiated and attached.
   *
   * @param request
   * @param response
   * @return Returns a KonaKart client engine instance
   * @throws KKException
   * @throws KKAppException
   */
  protected KKAppEng getKKAppEng(HttpServletRequest request, HttpServletResponse response)
      throws KKAppException, KKException {
    HttpSession session = request.getSession();
    KKAppEng kkAppEng = (KKAppEng) session.getAttribute(KKAppEng.KONAKART_KEY);
    if (kkAppEng == null) {
      if (log.isInfoEnabled()) {
        log.info("KKAppEng not found on the session");
      }

      String storeIdForNewEngine = getStoreIdFromRequest(request);

      StoreInfo si = new StoreInfo();
      si.setStoreId(storeIdForNewEngine);
      kkAppEng = new KKAppEng(si, session);

      if (log.isInfoEnabled()) {
        log.info("Set KKAppEng on the session for storeId " + si.getStoreId());
      }

      /*
       * Add KKAppEng to the struts and the HTTP sessions. In order for the struts jsp tags to
       * see it, it has to be added to the struts session as well.
       */
      session.setAttribute(KKAppEng.KONAKART_KEY, kkAppEng);
      strutsSession.put(KKAppEng.KONAKART_KEY, kkAppEng);

      String customerUuid = manageCookies(request, response, kkAppEng);
      if (customerUuid != null) {
        // Get the locale from the cookie
        String savedLocale = getKKCookie(customerUuid, CUSTOMER_LOCALE, kkAppEng);
        if (savedLocale != null) {
          // Set the engine with the new locale
          kkAppEng.setLocale(savedLocale);
        }
      }

      // Insert event
      insertCustomerEvent(kkAppEng, ACTION_NEW_CUSTOMER_VISIT);
    }

    kkAppEng.setPageTitle(kkAppEng.getMsg("seo.default.title"));
    kkAppEng.setMetaDescription(kkAppEng.getMsg("seo.default.meta.description"));
    kkAppEng.setMetaKeywords(kkAppEng.getMsg("seo.default.meta.keywords"));

    /* Save a copy in the base action */
    appEng = kkAppEng;

    /* Used by the JSP */
    jspEng = kkAppEng;

    return kkAppEng;
  }
Exemple #12
0
 /**
  * Utility method to read a KKCookie when we have the CustomerUuid
  *
  * @param customerUuid
  * @param attrId
  * @param kkAppEng
  * @return the value of the cookie
  * @throws KKException
  */
 protected String getKKCookie(String customerUuid, String attrId, KKAppEng kkAppEng)
     throws KKException {
   if (customerUuid == null) {
     return null;
   }
   KKCookieIf kkCookie = kkAppEng.getEng().getCookie(customerUuid, attrId);
   if (kkCookie != null) {
     return kkCookie.getAttributeValue();
   }
   return null;
 }
  @Override
  public void manageCookiesLogin(
      @Nonnull HttpServletRequest request,
      @Nonnull HttpServletResponse response,
      @Nonnull KKAppEng kkAppEng)
      throws HstComponentException {
    if (!kkAppEng.isKkCookieEnabled()) {
      return;
    }

    CustomerIf currentCustomer = kkAppEng.getCustomerMgr().getCurrentCustomer();
    if (currentCustomer != null) {
      setKKCookie(
          CUSTOMER_NAME,
          currentCustomer.getFirstName() + " " + currentCustomer.getLastName(),
          request,
          response,
          kkAppEng);
    }

    try {
      /*
       * Get customer preferences from customer tags. If the tag value exists, then set the
       * preference in the manager and set the cookie.
       */
      String prodPageSizeStr = kkAppEng.getCustomerTagMgr().getCustomerTagValue(TAG_PROD_PAGE_SIZE);
      if (prodPageSizeStr != null && prodPageSizeStr.length() > 0) {
        int prodPageSize = Integer.parseInt(prodPageSizeStr);
        kkAppEng.getProductMgr().setMaxDisplaySearchResults(prodPageSize);
        setKKCookie(TAG_PROD_PAGE_SIZE, prodPageSizeStr, request, response, kkAppEng);
      }
      String orderPageSizeStr =
          kkAppEng.getCustomerTagMgr().getCustomerTagValue(TAG_ORDER_PAGE_SIZE);
      if (orderPageSizeStr != null && orderPageSizeStr.length() > 0) {
        int orderPageSize = Integer.parseInt(orderPageSizeStr);
        kkAppEng.getOrderMgr().setPageSize(orderPageSize);
        setKKCookie(TAG_ORDER_PAGE_SIZE, orderPageSizeStr, request, response, kkAppEng);
      }
      String reviewPageSizeStr =
          kkAppEng.getCustomerTagMgr().getCustomerTagValue(TAG_REVIEW_PAGE_SIZE);
      if (reviewPageSizeStr != null && reviewPageSizeStr.length() > 0) {
        int reviewPageSize = Integer.parseInt(reviewPageSizeStr);
        kkAppEng.getReviewMgr().setPageSize(reviewPageSize);
        setKKCookie(TAG_REVIEW_PAGE_SIZE, reviewPageSizeStr, request, response, kkAppEng);
      }
    } catch (KKAppException e) {
      throw new HstComponentException(e);
    } catch (KKException e) {
      throw new HstComponentException(e);
    }
  }
 /**
  * Utility method to set a KKCookie when we have the customerUuid
  *
  * @param customerUuid customer uuid
  * @param attrId the id of the attribute
  * @param attrValue the value to save
  * @param kkAppEng the konakart engine
  * @throws org.hippoecm.hst.core.component.HstComponentException .
  */
 private void setKKCookie(String customerUuid, String attrId, String attrValue, KKAppEng kkAppEng)
     throws HstComponentException {
   KKCookieIf kkCookie = new KKCookie();
   kkCookie.setCustomerUuid(customerUuid);
   kkCookie.setAttributeId(attrId);
   kkCookie.setAttributeValue(attrValue);
   try {
     kkAppEng.getEng().setCookie(kkCookie);
   } catch (KKException e) {
     throw new HstComponentException(e);
   }
 }
Exemple #15
0
 /**
  * Creates HTML to display an image
  *
  * @param c
  * @param src
  * @param title
  * @param addBase
  * @return Returns the HTML to display an image
  */
 protected StringBuffer getImg(String c, String src, String title, boolean addBase) {
   StringBuffer sb = new StringBuffer();
   sb.append("<img ");
   if (c != null) {
     sb.append(CLASS + D_QUOTE + c + D_QUOTE + " ");
   }
   sb.append("src=" + D_QUOTE + ((addBase) ? eng.getImageBase() + "/" : "") + src + D_QUOTE + " ");
   sb.append("border=" + D_QUOTE + "0" + D_QUOTE + " ");
   sb.append("alt=" + D_QUOTE + title + D_QUOTE + " ");
   sb.append("title=" + D_QUOTE + title + D_QUOTE + " ");
   sb.append(">");
   return sb;
 }
  /**
   * Utility method to read a KKCookie when we have the CustomerUuid
   *
   * @param customerUuid the customer UUID
   * @param attrId the attribute to save
   * @param kkAppEng the konakart engine.
   * @return the value of the cookie
   * @throws org.hippoecm.hst.core.component.HstComponentException .
   */
  @Nullable
  private String getKKCookie(String customerUuid, String attrId, KKAppEng kkAppEng)
      throws HstComponentException {
    try {
      KKCookieIf kkCookie = kkAppEng.getEng().getCookie(customerUuid, attrId);
      if (kkCookie != null) {
        return kkCookie.getAttributeValue();
      }

      return null;
    } catch (KKException e) {
      throw new HstComponentException(e);
    }
  }
  /**
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {

    try {
      int custId;

      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      custId = this.loggedIn(request, response, kkAppEng, null);

      // Ensure we are using the correct protocol. Redirect if not.
      ActionForward redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */ false);
      if (redirForward != null) {
        return redirForward;
      }

      String revId = request.getParameter("revId");
      if (revId == null) {
        return mapping.findForward("Welcome");
      }

      if (log.isDebugEnabled()) {
        log.debug("Review Id from application = " + revId);
      }

      kkAppEng.getReviewMgr().fetchReviewDetails(new Integer(revId).intValue());

      kkAppEng.nav.set(getCatMessage(request, "header.review.details"), request);
      return mapping.findForward("ShowReviewDetails");

    } catch (Exception e) {
      return mapping.findForward(super.handleException(request, e));
    }
  }
Exemple #18
0
  /**
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {

    try {
      int custId;

      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      custId = this.loggedIn(request, response, kkAppEng, null);

      // Ensure we are using the correct protocol. Redirect if not.
      ActionForward redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */ false);
      if (redirForward != null) {
        return redirForward;
      }

      String prodId = request.getParameter("prodId");
      if (prodId == null) {
        return mapping.findForward("Welcome");
      }

      if (log.isDebugEnabled()) {
        log.debug("Product Id from application = " + prodId);
      }

      kkAppEng.getProductMgr().fetchSelectedProduct(new Integer(prodId).intValue());

      return mapping.findForward("ShowImage");

    } catch (Exception e) {
      return mapping.findForward(super.handleException(request, e));
    }
  }
Exemple #19
0
  /**
   * Method changes the session before performing the login in order to avoid a Session Fixation
   * attack.
   *
   * @param kkAppEng
   * @param request
   * @param emailAddr
   * @param password
   * @return Return the session id
   * @throws KKException
   * @throws KKAppException
   */
  protected String login(
      KKAppEng kkAppEng, HttpServletRequest request, String emailAddr, String password)
      throws KKException, KKAppException {
    // Change the session
    changeSession(request);

    // Set this session to null to avoid struts interceptors from throwing an exception because
    // the session is invalid
    ActionContext context = ActionContext.getContext();
    context.setSession(null);

    // Login and return the new session
    String sessionId = kkAppEng.getCustomerMgr().login(emailAddr, password);
    return sessionId;
  }
Exemple #20
0
 /**
  * Method called when a customer logs in or logs out. When logging in we need to decide whether to
  * update the customer's PRODUCTS_VIEWED tag value from the value of the guest customer's tag.
  * When logging out we need to make the same decision in the opposite direction. We only do the
  * updates if the tag value of the "oldTag" is more recent than the tag value of the "newTag".
  *
  * @param oldTag When logging in, it is the tag of the guest customer. When logging out, it is the
  *     tag of the logged in customer.
  * @param newTag When logging in, it is the tag of the logged in customer. When logging out, it is
  *     the tag of the guest customer.
  * @throws KKException
  * @throws KKAppException
  */
 protected void updateRecentlyViewedProducts(
     KKAppEng kkAppEng, CustomerTagIf oldTag, CustomerTagIf newTag)
     throws KKAppException, KKException {
   if (oldTag != null
       && oldTag.getDateAdded() != null
       && oldTag.getValue() != null
       && oldTag.getValue().length() > 0) {
     if (newTag == null
         || newTag.getDateAdded() == null
         || newTag.getDateAdded().before(oldTag.getDateAdded())) {
       /*
        * If new tag doesn't exist or old tag is newer than new tag, then give newTag the
        * value of old tag
        */
       kkAppEng.getCustomerTagMgr().insertCustomerTag(TAG_PRODUCTS_VIEWED, oldTag.getValue());
     }
   }
 }
Exemple #21
0
 /**
  * Inserts a customer event where all of the available parameters are passed
  *
  * @param kkAppEng App eng instance
  * @param action Event action
  * @param str1
  * @param str2
  * @param int1
  * @param int2
  * @param dec1
  * @param dec2
  * @throws KKException
  */
 protected void insertCustomerEvent(
     KKAppEng kkAppEng,
     int action,
     String str1,
     String str2,
     int int1,
     int int2,
     BigDecimal dec1,
     BigDecimal dec2)
     throws KKException {
   CustomerEventIf event = getCustomerEvent(kkAppEng, action);
   if (event != null) {
     event.setData1Str(str1);
     event.setData2Str(str2);
     event.setData1Int(int1);
     event.setData2Int(int2);
     event.setData1Dec(dec1);
     event.setData2Dec(dec2);
     kkAppEng.getEng().insertCustomerEvent(event);
   }
 }
  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    try {
      int custId;

      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      custId = this.loggedIn(request, response, kkAppEng, null);

      // Ensure we are using the correct protocol. Redirect if not.
      String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */ false);
      if (redirForward != null) {
        setupResponseForSSLRedirect(response, redirForward);
        return null;
      }

      /*
       * Save preferences in managers, cookies and tags
       */
      kkAppEng.getReviewMgr().setPageSize(numRevs);
      setKKCookie(TAG_REVIEW_PAGE_SIZE, Integer.toString(numRevs), request, response, kkAppEng);
      kkAppEng
          .getCustomerTagMgr()
          .insertCustomerTag(TAG_REVIEW_PAGE_SIZE, Integer.toString(numRevs));

      DataDescriptorIf dd = kkAppEng.getReviewMgr().getDataDesc();
      if (dd != null) {
        dd.setLimit(numRevs + 1);
        dd.setOffset(0);
        kkAppEng.getReviewMgr().orderCurrentReviews(dd.getOrderBy(), t);
      }
      kkAppEng.getReviewMgr().setShowTab(true);

      return SUCCESS;

    } catch (Exception e) {
      return super.handleException(request, e);
    }
  }
  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    try {
      int custId;

      KKAppEng kkAppEng = this.getKKAppEng(request, response);

      custId = this.loggedIn(request, response, kkAppEng, null);

      // Check to see whether the user is logged in since this is required to create a gift
      // registry
      custId = this.loggedIn(request, response, kkAppEng, "CreateGiftRegistry");
      if (custId < 0) {
        return KKLOGIN;
      }

      // If it is a temporary customer, then he needs to register to create a gift registry
      if (kkAppEng.getCustomerMgr().getCurrentCustomer() != null
          && kkAppEng.getCustomerMgr().getCurrentCustomer().getType()
              == com.konakart.bl.CustomerMgr.CUST_TYPE_NON_REGISTERED_CUST) {
        return KKLOGIN;
      }

      // Ensure we are using the correct protocol. Redirect if not.
      String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */ false);
      if (redirForward != null) {
        setupResponseForSSLRedirect(response, redirForward);
        return null;
      }

      /*
       * Create the gift registry
       */
      WishListIf wl = new WishList();
      wl.setAddressId(getAddressId());
      wl.setCustom1(escapeFormInput(getCustom1()));
      wl.setCustom2(escapeFormInput(getCustom2()));
      wl.setCustom3(escapeFormInput(getCustom3()));
      wl.setCustom4(escapeFormInput(getCustom4()));
      wl.setCustom5(escapeFormInput(getCustom5()));
      wl.setCustomer1FirstName(escapeFormInput(getFirstName1()));
      wl.setCustomer1LastName(escapeFormInput(getLastName1()));
      wl.setCustomerFirstName(escapeFormInput(getFirstName()));
      wl.setCustomerLastName(escapeFormInput(getLastName()));
      wl.setCustomerId(custId);
      wl.setLinkUrl(escapeFormInput(getLinkURL()));
      wl.setListType(getListType());
      wl.setName(escapeFormInput(getRegistryName()));
      if (getPublicWishList() != null && getPublicWishList().equalsIgnoreCase("true")) {
        wl.setPublicWishList(true);
      } else {
        wl.setPublicWishList(false);
      }
      // Set the event date
      if (getEventDateString() != null && !getEventDateString().equals("")) {
        SimpleDateFormat sdf = new SimpleDateFormat(kkAppEng.getMsg("date.format"));
        Date d = sdf.parse(getEventDateString());
        if (d != null) {
          GregorianCalendar gc = new GregorianCalendar();
          gc.setTime(d);
          wl.setEventDate(gc);
        }
      }

      // Add the item
      wishListId = kkAppEng.getWishListMgr().createWishList(wl);
      // Refresh the customer's wish list
      kkAppEng.getWishListMgr().fetchCustomersWishLists();

      return SUCCESS;

    } catch (Exception e) {
      return super.handleException(request, e);
    }
  }
  @Override
  @Nullable
  public String manageCookies(
      @Nonnull HttpServletRequest request,
      @Nonnull HttpServletResponse response,
      @Nonnull KKAppEng kkAppEng)
      throws HstComponentException {
    if (!kkAppEng.isKkCookieEnabled()) {
      return null;
    }

    /*
     * The current customer should at this point be a guest customer with a negative customer id
     */
    CustomerIf currentCustomer = kkAppEng.getCustomerMgr().getCurrentCustomer();
    if (currentCustomer == null) {
      log.warn(
          "Current customer is set to null in the manageCookies method. This should never happen");
      return null;
    }

    /*
     * Get the customerUuid from the browser cookie. A new cookie is created if it doesn't exist
     */
    String customerUuid = getCustomerUuidFromBrowserCookie(request, response);

    /*
     * Get the guestCustomerId from the KK database.
     */
    String guestCustomerIdStr = getKKCookie(customerUuid, GUEST_CUSTOMER_ID, kkAppEng);

    if (guestCustomerIdStr == null) {
      /*
       * If it doesn't exist, then we create it
       */
      setKKCookie(
          customerUuid, GUEST_CUSTOMER_ID, Integer.toString(currentCustomer.getId()), kkAppEng);

    } else {
      /*
       * Set the current customer id with the one retrieved from the cookie and fetch any cart
       * items that he may have.
       */
      currentCustomer.setId(Integer.parseInt(guestCustomerIdStr));
      try {
        kkAppEng.getBasketMgr().getBasketItemsPerCustomer();
      } catch (Exception e) {
        throw new HstComponentException(e);
      }

      if (kkAppEng.getWishListMgr().allowWishListWhenNotLoggedIn()) {
        try {
          kkAppEng.getWishListMgr().fetchCustomersWishLists();
        } catch (Exception e) {
          throw new HstComponentException(e);
        }
      }

      // Get the product page size
      String prodPageSizeStr = getKKCookie(customerUuid, TAG_PROD_PAGE_SIZE, kkAppEng);
      if (prodPageSizeStr != null && prodPageSizeStr.length() > 0) {
        try {
          int prodPageSize = Integer.parseInt(prodPageSizeStr);
          kkAppEng.getProductMgr().setMaxDisplaySearchResults(prodPageSize);
        } catch (NumberFormatException e) {
          log.warn(
              "The product page size value stored in the cookie for customer with guest id "
                  + guestCustomerIdStr
                  + " is not a numeric value: "
                  + prodPageSizeStr);
        }
      }

      // Get the order page size
      String orderPageSizeStr = getKKCookie(customerUuid, TAG_ORDER_PAGE_SIZE, kkAppEng);
      if (orderPageSizeStr != null && orderPageSizeStr.length() > 0) {
        try {
          int orderPageSize = Integer.parseInt(orderPageSizeStr);
          kkAppEng.getOrderMgr().setPageSize(orderPageSize);
        } catch (NumberFormatException e) {
          log.warn(
              "The order page size value stored in the cookie for customer with guest id "
                  + guestCustomerIdStr
                  + " is not a numeric value: "
                  + orderPageSizeStr);
        }
      }

      // Get the review page size
      String reviewPageSizeStr = getKKCookie(customerUuid, TAG_REVIEW_PAGE_SIZE, kkAppEng);
      if (reviewPageSizeStr != null && reviewPageSizeStr.length() > 0) {
        try {
          int reviewPageSize = Integer.parseInt(reviewPageSizeStr);
          kkAppEng.getReviewMgr().setPageSize(reviewPageSize);
        } catch (NumberFormatException e) {
          log.warn(
              "The review page size value stored in the cookie for customer with guest id "
                  + guestCustomerIdStr
                  + " is not a numeric value: "
                  + reviewPageSizeStr);
        }
      }
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "GUEST_CUSTOMER_ID cookie value = "
              + getKKCookie(customerUuid, GUEST_CUSTOMER_ID, kkAppEng));
      log.debug(
          "CUSTOMER_NAME cookie value = " + getKKCookie(customerUuid, CUSTOMER_NAME, kkAppEng));
      log.debug(
          "CUSTOMER_LOCALE cookie value = " + getKKCookie(customerUuid, CUSTOMER_LOCALE, kkAppEng));
      log.debug(
          "PROD_PAGE_SIZE cookie value = "
              + getKKCookie(customerUuid, TAG_PROD_PAGE_SIZE, kkAppEng));
      log.debug(
          "ORDER_PAGE_SIZE cookie value = "
              + getKKCookie(customerUuid, TAG_ORDER_PAGE_SIZE, kkAppEng));
      log.debug(
          "REVIEW_PAGE_SIZE cookie value = "
              + getKKCookie(customerUuid, TAG_REVIEW_PAGE_SIZE, kkAppEng));
    }

    return customerUuid;
  }
  public void _jspService(
      final javax.servlet.http.HttpServletRequest request,
      final javax.servlet.http.HttpServletResponse response)
      throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\r');
      out.write('\n');
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      com.konakart.al.KKAppEng kkEng =
          (com.konakart.al.KKAppEng) session.getAttribute("konakartKey");
      out.write("\r\n");
      out.write("\t\t    \t\r\n");
      //  kk:carousel
      com.konakart.kktags.CarouselTag _jspx_th_kk_005fcarousel_005f0 =
          (com.konakart.kktags.CarouselTag)
              _005fjspx_005ftagPool_005fkk_005fcarousel_0026_005fwidth_005ftitle_005fprods_005fnobody
                  .get(com.konakart.kktags.CarouselTag.class);
      _jspx_th_kk_005fcarousel_005f0.setPageContext(_jspx_page_context);
      _jspx_th_kk_005fcarousel_005f0.setParent(null);
      // /WEB-INF/jsp/FeaturedProductsBody.jsp(23,0) name = prods type = null reqTime = true
      // required = true fragment = false deferredValue = false expectedTypeName = null
      // deferredMethod = false methodSignature = null
      _jspx_th_kk_005fcarousel_005f0.setProds(kkEng.getProductMgr().getCustomProducts1());
      // /WEB-INF/jsp/FeaturedProductsBody.jsp(23,0) name = title type = null reqTime = true
      // required = true fragment = false deferredValue = false expectedTypeName = null
      // deferredMethod = false methodSignature = null
      _jspx_th_kk_005fcarousel_005f0.setTitle(kkEng.getMsg("featured.products.body.title"));
      // /WEB-INF/jsp/FeaturedProductsBody.jsp(23,0) name = width type = null reqTime = true
      // required = true fragment = false deferredValue = false expectedTypeName = null
      // deferredMethod = false methodSignature = null
      _jspx_th_kk_005fcarousel_005f0.setWidth(kkEng.getContentClass());
      int _jspx_eval_kk_005fcarousel_005f0 = _jspx_th_kk_005fcarousel_005f0.doStartTag();
      if (_jspx_th_kk_005fcarousel_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
        _005fjspx_005ftagPool_005fkk_005fcarousel_0026_005fwidth_005ftitle_005fprods_005fnobody
            .reuse(_jspx_th_kk_005fcarousel_005f0);
        return;
      }
      _005fjspx_005ftagPool_005fkk_005fcarousel_0026_005fwidth_005ftitle_005fprods_005fnobody.reuse(
          _jspx_th_kk_005fcarousel_005f0);
      out.write("\r\n");
      out.write("\r\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    String httpAuthStr = null;
    String httpUsername;
    String httpPassword;
    String pspReference = null;
    String merchantReference = null;
    String merchantAccountCode = null;
    String eventDate = null;
    String successString = null;
    boolean success = false;
    String paymentMethod = null;
    String value = null;
    String currency = null;
    String reason = null;

    String eventCode = null;
    String status = null;

    String sessionId = null;
    KKAppEng kkAppEng = null;

    if (log.isDebugEnabled()) {
      log.debug(BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE + " Notification Action");
    }

    // Create these outside of try / catch since they are needed in the case of a general
    // exception
    IpnHistoryIf ipnHistory = new IpnHistory();
    ipnHistory.setOrderId(-1);
    ipnHistory.setModuleCode(BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE);

    try {
      // Process the parameters sent in the callback
      StringBuffer sb = new StringBuffer();
      if (request != null) {
        Enumeration<String> en = request.getParameterNames();
        while (en.hasMoreElements()) {
          String paramName = en.nextElement();
          String paramValue = request.getParameter(paramName);
          if (sb.length() > 0) {
            sb.append("\n");
          }
          sb.append(paramName);
          sb.append(" = ");
          sb.append(paramValue);

          // Capture important variables so that we can determine whether the transaction
          // was successful
          if (paramName != null) {
            if (paramName.equalsIgnoreCase("eventCode")) {
              eventCode = paramValue;
            } else if (paramName.equalsIgnoreCase("pspReference")) {
              pspReference = paramValue;
            } else if (paramName.equalsIgnoreCase("merchantReference")) {
              merchantReference = paramValue;
            } else if (paramName.equalsIgnoreCase("merchantAccountCode")) {
              merchantAccountCode = paramValue;
            } else if (paramName.equalsIgnoreCase("eventDate")) {
              eventDate = paramValue;
            } else if (paramName.equalsIgnoreCase("success")) {
              successString = paramValue;
              success = Boolean.valueOf(successString);
            } else if (paramName.equalsIgnoreCase("paymentMethod")) {
              paymentMethod = paramValue;
            } else if (paramName.equalsIgnoreCase("value")) {
              value = paramValue;
            } else if (paramName.equalsIgnoreCase("currency")) {
              currency = paramValue;
            } else if (paramName.equalsIgnoreCase("reason")) {
              reason = paramValue;
            }
          }
        }
      }

      if (log.isDebugEnabled()) {
        log.debug(
            BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE
                + " Raw Notification Data:\n"
                + sb.toString());
        log.debug(
            "\n    merchantAccountCode       = "
                + merchantAccountCode
                + "\n"
                + "    eventCode                 = "
                + eventCode
                + "\n"
                + "    eventDate                 = "
                + eventDate
                + "\n"
                + "    merchantReference         = "
                + merchantReference
                + "\n"
                + "    pspReference              = "
                + pspReference
                + "\n"
                + "    paymentMethod             = "
                + paymentMethod
                + "\n"
                + "    amount                    = "
                + value
                + "\n"
                + "    currency                  = "
                + currency
                + "\n"
                + "    success                   = "
                + successString
                + "\n"
                + "    reason                    = "
                + reason);
      }

      // If we didn't receive an eventCode, we log a warning and return
      if (eventCode == null) {
        log.warn("No eventCode returned by " + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE);
        return null;
      }

      status = eventCode;
      if (eventCode.equals("AUTHORISATION")) {
        if (success) {
          status += " successful";
        } else {
          status += " unsuccessful";
        }
      }

      // Fill more details of the IPN history class
      ipnHistory.setGatewayResult(status);
      ipnHistory.setGatewayFullResponse(sb.toString());
      ipnHistory.setGatewayTransactionId(pspReference);

      /*
       * Get the uuid from the request so that we can look up the SSO Token
       */
      if (merchantReference == null) {
        throw new Exception(
            "The callback from BarclaycardSmartPayApi did not contain the 'merchantReference' parameter.");
      }

      // Get an instance of the KonaKart engine and look up the token
      kkAppEng = this.getKKAppEng(request, response);
      SSOTokenIf token = kkAppEng.getEng().getSSOToken(merchantReference, /* deleteToken */ true);
      if (token == null) {
        throw new Exception("The SSOToken from the BarclaycardSmartPayApi callback is null");
      }

      /*
       * Use the session of the logged in user to initialise kkAppEng
       */
      try {
        kkAppEng.getEng().checkSession(token.getSessionId());
      } catch (KKException e) {
        throw new Exception(
            "The SessionId from the SSOToken in the BarclaycardSmartPayApi Callback is not valid: "
                + token.getSessionId());
      }

      // Log in the user
      kkAppEng.getCustomerMgr().loginBySession(token.getSessionId());
      sessionId = token.getSessionId();

      /*
       * Get the parameters from the token
       */
      String custom1 = token.getCustom1();
      String[] custom1Array = custom1.split("~");
      if (custom1Array == null || custom1Array.length != 3) {
        throw new Exception(
            "Custom1 field of token doesn't contain expected data: " + token.getCustom1());
      }
      httpAuthStr = custom1Array[0];
      int orderId = Integer.parseInt(custom1Array[1]);
      String countryCode = custom1Array[2];
      httpUsername = token.getCustom2();
      httpPassword = token.getCustom3();

      if (countryCode == null) {
        log.warn(
            "CountryCode not returned in the "
                + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE
                + " response");
      }

      ipnHistory.setOrderId(orderId);

      // Do HTTP Authentication if required
      if (httpAuthStr != null && Boolean.valueOf(httpAuthStr)) {
        // Get Authorization header
        String auth = null;

        if (request != null) {
          auth = request.getHeader("Authorization");
        }

        // Do we allow that user?
        if (!allowUser(auth, httpUsername, httpPassword)) {
          // Not allowed, so return "unauthorized"
          response.setContentType("text/plain");
          response.setHeader("WWW-Authenticate", "BASIC realm=\"Protected Page\"");
          response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
          log.warn(
              "Notification from "
                  + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE
                  + " could not be Authenticated");

          ipnHistory.setKonakartResultDescription(RET2_DESC);
          ipnHistory.setKonakartResultId(RET2);
          kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
          return null;
        }
      }

      if (log.isDebugEnabled()) {
        log.debug("Accept Notification for " + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE);
      }

      // We always accept the Notification if we get this far
      response.setContentType("text/plain");
      response.getWriter().print("[accepted]\n");

      if (orderId < 0) {
        ipnHistory.setKonakartResultDescription(RET3_DESC);
        ipnHistory.setKonakartResultId(RET3);
        kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
        return null;
      }

      // If it's not an AUTHORISATION event, we just throw it away
      if (!eventCode.equals("AUTHORISATION")) {
        if (log.isInfoEnabled()) {
          log.info(
              "'"
                  + eventCode
                  + "' notification sent from "
                  + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE
                  + " discarded");
        }
        return null;
      }

      // If we're about to set the order status to the current value we'll assume this is a
      // duplicate Notification from Barclaycard and not do any updates

      int currentOrderStatus = kkAppEng.getEng().getOrderStatus(sessionId, orderId);

      if (log.isDebugEnabled()) {
        log.debug("currentOrderStatus for orderId " + orderId + " = " + currentOrderStatus);
      }

      if ((success && currentOrderStatus == com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS)
          || (!success && currentOrderStatus == com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS)) {
        if (log.isDebugEnabled()) {
          log.debug(
              "Possible Duplicate '"
                  + eventCode
                  + "' notification sent from "
                  + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE
                  + " discarded");
        }
        return null;
      }

      ipnHistory.setKonakartResultDescription(RET0_DESC);
      ipnHistory.setKonakartResultId(RET0);
      kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);

      return null;

    } catch (Exception e) {
      try {
        if (sessionId != null) {
          ipnHistory.setKonakartResultDescription(RET4_DESC);
          ipnHistory.setKonakartResultId(RET4);
          if (kkAppEng != null) {
            kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
          }
        }
      } catch (KKException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();
      return null;
    } finally {
      if (sessionId != null && kkAppEng != null) {
        try {
          kkAppEng.getEng().logout(sessionId);
        } catch (KKException e) {
          e.printStackTrace();
        }
      }
    }
  }
Exemple #27
0
 /**
  * Gets the text from the message catalog using place holders
  *
  * @param key
  * @param args
  * @return Gets the text from the message catalog
  */
 protected String getMsg(String key, String[] args) {
   return eng.getMsg(key, args);
 }
Exemple #28
0
 /**
  * Gets the text from the message catalog
  *
  * @param key
  * @param arg0
  * @param arg1
  * @param arg2
  * @return Gets the text from the message catalog
  */
 protected String getMsg(String key, String arg0, String arg1, String arg2) {
   return eng.getMsg(key, arg0, arg1, arg2);
 }
Exemple #29
0
 /**
  * Gets the text from the message catalog
  *
  * @param key
  * @param arg0
  * @return Gets the text from the message catalog
  */
 protected String getMsg(String key, String arg0) {
   return eng.getMsg(key, arg0);
 }
Exemple #30
0
 /**
  * Gets the text from the message catalog
  *
  * @param key
  * @return Gets the text from the message catalog
  */
 protected String getMsg(String key) {
   return eng.getMsg(key);
 }