/**
  * @see atg.servlet.DynamoServlet#service(atg.servlet.DynamoHttpServletRequest,
  *     atg.servlet.DynamoHttpServletResponse)
  */
 public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
     throws ServletException, IOException {
   if (getReferrerProgramConfig().isReferrerProgrameActive()) {
     pRequest.serviceLocalParameter("true", pRequest, pResponse);
   } else {
     pRequest.serviceLocalParameter("false", pRequest, pResponse);
   }
 }
  /**
   * Builds the complete URL string for the Endeca-produced action object. The action can be
   * represented either by NavigationAction, RecordAction or UrlAction.
   */
  @Override
  public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
      throws ServletException, IOException {

    // Take Action object from the request
    Action action = (Action) pRequest.getObjectParameter(ACTION);

    StringBuilder actionURL = new StringBuilder();

    if (action != null) {

      // Check the type of the action
      if (action instanceof NavigationAction) {

        // NavigationAction case
        actionURL.append(pRequest.getContextPath());
        actionURL.append(action.getContentPath());
        String navigationState = ((NavigationAction) action).getNavigationState();
        if (navigationState != null) {
          actionURL.append(navigationState);
        }
      } else {
        if (action instanceof RecordAction) {

          // RecordAction case
          actionURL.append(pRequest.getContextPath());
          actionURL.append(action.getContentPath());
          String recordState = ((RecordAction) action).getRecordState();
          if (recordState != null) {
            actionURL.append(recordState);
          }
        } else {
          if (action instanceof UrlAction) {

            // UrlAction case
            String url = ((UrlAction) action).getUrl();
            if (url.startsWith(URL_SEPARATOR)) {
              actionURL.append(pRequest.getContextPath());
            }
            actionURL.append(((UrlAction) action).getUrl());
          }
        }
      }

      // If action's URL is not empty pass it through output parameter
      if (actionURL.length() > 0) {
        pRequest.setParameter(ACTION_URL, actionURL.toString());
        pRequest.serviceLocalParameter(OUTPUT, pRequest, pResponse);
        return;
      }
    }

    // Action's URL is empty, render empty oparam
    pRequest.serviceLocalParameter(EMPTY, pRequest, pResponse);
  }
  /**
   * This droplet transforms specified url according to the selected type of processing, that is
   * declared through "operation"-parameter.<br>
   * If operation isn't defined, droplet by default will add or replace request parameter value.<br>
   */
  @Override
  public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
      throws ServletException, IOException {

    String operation = (String) pRequest.getLocalParameter(PARAM_OPERATION);
    if (operation == null) {
      operation = OPERATION_DEFAULT;
    }

    String url = (String) pRequest.getLocalParameter(PARAM_URL);
    String result = url;

    if (url != null && !url.isEmpty()) {
      if (OPERATION_ADD_OR_REPLACE_PARAMETER.equals(operation)) {
        String param = (String) pRequest.getLocalParameter(PARAM_NAME);

        if (param != null) {
          Object newValueObj = pRequest.getLocalParameter(PARAM_VALUE);
          String newValue = newValueObj != null ? newValueObj.toString() : "";

          String[] parts = url.split(param + "=");

          // if parameter is presented in url,
          // replace it's value to the new one
          if (parts != null && parts.length > 1) {
            String oldValue;
            int index = parts[1].indexOf("&");

            // parameter isn't last
            if (index != -1) {
              oldValue = parts[1].substring(0, index);
            } else {
                /* parameter is last */
              oldValue = parts[1];
            }

            result = url.replaceAll(param + "=" + oldValue, param + "=" + newValue);
          } else {
            // parameter is absent in url
            // add new parameter with a specified value
            String sep = (parts[0].indexOf("=") == -1 ? "?" : "&");
            result = url + sep + param + "=" + newValue;
          }
        }
      }
    }

    pRequest.setParameter(ELEMENT, result);
    pRequest.serviceLocalParameter(OUTPUT_OPARAM, pRequest, pResponse);
  }
 /** Called to execute this droplet */
 @Override
 public void service(
     final DynamoHttpServletRequest request, final DynamoHttpServletResponse response)
     throws ServletException, IOException {
   logInfo("Starting: " + this.getClass().getName());
   request.serviceLocalParameter(ParameterName.getParameterName("output"), request, response);
   request.setParameter("entry", "The Value");
   response.getOutputStream().write("Some content from the simple droplet".getBytes());
   mUsername = request.getParameter(USERNAME);
   // try to read data from the client if it is available
   if ("POST".equals(request.getMethod())) {
     ServletInputStream s = request.getInputStream();
     Properties p = new Properties();
     p.load(s);
     mUsernameFromInputStream = p.getProperty(USERNAME);
   }
 }
  /**
   * Calculate percent and discount of the product.
   *
   * @param pRequest - dynamo http request
   * @param pResponse - dynamo http response
   * @throws IOException - exception
   * @throws ServletException - exception
   */
  public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
      throws ServletException, IOException {
    BigDecimal listPrice = null;
    BigDecimal salePrice = null;
    BigDecimal cardPrice = null;
    try {
      listPrice = new BigDecimal("" + pRequest.getObjectParameter(LIST_PRICE));
    } catch (NumberFormatException ex) {
      if (isLoggingError())
        logError(
            "NumberFormatException: Please check list_price param: "
                + pRequest.getObjectParameter(LIST_PRICE));
    }
    try {
      salePrice = new BigDecimal("" + pRequest.getObjectParameter(SALE_PRICE));
    } catch (NumberFormatException ex) {
      if (isLoggingError())
        logError(
            "NumberFormatException: Please check sale_price param: "
                + pRequest.getObjectParameter(SALE_PRICE));
    }
    Object showCardPriceObj = pRequest.getObjectParameter(SHOW_CAST_CARD_PRICE);
    Object enabledCastCartObj = pRequest.getObjectParameter(ENABLED_CAST_CART);
    Object storeIsLocalObj = pRequest.getObjectParameter(STORE_IS_LOCAL);
    Object reqPrice = pRequest.getObjectParameter(CARD_PRICE);
    cardPrice = (reqPrice != null) ? new BigDecimal(reqPrice.toString()) : null;
    Boolean showCardPrice = (showCardPriceObj != null) ? (Boolean) showCardPriceObj : false;
    Boolean enabledCastCart = (enabledCastCartObj != null) ? (Boolean) enabledCastCartObj : false;
    Boolean storeIsLocal = (storeIsLocalObj != null) ? (Boolean) storeIsLocalObj : false;

    Map<String, Object> outputParams =
        getDropletsPricingTools()
            .calculateForCastPriceDroplet(
                listPrice, salePrice, cardPrice, showCardPrice, enabledCastCart, storeIsLocal);
    getDropletsPricingTools().putParamsToRequest(pRequest, outputParams);
    pRequest.serviceLocalParameter(OUTPUT, pRequest, pResponse);
  }
  /**
   * Extends service method of DynamoServlet to returns payment amounts by gift card and credit
   * card.
   *
   * @see atg.servlet.DynamoServlet#service(atg.servlet.DynamoHttpServletRequest,
   *     atg.servlet.DynamoHttpServletResponse)
   */
  @Override
  public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
      throws ServletException, IOException {

    boolean isEmpty = true;
    String paymentMethod = pRequest.getParameter(PAYMENT_METHOD);
    if (null != paymentMethod && 0 < paymentMethod.trim().length()) {
      List<OrderPaymentElement> elements = new ArrayList<OrderPaymentElement>();
      if (paymentMethod.equalsIgnoreCase("Call-Center")) {
        elements.add(new OrderPaymentElement("Téléphone", "en attente de paiement", null));
      } else if (paymentMethod.equalsIgnoreCase("Virement")) {
        elements.add(new OrderPaymentElement("Virement Bancaire", "en attente de paiement", null));
      } else if (paymentMethod.equalsIgnoreCase("Cheque")) {
        elements.add(new OrderPaymentElement("Chèque", "en attente de paiement", null));
      } else if (paymentMethod.equalsIgnoreCase("Atout")) {
        String orderId = pRequest.getParameter(ORDER_ID);
        Repository repository = getRepository();
        long sofincoAmount = 0;
        if (null != repository) {
          try {
            RepositoryView logsipsView = repository.getView(LOG_SIPS);
            QueryBuilder queryBuilder = logsipsView.getQueryBuilder();
            QueryExpression propertyQuery =
                queryBuilder.createPropertyQueryExpression(PROPERTTY_ORDER_ID);
            QueryExpression valueQuery = queryBuilder.createConstantQueryExpression(orderId);
            Query query =
                queryBuilder.createComparisonQuery(propertyQuery, valueQuery, QueryBuilder.EQUALS);
            RepositoryItem[] logsipsItems = logsipsView.executeQuery(query);
            String paymentType;
            String responseCode;
            Integer amount;
            if (null != logsipsItems && 0 < logsipsItems.length) {
              for (RepositoryItem logsipsItem : logsipsItems) {
                responseCode = (String) logsipsItem.getPropertyValue(PROPERTTY_RESPONSE_CODE);
                if (isErrorCodeOK(responseCode)) {
                  amount = (Integer) logsipsItem.getPropertyValue(PROPERTTY_AMOUNT);
                  if (null != amount) {
                    paymentType = (String) logsipsItem.getPropertyValue(PROPERTTY_PAYMENT_TYPE);
                    if ("SOFINCO".equalsIgnoreCase(paymentType)) {
                      sofincoAmount += amount;
                    }
                  }
                }
              }
            }
          } catch (Exception e) {
            if (isLoggingError()) {
              logError(e);
            }
          }
        }
        elements.add(
            new OrderPaymentElement(
                CARTE_CASTORAMA_PAYMENT_TYPE, null, new Double(sofincoAmount / 100.0)));
      } else {
        String orderId = pRequest.getParameter(ORDER_ID);
        Repository repository = getRepository();
        long giftAmount = 0;
        long blueAmount = 0;
        long visaAmount = 0;
        long amexAmount = 0;
        long euroAmount = 0;
        if (null != repository) {
          try {
            RepositoryView logsipsView = repository.getView(LOG_SIPS);
            QueryBuilder queryBuilder = logsipsView.getQueryBuilder();
            QueryExpression propertyQuery =
                queryBuilder.createPropertyQueryExpression(PROPERTTY_ORDER_ID);
            QueryExpression valueQuery = queryBuilder.createConstantQueryExpression(orderId);
            Query query =
                queryBuilder.createComparisonQuery(propertyQuery, valueQuery, QueryBuilder.EQUALS);
            RepositoryItem[] logsipsItems = logsipsView.executeQuery(query);
            String paymentType;
            String responseCode;
            Integer amount;
            if (null != logsipsItems && 0 < logsipsItems.length) {
              for (RepositoryItem logsipsItem : logsipsItems) {
                responseCode = (String) logsipsItem.getPropertyValue(PROPERTTY_RESPONSE_CODE);
                if (isErrorCodeOK(responseCode)) {
                  amount = (Integer) logsipsItem.getPropertyValue(PROPERTTY_AMOUNT);
                  if (null != amount) {
                    paymentType = (String) logsipsItem.getPropertyValue(PROPERTTY_PAYMENT_TYPE);
                    if ("SVS".equalsIgnoreCase(paymentType)) {
                      giftAmount += amount;
                    } else if ("CB".equalsIgnoreCase(paymentType)) {
                      blueAmount += amount;
                    } else if ("VISA".equalsIgnoreCase(paymentType)) {
                      visaAmount += amount;
                    } else if ("AMEX".equalsIgnoreCase(paymentType)) {
                      amexAmount += amount;
                    } else if ("EUROCARD_MASTERCARD".equalsIgnoreCase(paymentType)) {
                      euroAmount += amount;
                    } else if ("MASTERCARD".equalsIgnoreCase(paymentType)) {
                      euroAmount += amount;
                    }
                  }
                }
              }
            }
            if (0 != giftAmount) {
              elements.add(
                  new OrderPaymentElement(
                      CARTE_CADEAU_PAYMENT_TYPE, null, new Double(giftAmount / 100.0)));
            }
            if (0 != blueAmount) {
              elements.add(
                  new OrderPaymentElement(
                      CARTE_BLEUE_PAYMENT_TYPE, null, new Double(blueAmount / 100.0)));
            }
            if (0 != visaAmount) {
              elements.add(
                  new OrderPaymentElement(
                      CARTE_VISA_PAYMENT_TYPE, null, new Double(visaAmount / 100.0)));
            }
            if (0 != amexAmount) {
              elements.add(
                  new OrderPaymentElement(
                      CARTE_AMERICAN_EXPRESS_PAYMENT_TYPE, null, new Double(amexAmount / 100.0)));
            }
            if (0 != euroAmount) {
              elements.add(
                  new OrderPaymentElement(
                      CARTE_EUROCARD_MASTERCARD_PAYMENT_TYPE,
                      null,
                      new Double(euroAmount / 100.0)));
            }

          } catch (Exception e) {
            if (isLoggingError()) {
              logError(e);
            }
          }
        }
      }

      int count = 0;
      if (0 < elements.size()) {
        pRequest.setParameter(SIZE, elements.size());
        pRequest.serviceLocalParameter(OUTPUT_START, pRequest, pResponse);
        Iterator<OrderPaymentElement> iterator = elements.iterator();
        while (iterator.hasNext()) {
          pRequest.setParameter(INDEX, count);
          OrderPaymentElement element = iterator.next();
          pRequest.setParameter(PAYMENT_TYPE, element.type);
          pRequest.setParameter(PAYMENT_DESCRIPTION, element.description);
          pRequest.setParameter(PAYMENT_AMOUNT, element.amount);
          pRequest.serviceLocalParameter(OUTPUT, pRequest, pResponse);
          count++;
        }
        pRequest.serviceLocalParameter(OUTPUT_END, pRequest, pResponse);
        isEmpty = false;
      }
    }
    if (isEmpty) {
      pRequest.serviceLocalParameter(EMPTY, pRequest, pResponse);
    }
  }
  /**
   * Forms correct trails for ajouters(pop-ups). Save ajouter's trail as map :ajouter id to trail.
   * If trail is empty or contains only one value(case for product listing (we don't show pivot
   * category facet at the UI)) so no one facet value was selected, so re-running search for pop-up
   * isn't necessary. the same situation for question parameter(search re-run isn't necessary).
   *
   * @param pRequest dynamo http request
   * @param pResponse dynamo http response
   * @throws ServletException
   * @throws IOException
   */
  public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
      throws ServletException, IOException {
    try {
      if (PerformanceMonitor.isEnabled()) {
        PerformanceMonitor.startOperation("search", "TEST:FacetedSearchPopUpFinder.service");
      }
      String initialTrail = pRequest.getParameter(TRAIL);

      if ((getCommerceFacetTrailTools() != null)
          && !StringUtils.isBlank(initialTrail)
          && (initialTrail.indexOf(":") != initialTrail.lastIndexOf(":"))) {
        List<FacetValue> trails =
            getCommerceFacetTrailTools().parseFacetValueString(initialTrail, null);

        Map<String, ArrayList<String>> facetIdToFacetValues =
            new HashMap<String, ArrayList<String>>();

        String firstSafeFacet;

        /*
         * pivot category || SRCH facet || root catgory facet - should stay the same; if this facet will be multiple
         * (facetId:facetValue1|facetValue2|...) So do check, the reason of this is .getTrailString() method returns
         * not correct value
         */
        if (trails.get(0) instanceof DisjunctionMultiValue) {
          firstSafeFacet = trails.get(0).toString();
          trails.remove(0);
        } else {
          firstSafeFacet = trails.get(0).getTrailString();
          trails.remove(0);
        }

        if (trails != null) {
          for (FacetValue fv : trails) {
            facetIdToFacetValues.put(fv.getFacet().getId(), new ArrayList());
          }

          for (FacetValue fv : trails) {
            if (facetIdToFacetValues.get(fv.getFacet().getId()) != null) {
              if (fv instanceof DisjunctionMultiValue) {
                ((ArrayList) facetIdToFacetValues.get(fv.getFacet().getId())).add(fv.toString());
              } else {
                ((ArrayList) facetIdToFacetValues.get(fv.getFacet().getId()))
                    .add(fv.getTrailString());
              }
            }
          }
          Map<String, String> resultedMapFacetIdToTrail = new HashMap<String, String>();

          // trails for queries
          for (Map.Entry<String, ArrayList<String>> excludedFacet :
              facetIdToFacetValues.entrySet()) {
            StringBuffer inludedFacetsSB = new StringBuffer();

            for (Map.Entry<String, ArrayList<String>> inludedFacets :
                facetIdToFacetValues.entrySet()) {
              if (!excludedFacet.getKey().equalsIgnoreCase(inludedFacets.getKey())) {
                for (String str : inludedFacets.getValue()) {
                  inludedFacetsSB.append(str).append(":");
                }
              }
            }

            // prepend first facet value (srch || pivot || root category)
            inludedFacetsSB.insert(0, ":").insert(0, firstSafeFacet);

            // delete extra last ":"
            if (inludedFacetsSB.lastIndexOf(":") == (inludedFacetsSB.length() - 1)) {
              inludedFacetsSB.replace(
                  inludedFacetsSB.lastIndexOf(":"), inludedFacetsSB.length(), "");
            }

            resultedMapFacetIdToTrail.put(excludedFacet.getKey(), inludedFacetsSB.toString());
          } // end for

          pRequest.setParameter(RESULTED_MAP_FACET_ID_TO_TRAIL, resultedMapFacetIdToTrail);
        } // end if
      } // end if
    } finally {
      if (PerformanceMonitor.isEnabled()) {
        PerformanceMonitor.endOperation("search", "TEST:FacetedSearchPopUpFinder.service");
      }
    } // end try-finally
    pRequest.serviceLocalParameter(OUTPUT, pRequest, pResponse);
  }