public static synchronized File getProcessedFile(
      String resourceName, InputStream resourceInputStream) throws IOException {
    resourceName = resourceName.replace(".css", "_processed.css");
    resourceName = resourceName.substring(resourceName.lastIndexOf("/") + 1);
    File file =
        new File(
            CommonWorkingDirectory.PROCESSED_RESOURCES_DIR.getDirectoryPath(true) + resourceName);
    if (!file.exists() || ApplicationUtil.getAplosContextListener().isDebugMode()) {
      String lineSep = System.getProperty("line.separator");
      BufferedReader br = null;
      br = new BufferedReader(new InputStreamReader(resourceInputStream));

      String nextLine = "";
      StringBuffer sb = new StringBuffer();
      try {
        while ((nextLine = br.readLine()) != null) {
          sb.append(nextLine);
          sb.append(lineSep);
        }
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      String cssContent = sb.toString();
      String newCssContent =
          CommonUtil.includeContextRootInPathsForCss(cssContent, JSFUtil.getContextPath());
      FileOutputStream fileOutputStream = new FileOutputStream(file);
      fileOutputStream.write(newCssContent.getBytes());
      fileOutputStream.close();
    }
    return file;
  }
  @Override
  public String generateXhtml() {
    StringBuffer xhtmlBuffer = new StringBuffer();
    xhtmlBuffer.append("<ui:composition template=\"/templates/frontend.xhtml\"");
    xhtmlBuffer.append(" xmlns=\"http://www.w3.org/1999/xhtml\"");
    xhtmlBuffer.append(" xmlns:ui=\"http://java.sun.com/jsf/facelets\" ");
    if (getXmlNamespaceStr() != null) {
      xhtmlBuffer.append(getXmlNamespaceStr());
    }
    if (getXmlNamespaceStr() == null || !getXmlNamespaceStr().contains("xmlns:aplos")) {
      // need the aplos library for including menus invisibly
      xhtmlBuffer.append(" xmlns:aplos=\"http://www.aplossystems.co.uk/aplosComponents\" ");
    }
    if (getXmlNamespaceStr() == null || !getXmlNamespaceStr().contains("xmlns:h=")) {
      // need the h library for {_page_name} (becomes a h output text)
      xhtmlBuffer.append(" xmlns:h=\"http://java.sun.com/jsf/html\" ");
    }
    xhtmlBuffer.append(" >\n");
    // for ease of debugging

    xhtmlBuffer.append("<ui:define name='__templateInsertHead'>\n");
    if (getParentWebsite() != null) {
      String googleAnalyticsId = getParentWebsite().getGoogleAnalyticsId();
      if (!CommonUtil.isNullOrEmpty(googleAnalyticsId)) {
        Website.addGoogleAnalyticsCode(xhtmlBuffer, googleAnalyticsId);
      }
    }

    xhtmlBuffer.append("\n<ui:insert name=\"templateAtomHeadContent\" />\n");
    xhtmlBuffer.append("\n<ui:insert name=\"pageAtomHeadContent\" />\n");
    String contextPath = JSFUtil.getContextPath();
    String contextRootWithoutSlash = contextPath.replace("\\", "").replace("/", "");

    String headContent = CommonUtil.includeContextRootInPaths(contextRootWithoutSlash, getHead());
    // headContent = CmsModule.parseCmsContentTags(headContent);
    xhtmlBuffer.append(headContent);
    xhtmlBuffer.append("\n</ui:define>\n");
    xhtmlBuffer.append("<ui:define name='__templateInsertBody'>\n");
    String bodyContent = CommonUtil.includeContextRootInPaths(contextRootWithoutSlash, getBody());
    // bodyContent = CmsModule.parseCmsContentTags(bodyContent);
    xhtmlBuffer.append(bodyContent);
    xhtmlBuffer.append("\n</ui:define>\n");
    xhtmlBuffer.append("</ui:composition>\n");
    return xhtmlBuffer.toString();
  }
  public void sendEmail() {
    logger.debug("Entered send email method");
    if (CommonUtil.validateEmailAddressFormat(emailAddress)) {
      Subscriber subscriber = Subscriber.getOrCreateSubscriber(emailAddress);
      if (subscriber.isNew()) {
        String[] senderNameParts = getSenderName().split(" ");
        for (int i = 0, n = senderNameParts.length; i < n; i++) {
          if (i == 0) {
            subscriber.setFirstName(senderNameParts[i]);
          } else if (i == 1) {
            subscriber.setSurname(senderNameParts[i]);
          } else {
            subscriber.setSurname(subscriber.getSurname() + " " + senderNameParts[i]);
          }
        }
      }
      getContactFormSubmission().setSubscriber((Subscriber) subscriber.getSaveableBean());
      getContactFormSubmission().saveDetails();
      AplosEmail aplosEmail =
          new AplosEmail(
              CmsEmailTemplateEnum.CONTACT, getContactFormSubmission(), getContactFormSubmission());
      if (getContactFormSubmission().getAttachment() != null) {
        aplosEmail.addSaveableAttachment(getContactFormSubmission().getAttachment());
      }
      aplosEmail.setToAddress(
          CommonConfiguration.getCommonConfiguration()
              .getDefaultCompanyDetails()
              .getEmailAddress());
      if (isSendingDuplicateEmail()) {
        aplosEmail.addCcAddress(getContactFormSubmission().getEmailAddress());
      }
      if (aplosEmail.sendAplosEmailToQueue() != null) {
        setMessageSent(true);
        JSFUtil.addMessage("Thank you, your message has been sent.", FacesMessage.SEVERITY_INFO);

        aplosEmail =
            new AplosEmail(
                CmsEmailTemplateEnum.CONTACT,
                getContactFormSubmission(),
                getContactFormSubmission());
      } else {
        JSFUtil.addMessage("Sorry, your e-mail has not been sent.", FacesMessage.SEVERITY_WARN);
      }
    } else {
      JSFUtil.addMessage(
          "Sorry, your e-mail has not been sent. Please check your email address is correct.",
          FacesMessage.SEVERITY_WARN);
    }
  }
 public String generateXhtml(String contextRoot) {
   String contextRootWithoutSlash = contextRoot.replace("\\", "").replace("/", "");
   StringBuffer strBuf = new StringBuffer();
   // for ease of debugging
   String descriptionString = "";
   if (this.getDescription() != null && !this.getDescription().equals("")) {
     descriptionString = " (" + this.getDescription() + ")";
   }
   strBuf.append("// File: " + this.getName() + descriptionString + "\n");
   strBuf.append(
       "// Last Generated: "
           + FormatUtil.formatDate(FormatUtil.getEngSlashSimpleDateTimeFormat(), new Date())
           + "\n");
   strBuf.append(
       CommonUtil.includeContextRootInPathsForCss(getContent(), contextRootWithoutSlash));
   return strBuf.toString();
 }
 @Override
 public void addContentJDynamiTeValues(JDynamiTe jDynamiTe, Transaction transaction) {
   super.addContentJDynamiTeValues(jDynamiTe, transaction);
   jDynamiTe.setVariable(
       "CUSTOMER_FULLNAME", transaction.getEcommerceShoppingCart().getCustomer().getDisplayName());
   CompanyDetails companyDetails =
       CommonConfiguration.getCommonConfiguration().getDefaultCompanyDetails();
   jDynamiTe.setVariable("COMPANY_NAME", companyDetails.getAddress().getContactFirstName());
   if (companyDetails.getLogoDetails() != null) {
     jDynamiTe.setVariable("COMPANY_LOGO", companyDetails.getLogoDetails().getFilename());
   }
   jDynamiTe.setVariable("COMPANY_WEBSITE", companyDetails.getWeb());
   jDynamiTe.setVariable("ORDER_NUMBER", transaction.getId().toString());
   jDynamiTe.setVariable("DISPATCH_DATETIME", new Date().toString());
   String shippingMethodName = "";
   if (transaction.getEcommerceShoppingCart().getAvailableShippingService() != null) {
     shippingMethodName =
         transaction
             .getEcommerceShoppingCart()
             .getAvailableShippingService()
             .getCachedServiceName();
   }
   jDynamiTe.setVariable("SHIPPING_METHOD_NAME", shippingMethodName);
   jDynamiTe.setVariable(
       "SHIPPING_ADDRESS_STRING", transaction.getShippingAddress().getAddressString());
   jDynamiTe.setVariable("ORDER_STATUS", transaction.getTransactionStatus().getLabel());
   List<ShoppingCartItem> shoppingCartItems = transaction.getEcommerceShoppingCart().getItems();
   for (int i = 0, n = shoppingCartItems.size(); i < n; i++) {
     EcommerceShoppingCartItem shoppingItem = (EcommerceShoppingCartItem) shoppingCartItems.get(i);
     jDynamiTe.setVariable(
         "PRODUCT_CODE_REPEATED", CommonUtil.getStringOrEmpty(shoppingItem.getItemCode()));
     jDynamiTe.setVariable("PRODUCT_SIZE_REPEATED", shoppingItem.getProductSize());
     jDynamiTe.setVariable("PRODUCT_BRAND_AND_NAME_REPEATED", shoppingItem.getItemName());
     jDynamiTe.setVariable(
         "PRODUCT_QUANTITY_REPEATED", FormatUtil.formatTwoDigit(shoppingItem.getQuantity()));
     jDynamiTe.parseDynElem("productList");
   }
   jDynamiTe.setVariable(
       "COMPLETE_OR_CONTINUE",
       "This dispatch completes your order. We hope you will be very happy with your purchases.");
   jDynamiTe.setVariable("PART_OR_Y", "Y");
 }
  @Override
  public boolean responsePageLoad() {
    super.responsePageLoad();

    JSFUtil.getResponse().setStatus(500);
    FacesContext ctx = FacesContext.getCurrentInstance();
    Throwable throwable = null;
    if (ctx.getExternalContext().getRequestMap().containsKey(SERVLET_EXCEPTION_KEY)) {
      throwable =
          (Throwable) ctx.getExternalContext().getRequestMap().remove(SERVLET_EXCEPTION_KEY);
    } else if (ctx.getExternalContext().getSessionMap().containsKey(SERVLET_EXCEPTION_KEY)) {
      throwable =
          (Throwable) ctx.getExternalContext().getSessionMap().remove(SERVLET_EXCEPTION_KEY);
    }

    if (throwable != null) {
      JSFUtil.addToTabSession(
          AplosScopedBindings.TECHNICAL_DETAILS, CommonUtil.createStackTraceString(throwable));
      //			if( !aplosContextListener.isDebugMode() ) {
      //				ErrorEmailSender.sendErrorEmail(aplosContextListener,throwable);
      //			}
    }
    return true;
  }
  @Override
  public Boolean executeCall() throws Exception {

    String[] cols = {
      "Category",
      "Manufacturer", // * fields marked with * are mandatory and MUST be filled in
      "Title", // *
      "Product Description", //
      "Link", // *
      "Image", //
      "SKU", // *
      "Stock", //  they only update the feed every 2-3 days
      "Condition", //  New, Open Box, Refurbished, OEM, Used
      "Shipping Weight", //  in pounds
      "Shipping Cost", //  expects lowest available, value not required but useful if free shipping
                       // offered
      "Bid",
      "Promotional Description",
      "EAN/UPC", //  only really applies to entertainment goods
      "Price" // *
    };
    List<String[]> rows = new ArrayList<String[]>();
    BeanDao realizedProductDao = new BeanDao(RealizedProduct.class);
    if (EcommerceConfiguration.getEcommerceSettingsStatic().isProductListGroupByColour()) {
      realizedProductDao.setWhereCriteria("bean.productInfo.defaultRealizedProduct.id=bean.id");
    }
    realizedProductDao.addWhereCriteria("bean.productInfo.product.isShowingOnWebsite=1");
    List<RealizedProduct> realizedProducts =
        realizedProductDao.setIsReturningActiveBeans(true).getAll();
    Map<ProductInfo, ArrayList<ProductColour>> coloursCovered =
        new HashMap<ProductInfo, ArrayList<ProductColour>>();
    for (RealizedProduct realizedProduct : realizedProducts) {
      if (!EcommerceConfiguration.getEcommerceSettingsStatic().isProductListGroupByColour()) {
        ArrayList<ProductColour> currentColours =
            coloursCovered.get(realizedProduct.getProductInfo());
        if (currentColours == null) {
          currentColours = new ArrayList<ProductColour>();
        }
        if (!currentColours.contains(realizedProduct.getProductColour())) {
          currentColours.add(realizedProduct.getProductColour());
          coloursCovered.put(realizedProduct.getProductInfo(), currentColours);
        } else {
          // we dont want multiple where there are several sizes for this
          // colour/p.info combination
          continue;
        }
      }
      List<ProductType> productTypes =
          realizedProduct.getProductInfo().getProduct().getProductTypes();
      String category = "Misc.";
      String typeForUrl = null;
      for (ProductType type : productTypes) {
        typeForUrl = type.getMapping();
        if (typeForUrl == null || typeForUrl.equals("")) {
          typeForUrl = type.getMapping();
          if (typeForUrl == null || typeForUrl.equals("")) {
            typeForUrl = CommonUtil.makeSafeUrlMapping(type.getName());
          }
        }
      }

      String manufacturerName;
      // ordinarily we would use something like 'menswear' or 'sportswear' here not brand but
      // we cant determine it here so need to improvise to keep correct format and still make sense
      // to a user (for seo)
      String manufacturerNameForUrl;
      if (realizedProduct.getProductInfo().getProduct().getProductBrand() != null) {
        manufacturerName =
            realizedProduct.getProductInfo().getProduct().getProductBrand().getMapping();
        if (manufacturerName == null || manufacturerName.equals("")) {
          manufacturerName =
              realizedProduct.getProductInfo().getProduct().getProductBrand().getName();
        }
        manufacturerNameForUrl = CommonUtil.makeSafeUrlMapping(manufacturerName);
      } else {
        manufacturerName = "";
        manufacturerNameForUrl = CommonUtil.makeSafeUrlMapping(websiteName);
      }
      String title = realizedProduct.getProductInfo().getProduct().getName();
      String productDescription =
          CommonUtil.getStringOrEmpty(realizedProduct.getProductInfo().getShortDescription());
      if (!serverUrl.startsWith("http")) {
        serverUrl = "http://" + serverUrl;
      }
      if (!serverUrl.endsWith("/")) {
        serverUrl = serverUrl + "/";
      }
      if (contextPath.startsWith("/")) {
        contextPath = contextPath.substring(1);
      }
      if (!contextPath.endsWith("/")) {
        contextPath = contextPath + "/";
      }
      String serverContext = serverUrl + contextPath;
      serverContext = serverContext.replaceAll("//", "/");
      serverContext = serverContext.replaceAll("http:/", "http://");
      String urlToProductView =
          serverContext
              + manufacturerNameForUrl
              + "/"
              + typeForUrl
              + "/"
              + realizedProduct.getProductInfo().getMappingOrId()
              + ".aplos?type=product";
      String imageDetailsId = "missing";
      FileDetails largeImage = realizedProduct.getImageDetailsByKey("LARGE_IMAGE");
      if (largeImage != null) {
        imageDetailsId = String.valueOf(largeImage.getId());
      } else if (realizedProduct.getDefaultImageDetails() != null) {
        imageDetailsId = String.valueOf(realizedProduct.getDefaultImageDetails().getId());
      } else if (realizedProduct.getImageDetailsList() != null
          && realizedProduct.getImageDetailsList().size() > 0) {
        imageDetailsId = String.valueOf(realizedProduct.getImageDetailsList().get(0).getId());
      }

      String urlToImage = "";
      if (!imageDetailsId.equals("missing")) {
        urlToImage =
            serverContext
                + "media/?filename=realizedProductImages/"
                + imageDetailsId
                + "_large.jpg&provideDefaultIfMissing=true";
      }

      String sku = realizedProduct.determineItemCode();
      if (sku == null || sku.equals("")) {
        // not all sites use item codes but we have to pass one, so invent one
        sku = realizedProduct.getProductInfo().getId() + "SKU";
        sku += realizedProduct.getId();
        if (!EcommerceConfiguration.getEcommerceSettingsStatic().isProductListGroupByColour()
            && realizedProduct.getProductColour() != null) {
          sku += "C" + realizedProduct.getProductColour().getId();
        }
      }
      String stock = "";
      String condition = "New";
      String shippingWeight = FormatUtil.formatTwoDigit(realizedProduct.determineWeight());
      // there's way too many factors to consider for shipping cost, so i'm only going to pass a
      // value
      String shippingCost = "";
      if (isFreeShippingAvailable(realizedProduct.getProductInfo())) {
        shippingCost = "0";
      }
      String bid = "";
      String promotionalDescription = "";
      String eanUpc =
          String.valueOf(
              realizedProduct
                  .getProductInfo()
                  .getId()); // we might want to use isbn etc if this were a book
      String price;
      if (realizedProduct.getSitewideDiscount() != null) {
        price =
            FormatUtil.formatTwoDigit(
                realizedProduct
                    .getPrice()
                    .subtract(
                        realizedProduct
                            .getPrice()
                            .divide(new BigDecimal(100))
                            .multiply(realizedProduct.getSitewideDiscount())));
      } else {
        price = realizedProduct.getPriceStr();
      }
      rows.add(
          new String[] {
            category,
            manufacturerName,
            title,
            productDescription,
            urlToProductView,
            urlToImage,
            sku,
            stock,
            condition,
            shippingWeight,
            shippingCost,
            bid,
            promotionalDescription,
            eanUpc,
            price
          });
    }
    try {
      // this is relative to webroot - so that it can be accessed as a feed
      String filename = "tab-delimited-feed.txt";
      FileIoUtil.generateTabDelimitedFile(filename, cols, rows);
    } catch (InputMismatchException ime) {
      ime.printStackTrace();
    }
    return true;
  }