<p>Write PDF report for given invoice to output stream.</p>
@param pReqVars additional param
@param pInvoice Invoice
@param pRequestData Request Data
@param pOus servlet output stream
@throws Exception - an exception
519665
@Override
  public final void makeReport(final Map<String, Object> pReqVars,
    final SalesInvoice pInvoice, final IRequestData pRequestData,
      final OutputStream pOus) throws Exception {
    AccSettings accSet = this.srvAccSettings.lazyGetAccSettings(pReqVars);
    String lang = (String) pReqVars.get("lang");
    String langDef = (String) pReqVars.get("langDef");
    DateFormat dateFormat = DateFormat
      .getDateInstance(DateFormat.MEDIUM, new Locale(lang));
    SalesInvoice inv = retrieveEntity(pReqVars, pInvoice, lang,
      !lang.equals(langDef));
    boolean isInvoiceBasis = false;
    for (SalesInvoiceTaxLine itl : inv.getTaxesLines()) {
      if (itl.getTaxableInvBas().compareTo(BigDecimal.ZERO) == 1) {
        isInvoiceBasis = true;
        break;
      }
    }
    Currency currency;
    if (inv.getForeignCurrency() != null) {
      currency = inv.getForeignCurrency();
    } else {
      currency = accSet.getCurrency();
    }
    String priceName;
    if (inv.getPriceIncTax()) {
      priceName = "priceIncTax";
    } else {
      priceName = "itsPrice";
    }
    I18nCurrency i18nCurrency = null;
    String curSign;
    boolean isPrnCurLf;
    if (!lang.equals(langDef)) {
      List<I18nCurrency> i18nCurrencyLst = this.srvOrm.retrieveList(
        pReqVars, I18nCurrency.class);
      for (I18nCurrency i18nCur : i18nCurrencyLst) {
        if (i18nCur.getHasName().getItsId().equals(currency.getItsId())
          && i18nCur.getLang().getItsId().equals(lang)) {
          i18nCurrency = i18nCur;
          break;
        }
      }
    }
    if (i18nCurrency != null) {
      isPrnCurLf = i18nCurrency.getPrintCurrencyLeft();
      if (i18nCurrency.getUseCurrencySign()) {
        curSign = i18nCurrency.getHasName().getItsSign();
      } else {
        curSign = " " + i18nCurrency.getItsName() + " ";
      }
    } else {
      isPrnCurLf = accSet.getPrintCurrencyLeft();
      if (accSet.getUseCurrencySign()) {
        curSign = currency.getItsSign();
      } else {
        curSign = " " + currency.getItsName() + " ";
      }
    }
    Document<WI> doc = this.pdfFactory.lazyGetFctDocument()
      .createDoc(accSet.getPageSize(), accSet.getPageOrientation());
    doc.setFontSize(accSet.getFontSize());
    doc.getPages().get(0).setMarginBottom(accSet.getMarginBottom());
    doc.getPages().get(0).setMarginTop(accSet.getMarginTop());
    doc.getPages().get(0).setMarginLeft(accSet.getMarginLeft());
    doc.getPages().get(0).setMarginRight(accSet.getMarginRight());
    PdfDocument<WI> docPdf = this.pdfFactory.createPdfDoc(doc);
    IDocumentMaker<WI> docMaker = this.pdfFactory.lazyGetDocumentMaker();
    docPdf.getPdfInfo().setAuthor("Beigesoft (TM) Accounting, "
      + accSet.getOrganization());
    IPdfMaker<WI> pdfMaker = this.pdfFactory.lazyGetPdfMaker();
    if (accSet.getTtfBoldFileName() != null) {
      pdfMaker.addFontTtf(docPdf, accSet.getTtfBoldFileName());
    }
    pdfMaker.addFontTtf(docPdf, accSet.getTtfFileName());
    double widthNdot = this.pdfFactory.lazyGetUomHelper()
      .fromPoints(2.0, 300.0, doc.getUnitOfMeasure()); //printer resolution
    doc.setBorder(widthNdot);
    doc.setContentPadding(0.0);
    doc.setContentPaddingBottom(mmToDocUom(1.0, doc.getUnitOfMeasure()));
    DocTable<WI> tblOwner = docMaker.addDocTableNoBorder(doc, 1, 1);
    I18nAccounting i18nAccounting =
      (I18nAccounting) pReqVars.get("i18nAccounting");
    if (i18nAccounting != null) {
      tblOwner.getItsCells().get(0)
        .setItsContent(i18nAccounting.getOrganizationName());
    } else {
      tblOwner.getItsCells().get(0).setItsContent(accSet.getOrganization());
    }
    int n = 0;
    if (accSet.getTaxIdentificationNumber() != null) {
      docMaker.addRowToDocTable(tblOwner);
      tblOwner.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("taxIdentificationNumber", lang) + ": "
          + accSet.getTaxIdentificationNumber());
    }
    if (accSet.getRegZip() != null) {
      docMaker.addRowToDocTable(tblOwner);
      tblOwner.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regZip", lang) + ": " + accSet.getRegZip());
    }
    String addr = null;
    if (i18nAccounting != null) {
      addr = i18nAccounting.getRegAddress1();
    } else {
      addr = accSet.getRegAddress1();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblOwner);
      tblOwner.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regAddress1", lang) + ": " + addr);
    }
    if (i18nAccounting != null) {
      addr = i18nAccounting.getRegAddress2();
    } else {
      addr = accSet.getRegAddress2();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblOwner);
      tblOwner.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regAddress2", lang) + ": " + addr);
    }
    if (i18nAccounting != null) {
      addr = i18nAccounting.getRegCity();
    } else {
      addr = accSet.getRegCity();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblOwner);
      tblOwner.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regCity", lang) + ": " + addr);
    }
    if (i18nAccounting != null) {
      addr = i18nAccounting.getRegState();
    } else {
      addr = accSet.getRegState();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblOwner);
      tblOwner.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regState", lang) + ": " + addr);
    }
    if (i18nAccounting != null) {
      addr = i18nAccounting.getRegCountry();
    } else {
      addr = accSet.getRegCountry();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblOwner);
      tblOwner.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regCountry", lang) + ": " + addr);
    }
    tblOwner.getItsCells().get(0).setFontNumber(1);
    docMaker.makeDocTableWrapping(tblOwner);
    tblOwner.setAlignHorizontal(EAlignHorizontal.RIGHT);
    DocTable<WI> tblTitle = docMaker.addDocTableNoBorder(doc, 1, 1);
    String invNum;
    if (inv.getIdBirth() != null) {
      invNum = inv.getIdDatabaseBirth().toString() + "-"
        + inv.getIdBirth();
    } else {
      invNum = inv.getIdDatabaseBirth().toString() + "-"
        + inv.getItsId();
    }
    String title = this.srvI18n.getMsg("Invoice", lang) + " #" + invNum + ", "
      + this.srvI18n.getMsg("date", lang) + ": "
        + dateFormat.format(inv.getItsDate());
    tblTitle.getItsCells().get(0).setItsContent(title);
    tblTitle.getItsCells().get(0).setFontNumber(1);
    tblTitle.setAlignHorizontal(EAlignHorizontal.CENTER);
    doc.setContainerMarginBottom(mmToDocUom(1.0, doc.getUnitOfMeasure()));
    docMaker.makeDocTableWrapping(tblTitle);
    DocTable<WI> tblCustomer = docMaker.addDocTableNoBorder(doc, 1, 1);
    I18nBuyer i18nBuyer = null;
    if (!lang.equals(langDef)) {
      i18nBuyer = getSrvOrm().retrieveEntityById(pReqVars,
        I18nBuyer.class, inv.getCustomer());
    }
    if (i18nBuyer != null) {
      tblCustomer.getItsCells().get(0)
        .setItsContent(i18nBuyer.getItsName());
    } else {
      tblCustomer.getItsCells().get(0)
        .setItsContent(inv.getCustomer().getItsName());
    }
    n = 0;
    if (inv.getCustomer().getTaxIdentificationNumber() != null) {
      docMaker.addRowToDocTable(tblCustomer);
      tblCustomer.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("taxIdentificationNumber", lang) + ": "
          + inv.getCustomer().getTaxIdentificationNumber());
    }
    if (inv.getCustomer().getRegZip() != null) {
      docMaker.addRowToDocTable(tblCustomer);
      tblCustomer.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regZip", lang) + ": " + inv.getCustomer().getRegZip());
    }
    if (i18nBuyer != null) {
      addr = i18nBuyer.getRegAddress1();
    } else {
      addr = inv.getCustomer().getRegAddress1();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblCustomer);
      tblCustomer.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regAddress1", lang) + ": " + addr);
    }
    if (i18nBuyer != null) {
      addr = i18nBuyer.getRegAddress2();
    } else {
      addr = inv.getCustomer().getRegAddress2();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblCustomer);
      tblCustomer.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regAddress2", lang) + ": " + addr);
    }
    if (i18nBuyer != null) {
      addr = i18nBuyer.getRegCity();
    } else {
      addr = inv.getCustomer().getRegCity();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblCustomer);
      tblCustomer.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regCity", lang) + ": " + addr);
    }
    if (i18nBuyer != null) {
      addr = i18nBuyer.getRegState();
    } else {
      addr = inv.getCustomer().getRegState();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblCustomer);
      tblCustomer.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regState", lang) + ": " + addr);
    }
    if (i18nBuyer != null) {
      addr = i18nBuyer.getRegCountry();
    } else {
      addr = inv.getCustomer().getRegCountry();
    }
    if (addr != null) {
      docMaker.addRowToDocTable(tblCustomer);
      tblCustomer.getItsCells().get(++n).setItsContent(this.srvI18n
        .getMsg("regCountry", lang) + ": " + addr);
    }
    tblCustomer.getItsCells().get(0).setFontNumber(1);
    BigDecimal price;
    BigDecimal subtotal;
    BigDecimal totalTaxes;
    BigDecimal total;
    if (inv.getItsLines() != null && inv.getItsLines().size() > 0) {
      doc.setContainerMarginBottom(mmToDocUom(2.0, doc.getUnitOfMeasure()));
      DocTable<WI> tblTiGoods = docMaker.addDocTableNoBorder(doc, 1, 1);
      tblTiGoods.getItsCells().get(0).setItsContent(this.srvI18n
        .getMsg(SalesInvoiceLine.class.getSimpleName() + "s", lang));
      tblTiGoods.getItsCells().get(0).setFontNumber(1);
      tblTiGoods.setAlignHorizontal(EAlignHorizontal.CENTER);
      docMaker.makeDocTableWrapping(tblTiGoods);
      doc.setContentPadding(mmToDocUom(1.0, doc.getUnitOfMeasure()));
      doc.setContentPaddingBottom(mmToDocUom(1.5, doc.getUnitOfMeasure()));
      int rowc;
      if (isInvoiceBasis) {
        rowc = 6;
      } else if (inv.getPriceIncTax()) {
        rowc = 7;
      } else {
        rowc = 8;
      }
      DocTable<WI> tblGoods = docMaker
        .addDocTable(doc, rowc, inv.getItsLines().size() + 1);
      tblGoods.setIsRepeatHead(true);
      tblGoods.getItsRows().get(0).setIsHead(true);
      tblGoods.getItsCells().get(0).setItsContent(this.srvI18n
        .getMsg("invItem", lang).replace(" ", "\n"));
      tblGoods.getItsColumns().get(0).setIsWidthFixed(true);
      tblGoods.getItsColumns().get(0).setWidthInPercentage(60.0);
      tblGoods.getItsCells().get(1).setItsContent(this.srvI18n
        .getMsg("unitOfMeasure", lang).replace(" ", "\n"));
      tblGoods.getItsColumns().get(1).setWraping(EWraping.WRAP_CONTENT);
      tblGoods.getItsCells().get(2).setItsContent(this.srvI18n
        .getMsg(priceName, lang).replace(" ", "\n"));
      tblGoods.getItsColumns().get(2).setWraping(EWraping.WRAP_CONTENT);
      tblGoods.getItsCells().get(3).setItsContent(this.srvI18n
        .getMsg("itsQuantity", lang).replace(" ", "\n"));
      tblGoods.getItsColumns().get(3).setWraping(EWraping.WRAP_CONTENT);
      int pos = 3;
      if (!inv.getPriceIncTax()) {
        pos++;
        tblGoods.getItsCells().get(pos).setItsContent(this.srvI18n
        .getMsg("subtotal", lang).replace(" ", "\n"));
        tblGoods.getItsColumns().get(pos).setWraping(EWraping.WRAP_CONTENT);
      } else if (isInvoiceBasis && inv.getPriceIncTax()) {
        pos++;
        tblGoods.getItsCells().get(pos).setItsContent(this.srvI18n
        .getMsg("itsTotal", lang).replace(" ", "\n"));
        tblGoods.getItsColumns().get(pos).setWraping(EWraping.WRAP_CONTENT);
      }
      pos++;
      tblGoods.getItsCells().get(pos)
        .setItsContent(this.srvI18n.getMsg("taxesDescription", lang));
      if (!isInvoiceBasis) {
        pos++;
        tblGoods.getItsCells().get(pos).setItsContent(this.srvI18n
          .getMsg("totalTaxes", lang).replace(" ", "\n"));
        tblGoods.getItsColumns().get(pos).setWraping(EWraping.WRAP_CONTENT);
        pos++;
        tblGoods.getItsCells().get(pos).setItsContent(this.srvI18n
          .getMsg("itsTotal", lang).replace(" ", "\n"));
        tblGoods.getItsColumns().get(pos).setWraping(EWraping.WRAP_CONTENT);
      }
      for (int i = 0; i < rowc; i++) {
        tblGoods.getItsCells().get(i).setFontNumber(1);
        tblGoods.getItsCells().get(i)
          .setAlignHorizontal(EAlignHorizontal.CENTER);
      }
      int j = 1;
      for (SalesInvoiceLine ln : inv.getItsLines()) {
        if (inv.getForeignCurrency() != null) {
          price = ln.getForeignPrice();
          subtotal = ln.getForeignSubtotal();
          totalTaxes = ln.getForeignTotalTaxes();
          total = ln.getForeignTotal();
        } else {
          price = ln.getItsPrice();
          subtotal = ln.getSubtotal();
          totalTaxes = ln.getTotalTaxes();
          total = ln.getItsTotal();
        }
        int i = 0;
        int k = j * rowc + i++;
        tblGoods.getItsCells().get(k)
          .setItsContent(ln.getInvItem().getItsName());
        k = j * rowc + i++;
        tblGoods.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.CENTER);
        tblGoods.getItsCells().get(k)
          .setItsContent(ln.getUnitOfMeasure().getItsName());
        k = j * rowc + i++;
        tblGoods.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.RIGHT);
        tblGoods.getItsCells().get(k)
          .setItsContent(prn(pReqVars, price));
        k = j * rowc + i++;
        tblGoods.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.RIGHT);
        tblGoods.getItsCells().get(k)
          .setItsContent(prn(pReqVars, ln.getItsQuantity()));
        if (!inv.getPriceIncTax()) {
          k = j * rowc + i++;
          tblGoods.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblGoods.getItsCells().get(k)
            .setItsContent(prn(pReqVars, subtotal));
        } else if (isInvoiceBasis && inv.getPriceIncTax()) {
          k = j * rowc + i++;
          tblGoods.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblGoods.getItsCells().get(k)
            .setItsContent(prn(pReqVars, total));
        }
        k = j * rowc + i++;
        tblGoods.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.CENTER);
        tblGoods.getItsCells().get(k)
          .setItsContent(ln.getTaxesDescription());
        if (!isInvoiceBasis) {
          k = j * rowc + i++;
          tblGoods.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblGoods.getItsCells().get(k)
            .setItsContent(prn(pReqVars, totalTaxes));
          k = j * rowc + i++;
          tblGoods.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblGoods.getItsCells().get(k)
            .setItsContent(prn(pReqVars, total));
        }
        j++;
      }
    }
    if (inv.getServices() != null && inv.getServices().size() > 0) {
      doc.setContainerMarginBottom(mmToDocUom(2.0, doc.getUnitOfMeasure()));
      DocTable<WI> tblTiServices = docMaker.addDocTableNoBorder(doc, 1, 1);
      tblTiServices.getItsCells().get(0).setItsContent(this.srvI18n
        .getMsg(SalesInvoiceServiceLine.class.getSimpleName() + "s", lang));
      tblTiServices.getItsCells().get(0).setFontNumber(1);
      tblTiServices.setAlignHorizontal(EAlignHorizontal.CENTER);
      docMaker.makeDocTableWrapping(tblTiServices);
      doc.setContentPadding(mmToDocUom(1.0, doc.getUnitOfMeasure()));
      doc.setContentPaddingBottom(mmToDocUom(1.5, doc.getUnitOfMeasure()));
      int rowc;
      double wd15;
      if (isInvoiceBasis) {
        rowc = 6;
        wd15 = 30.0d;
      } else if (inv.getPriceIncTax()) {
        rowc = 7;
        wd15 = 15.0d;
      } else {
        rowc = 8;
        wd15 = 15.0d;
      }
      DocTable<WI> tblServices = docMaker
        .addDocTable(doc, rowc, inv.getServices().size() + 1);
      tblServices.setIsRepeatHead(true);
      tblServices.getItsRows().get(0).setIsHead(true);
      tblServices.getItsCells().get(0)
        .setItsContent(this.srvI18n.getMsg("service", lang));
      tblServices.getItsColumns().get(0).setIsWidthFixed(true);
      tblServices.getItsColumns().get(0).setWidthInPercentage(35.0);
      tblServices.getItsCells().get(1).setItsContent(this.srvI18n
        .getMsg("unitOfMeasure", lang).replace(" ", "\n"));
      tblServices.getItsColumns().get(1).setWraping(EWraping.WRAP_CONTENT);
      tblServices.getItsCells().get(2)
        .setItsContent(this.srvI18n.getMsg(priceName, lang).replace(" ", "\n"));
      tblServices.getItsColumns().get(2).setIsWidthFixed(true);
      tblServices.getItsColumns().get(2).setWidthInPercentage(wd15);
      tblServices.getItsCells().get(3).setItsContent(this.srvI18n
        .getMsg("itsQuantity", lang).replace(" ", "\n"));
      tblServices.getItsColumns().get(3).setWraping(EWraping.WRAP_CONTENT);
      int pos = 3;
      if (!inv.getPriceIncTax()) {
        pos++;
        tblServices.getItsCells().get(pos).setItsContent(this.srvI18n
          .getMsg("subtotal", lang).replace(" ", "\n"));
        tblServices.getItsColumns().get(pos).setWraping(EWraping.WRAP_CONTENT);
      } else if (isInvoiceBasis && inv.getPriceIncTax()) {
        pos++;
        tblServices.getItsCells().get(pos).setItsContent(this.srvI18n
          .getMsg("itsTotal", lang).replace(" ", "\n"));
        tblServices.getItsColumns().get(pos).setWraping(EWraping.WRAP_CONTENT);
      }
      pos++;
      tblServices.getItsCells().get(pos)
        .setItsContent(this.srvI18n.getMsg("taxesDescription", lang));
      if (!isInvoiceBasis) {
        tblServices.getItsColumns().get(pos).setIsWidthFixed(true);
        tblServices.getItsColumns().get(pos).setWidthInPercentage(20.0);
        pos++;
        tblServices.getItsCells().get(pos)
          .setItsContent(this.srvI18n.getMsg("totalTaxes", lang));
        tblServices.getItsColumns().get(pos).setIsWidthFixed(true);
        tblServices.getItsColumns().get(pos).setWidthInPercentage(wd15);
        pos++;
        tblServices.getItsCells().get(pos)
          .setItsContent(this.srvI18n.getMsg("itsTotal", lang));
        tblServices.getItsColumns().get(pos).setIsWidthFixed(true);
        tblServices.getItsColumns().get(pos).setWidthInPercentage(wd15);
      }
      for (int i = 0; i < rowc; i++) {
        tblServices.getItsCells().get(i).setFontNumber(1);
        tblServices.getItsCells().get(i)
          .setAlignHorizontal(EAlignHorizontal.CENTER);
      }
      int j = 1;
      for (SalesInvoiceServiceLine ln : inv.getServices()) {
        if (inv.getForeignCurrency() != null) {
          price = ln.getForeignPrice();
          subtotal = ln.getForeignSubtotal();
          totalTaxes = ln.getForeignTotalTaxes();
          total = ln.getForeignTotal();
        } else {
          price = ln.getItsPrice();
          subtotal = ln.getSubtotal();
          totalTaxes = ln.getTotalTaxes();
          total = ln.getItsTotal();
        }
        int i = 0;
        int k = j * rowc + i++;
        tblServices.getItsCells().get(k)
          .setItsContent(ln.getService().getItsName());
        k = j * rowc + i++;
        tblServices.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.CENTER);
        tblServices.getItsCells().get(k)
          .setItsContent(ln.getUnitOfMeasure().getItsName());
        k = j * rowc + i++;
        tblServices.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.RIGHT);
        tblServices.getItsCells().get(k)
          .setItsContent(prn(pReqVars, price));
        k = j * rowc + i++;
        tblServices.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.RIGHT);
        tblServices.getItsCells().get(k)
          .setItsContent(prn(pReqVars, ln.getItsQuantity()));
        if (!inv.getPriceIncTax()) {
          k = j * rowc + i++;
          tblServices.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblServices.getItsCells().get(k)
            .setItsContent(prn(pReqVars, subtotal));
        } else if (isInvoiceBasis && inv.getPriceIncTax()) {
          k = j * rowc + i++;
          tblServices.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblServices.getItsCells().get(k)
            .setItsContent(prn(pReqVars, total));
        }
        k = j * rowc + i++;
        tblServices.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.CENTER);
        tblServices.getItsCells().get(k)
          .setItsContent(ln.getTaxesDescription());
        if (!isInvoiceBasis) {
          k = j * rowc + i++;
          tblServices.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblServices.getItsCells().get(k)
            .setItsContent(prn(pReqVars, totalTaxes));
          k = j * rowc + i++;
          tblServices.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblServices.getItsCells().get(k)
            .setItsContent(prn(pReqVars, total));
        }
        j++;
      }
    }
    if (inv.getTaxesLines() != null && inv.getTaxesLines().size() > 0) {
      doc.setContainerMarginBottom(mmToDocUom(2.0, doc.getUnitOfMeasure()));
      DocTable<WI> tblTiTaxes = docMaker.addDocTableNoBorder(doc, 1, 1);
      tblTiTaxes.setIsRepeatHead(true);
      tblTiTaxes.getItsRows().get(0).setIsHead(true);
      tblTiTaxes.getItsCells().get(0).setItsContent(this.srvI18n
        .getMsg(SalesInvoiceTaxLine.class.getSimpleName() + "s", lang));
      tblTiTaxes.getItsCells().get(0).setFontNumber(1);
      tblTiTaxes.setAlignHorizontal(EAlignHorizontal.CENTER);
      docMaker.makeDocTableWrapping(tblTiTaxes);
      doc.setContentPadding(mmToDocUom(1.0, doc.getUnitOfMeasure()));
      doc.setContentPaddingBottom(mmToDocUom(1.5, doc.getUnitOfMeasure()));
      int rowc;
      double rowtw;
      if (isInvoiceBasis) {
        rowc = 3;
        rowtw = 40.0d;
      } else {
        rowc = 2;
        rowtw = 70.0d;
      }
      DocTable<WI> tblTaxes = docMaker
        .addDocTable(doc, rowc, inv.getTaxesLines().size() + 1);
      tblTaxes.getItsCells().get(0)
        .setItsContent(this.srvI18n.getMsg("tax", lang));
      tblTaxes.getItsColumns().get(0).setIsWidthFixed(true);
      tblTaxes.getItsColumns().get(0).setWidthInPercentage(rowtw);
      if (isInvoiceBasis) {
        tblTaxes.getItsCells().get(1)
          .setItsContent(this.srvI18n.getMsg("taxable", lang));
      }
      tblTaxes.getItsCells().get(rowc - 1)
        .setItsContent(this.srvI18n.getMsg("itsTotal", lang));
      for (int i = 0; i < rowc; i++) {
        tblTaxes.getItsCells().get(i).setFontNumber(1);
        tblTaxes.getItsCells().get(i)
          .setAlignHorizontal(EAlignHorizontal.CENTER);
      }
      BigDecimal taxable;
      int j = 1;
      for (SalesInvoiceTaxLine ln : inv.getTaxesLines()) {
        if (inv.getForeignCurrency() != null) {
          taxable = ln.getTaxableInvBasFc();
          total = ln.getForeignTotalTaxes();
        } else {
          taxable = ln.getTaxableInvBas();
          total = ln.getItsTotal();
        }
        int i = 0;
        tblTaxes.getItsCells().get(j * rowc + i++)
          .setItsContent(ln.getTax().getItsName());
        int k = j * rowc + i++;
        if (isInvoiceBasis) {
          tblTaxes.getItsCells().get(k)
            .setAlignHorizontal(EAlignHorizontal.RIGHT);
          tblTaxes.getItsCells().get(k)
            .setItsContent(prn(pReqVars, taxable));
          k = j * rowc + i++;
        }
        tblTaxes.getItsCells().get(k)
          .setAlignHorizontal(EAlignHorizontal.RIGHT);
        tblTaxes.getItsCells().get(k)
          .setItsContent(prn(pReqVars, total));
        j++;
      }
    }
    doc.setAlignHoriCont(EAlignHorizontal.RIGHT);
    DocTable<WI> tblRez = docMaker.addDocTableNoBorder(doc, 2, 3);
    tblRez.getItsCells().get(0).setFontNumber(1);
    tblRez.getItsCells().get(0).setItsContent(this.srvI18n.getMsg("subtotal",
      lang) + ": ");
    tblRez.getItsCells().get(1).setFontNumber(1);
    String cnt;
    if (inv.getForeignCurrency() != null) {
      subtotal = inv.getForeignSubtotal();
      totalTaxes = inv.getForeignTotalTaxes();
      total = inv.getForeignTotal();
    } else {
      subtotal = inv.getSubtotal();
      totalTaxes = inv.getTotalTaxes();
      total = inv.getItsTotal();
    }
    if (isPrnCurLf) {
      cnt = curSign + prn(pReqVars, subtotal);
    } else {
      cnt = prn(pReqVars, subtotal) + curSign;
    }
    tblRez.getItsCells().get(1).setItsContent(cnt);
    tblRez.getItsCells().get(2).setFontNumber(1);
    tblRez.getItsCells().get(2).setItsContent(this.srvI18n.getMsg("totalTaxes",
      lang) + ": ");
    tblRez.getItsCells().get(3).setFontNumber(1);
    if (isPrnCurLf) {
      cnt = curSign + prn(pReqVars, totalTaxes);
    } else {
      cnt = prn(pReqVars, totalTaxes) + curSign;
    }
    tblRez.getItsCells().get(3).setItsContent(cnt);
    tblRez.getItsCells().get(4).setFontNumber(1);
    tblRez.getItsCells().get(4).setItsContent(this.srvI18n.getMsg("itsTotal",
      lang) + ": ");
    tblRez.getItsCells().get(5).setFontNumber(1);
    if (isPrnCurLf) {
      cnt = curSign + prn(pReqVars, total);
    } else {
      cnt = prn(pReqVars, total) + curSign;
    }
    tblRez.getItsCells().get(5).setItsContent(cnt);
    tblRez.setAlignHorizontal(EAlignHorizontal.RIGHT);
    docMaker.makeDocTableWrapping(tblRez);
    docMaker.addPagination(doc);
    docMaker.deriveElements(doc);
    pdfMaker.prepareBeforeWrite(docPdf);
    try {
      this.pdfFactory.lazyGetPdfWriter().write(null, docPdf, pOus);
    } finally {
      pOus.close();
    }
  }
795456
@Override
  public final T process(final Map<String, Object> pReqVars,
    final T pEntity, final IRequestData pRequestData) throws Exception {
    SeSeller ses = findSeSeller.find(pReqVars, pRequestData.getUserName());
    pEntity.setSeller(ses);
    if (pEntity.getIsNew()) {
      this.srvOrm.insertEntity(pReqVars, pEntity);
      pEntity.setIsNew(false);
    } else {
      T entOld = this.srvOrm.retrieveEntity(pReqVars, pEntity);
      if (!entOld.getSeller().getItsId().getItsId()
        .equals(pEntity.getSeller().getItsId().getItsId())) {
        throw new ExceptionWithCode(ExceptionWithCode.FORBIDDEN,
        "Attempt to update smb. else's entity: user/entity/EID/SEOLDID/SEID - "
          + pRequestData.getUserName() + "/" + pEntity.getClass()
           .getSimpleName() + "/" + pEntity.getItsId() + "/" + entOld
            .getSeller().getItsId().getItsId() + "/" + pEntity.getSeller()
              .getItsId().getItsId());
      }
      this.srvOrm.updateEntity(pReqVars, pEntity);
    }
    return pEntity;
  }
226387
@Override
  public final void handle(final Map<String, Object> pReqVars,
    final IRequestData pRequestData) throws Exception {
    AccSettings as = srvAccSettings.lazyGetAccSettings(pReqVars);
    String curSign;
    if (as.getUseCurrencySign()) {
      curSign = as.getCurrency().getItsSign();
    } else {
      curSign = " " + as.getCurrency().getItsName() + " ";
    }
    pReqVars.put("quantityDp", as.getQuantityPrecision());
    pReqVars.put("priceDp", as.getPricePrecision());
    pReqVars.put("costDp", as.getCostPrecision());
    pReqVars.put("taxDp", as.getTaxPrecision());
    pReqVars.put("reportDp", as.getBalancePrecision());
    pReqVars.put("curSign", curSign);
    pReqVars.put("accSet", as);
    String lang = (String) pReqVars.get("lang");
    String langDef = (String) pReqVars.get("langDef");
    if (lang != null && langDef != null && !lang.equals(langDef)) {
      List<I18nAccounting> i18nAccTmp;
      List<I18nCurrency> i18nCurTmp;
      synchronized (this) {
        if (this.i18nAccountingList == null) {
          try {
            this.logger.info(null, HndlAccVarsRequest.class,
              "Refreshing I18N data...");
            this.srvDatabase.setIsAutocommit(false);
            this.srvDatabase.setTransactionIsolation(ISrvDatabase
              .TRANSACTION_READ_UNCOMMITTED);
            this.srvDatabase.beginTransaction();
            List<I18nAccounting> i18nac = this.srvOrm.retrieveList(pReqVars,
              I18nAccounting.class);
            List<I18nCurrency> i18ncur = this.srvOrm.retrieveList(pReqVars,
              I18nCurrency.class);
            this.srvDatabase.commitTransaction();
            //assigning fully initialized data:
            this.i18nAccountingList = i18nac;
            this.i18nCurrencyList = i18ncur;
          } catch (Exception ex) {
            if (!this.srvDatabase.getIsAutocommit()) {
              this.srvDatabase.rollBackTransaction();
            }
            throw ex;
          } finally {
            this.srvDatabase.releaseResources();
          }
        }
        i18nAccTmp = this.i18nAccountingList;
        i18nCurTmp = this.i18nCurrencyList;
      }
      for (I18nAccounting i18nAccounting : i18nAccTmp) {
        if (i18nAccounting.getLang().getItsId().equals(lang)) {
          pReqVars.put("i18nAccounting", i18nAccounting);
          break;
        }
      }
      for (I18nCurrency i18nCurrency : i18nCurTmp) {
        if (i18nCurrency.getHasName().getItsId()
          .equals(as.getCurrency().getItsId())
            && i18nCurrency.getLang().getItsId().equals(lang)) {
          pReqVars.put("i18nCurrency", i18nCurrency);
          break;
        }
      }
    }
    if (this.additionalI18nReqHndl != null) {
      this.additionalI18nReqHndl.handle(pReqVars, pRequestData);
    }
  }
969938
@Override
  public final AItemSpecifics<T, ID> process(
    final Map<String, Object> pReqVars,
      final AItemSpecifics<T, ID> pEntity,
        final IRequestData pRequestData) throws Exception {
    String fileToUploadName = (String) pRequestData
      .getAttribute("fileToUploadName");
    OutputStream outs = null;
    InputStream ins = null;
    try {
      String filePath;
      if (pEntity.getStringValue1() == null) { //in base language:
        String ft = String.valueOf(new Date().getTime());
        filePath = this.webAppPath + File.separator
          + this.uploadDirectory + File.separator
            + ft + fileToUploadName;
        pEntity.setStringValue2(filePath);
        pEntity.setStringValue1(this.uploadDirectory
              + "/" + ft + fileToUploadName);
      } else { //I18N files:
        String fileLang = pRequestData.getParameter("fileLang");
        if (pEntity.getStringValue3() == null
          || !pEntity.getStringValue3().contains(fileLang)) {
          throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
            "notset_language");
        }
        int idhHtml = pEntity.getStringValue1().indexOf(".html");
        String urlWithoutHtml = pEntity.getStringValue1().substring(0, idhHtml);
        filePath = this.webAppPath + File.separator
          + urlWithoutHtml + "_" + fileLang + ".html";
      }
      ins = (InputStream) pRequestData.getAttribute("fileToUploadInputStream");
      outs = new BufferedOutputStream(new FileOutputStream(filePath));
      byte[] data = new byte[1024];
      int count;
      while ((count = ins.read(data)) != -1) {
        outs.write(data, 0, count);
      }
      outs.flush();
    } finally {
      if (ins != null) {
        ins.close();
      }
      if (outs != null) {
        outs.close();
      }
    }
    getSrvOrm().updateEntity(pReqVars, pEntity);
    return pEntity;
  }
846085
@Override
  public final SeGoodsSpecifics process(
    final Map<String, Object> pReqVars,
      final SeGoodsSpecifics pEntity,
        final IRequestData pRequestData) throws Exception {
    SeSeller ses = this.findSeSeller.find(pReqVars, pRequestData.getUserName());
    pEntity.setSeller(ses);
    SeGoodsSpecifics entOld = this.srvOrm.retrieveEntity(pReqVars, pEntity);
    if (!entOld.getSeller().getItsId().getItsId()
      .equals(pEntity.getSeller().getItsId().getItsId())) {
      throw new ExceptionWithCode(ExceptionWithCode.FORBIDDEN,
      "Attempt to delete smb. else's entity: user/entity/EID/SEOLDID/SEID - "
        + pRequestData.getUserName() + "/" + pEntity.getClass()
         .getSimpleName() + "/" + pEntity.getItsId() + "/" + entOld
          .getSeller().getItsId().getItsId() + "/" + pEntity.getSeller()
            .getItsId().getItsId());
    }
    File fileToDel;
    if (pEntity.getStringValue2() != null) {
      fileToDel = new File(pEntity.getStringValue2());
      if (fileToDel.exists() && !fileToDel.delete()) {
        throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
          "Can not delete file: " + fileToDel);
      }
    }
    if (pEntity.getStringValue3() != null) {
      int idhHtml = pEntity.getStringValue1().indexOf(".html");
      String urlWithoutHtml = pEntity.getStringValue1().substring(0, idhHtml);
      for (String lang : pEntity.getStringValue3().split(",")) {
        String filePath = this.webAppPath + File.separator
          + urlWithoutHtml + "_" + lang + ".html";
        fileToDel = new File(filePath);
        if (fileToDel.exists() && !fileToDel.delete()) {
          throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
            "Can not delete file: " + fileToDel);
        }
      }
    }
    getSrvOrm().deleteEntity(pReqVars, pEntity);
    return null;
  }
136671
@Override
  public final void process(final Map<String, Object> pReqVars,
    final IRequestData pRequestData) throws Exception {
    retrieveStartData(pReqVars);
    List<PriceCategory> defPcs = this.srvOrm.retrieveListWithConditions(pReqVars, PriceCategory.class, "where DFOL=1");
    if (defPcs.size() != 1) {
      throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE, "where_is_no_only_default_online_price_category");
    }
    SettingsAdd settingsAdd = (SettingsAdd) pReqVars.get("setAdd");
    TradingSettings tradSet = (TradingSettings) pReqVars.get("tradSet");
    GoodsInListLuv goodsInListLuv = (GoodsInListLuv) pReqVars.get("goodsInListLuv");
    pReqVars.remove("goodsInListLuv");
    String refreshAll = pRequestData.getParameter("refreshAll");
    List<GoodsSpecifics> goodsSpecificsLst;
    if (refreshAll != null) {
      goodsSpecificsLst = retrieveItemSpecificsLst(pReqVars, null, GoodsSpecifics.class);
    } else {
      goodsSpecificsLst = retrieveItemSpecificsLst(pReqVars, goodsInListLuv.getGoodsSpecificLuv(), GoodsSpecifics.class);
    }
    updateForItemSpecificsList(pReqVars, goodsSpecificsLst, settingsAdd, goodsInListLuv, tradSet, I18nInvItem.class, EShopItemType.GOODS);
    pRequestData.setAttribute("totalUpdatedGdSp", goodsSpecificsLst.size());
    goodsSpecificsLst = null;
    List<PriceGoods> goodsPriceLst;
    if (refreshAll != null) {
      goodsPriceLst = retrieveItemPriceLst(pReqVars, null, PriceGoods.class, defPcs.get(0).getItsId());
    } else {
      goodsPriceLst = retrieveItemPriceLst(pReqVars, goodsInListLuv.getGoodsPriceLuv(), PriceGoods.class, defPcs.get(0).getItsId());
    }
    updateForItemPriceList(pReqVars, goodsPriceLst, settingsAdd, goodsInListLuv, EShopItemType.GOODS);
    pRequestData.setAttribute("totalUpdatedGdPr", goodsPriceLst.size());
    goodsPriceLst = null;
    List<GoodsPlace> goodsPlaceLst;
    if (refreshAll != null) {
      goodsPlaceLst = retrieveItemPlaceLst(pReqVars, null, GoodsPlace.class);
    } else {
      goodsPlaceLst = retrieveItemPlaceLst(pReqVars, goodsInListLuv.getGoodsAvailableLuv(), GoodsPlace.class);
    }
    updateForItemPlaceList(pReqVars, goodsPlaceLst, settingsAdd, goodsInListLuv, EShopItemType.GOODS);
    pRequestData.setAttribute("totalUpdatedGdAv", goodsPlaceLst.size());
    goodsPlaceLst = null;
    List<ServiceSpecifics> serviceSpecificsLst;
    if (refreshAll != null) {
      serviceSpecificsLst = retrieveItemSpecificsLst(pReqVars, null, ServiceSpecifics.class);
    } else {
      serviceSpecificsLst = retrieveItemSpecificsLst(pReqVars, goodsInListLuv.getServiceSpecificLuv(), ServiceSpecifics.class);
    }
    updateForItemSpecificsList(pReqVars, serviceSpecificsLst, settingsAdd, goodsInListLuv, tradSet, I18nServiceToSale.class, EShopItemType.SERVICE);
    pRequestData.setAttribute("totalUpdatedServSp", serviceSpecificsLst.size());
    serviceSpecificsLst = null;
    List<ServicePrice> servicePriceLst;
    if (refreshAll != null) {
      servicePriceLst = retrieveItemPriceLst(pReqVars, null, ServicePrice.class, defPcs.get(0).getItsId());
    } else {
      servicePriceLst = retrieveItemPriceLst(pReqVars, goodsInListLuv.getServicePriceLuv(), ServicePrice.class, defPcs.get(0).getItsId());
    }
    updateForItemPriceList(pReqVars, servicePriceLst, settingsAdd, goodsInListLuv, EShopItemType.SERVICE);
    pRequestData.setAttribute("totalUpdatedServPr", servicePriceLst.size());
    servicePriceLst = null;
    List<ServicePlace> servicePlaceLst;
    if (refreshAll != null) {
      servicePlaceLst = retrieveItemPlaceLst(pReqVars, null, ServicePlace.class);
    } else {
      servicePlaceLst = retrieveItemPlaceLst(pReqVars, goodsInListLuv.getServicePlaceLuv(), ServicePlace.class);
    }
    updateForItemPlaceList(pReqVars, servicePlaceLst, settingsAdd, goodsInListLuv, EShopItemType.SERVICE);
    pRequestData.setAttribute("totalUpdatedServAv", servicePlaceLst.size());
    servicePlaceLst = null;
    List<SeGoodsSpecifics> seGoodSpecificsLst;
    if (refreshAll != null) {
      seGoodSpecificsLst = retrieveItemSpecificsLst(pReqVars, null, SeGoodsSpecifics.class);
    } else {
      seGoodSpecificsLst = retrieveItemSpecificsLst(pReqVars, goodsInListLuv.getSeGoodSpecificLuv(), SeGoodsSpecifics.class);
    }
    updateForItemSpecificsList(pReqVars, seGoodSpecificsLst, settingsAdd, goodsInListLuv, tradSet, I18nSeGoods.class, EShopItemType.SEGOODS);
    pRequestData.setAttribute("totalUpdatedSeGoodSp", seGoodSpecificsLst.size());
    seGoodSpecificsLst = null;
    List<SeGoodsPrice> seGoodPriceLst;
    if (refreshAll != null) {
      seGoodPriceLst = retrieveItemPriceLst(pReqVars, null, SeGoodsPrice.class, defPcs.get(0).getItsId());
    } else {
      seGoodPriceLst = retrieveItemPriceLst(pReqVars, goodsInListLuv.getSeGoodPriceLuv(), SeGoodsPrice.class, defPcs.get(0).getItsId());
    }
    updateForItemPriceList(pReqVars, seGoodPriceLst, settingsAdd, goodsInListLuv, EShopItemType.SEGOODS);
    pRequestData.setAttribute("totalUpdatedSeGoodPr", seGoodPriceLst.size());
    seGoodPriceLst = null;
    List<SeGoodsPlace> seGoodPlaceLst;
    if (refreshAll != null) {
      seGoodPlaceLst = retrieveItemPlaceLst(pReqVars, null, SeGoodsPlace.class);
    } else {
      seGoodPlaceLst = retrieveItemPlaceLst(pReqVars, goodsInListLuv.getSeGoodPlaceLuv(), SeGoodsPlace.class);
    }
    updateForItemPlaceList(pReqVars, seGoodPlaceLst, settingsAdd, goodsInListLuv, EShopItemType.SEGOODS);
    pRequestData.setAttribute("totalUpdatedSeGoodAv", seGoodPlaceLst.size());
    seGoodPlaceLst = null;
    List<SeServiceSpecifics> seServiceSpecificsLst;
    if (refreshAll != null) {
      seServiceSpecificsLst = retrieveItemSpecificsLst(pReqVars, null, SeServiceSpecifics.class);
    } else {
      seServiceSpecificsLst = retrieveItemSpecificsLst(pReqVars, goodsInListLuv.getSeServiceSpecificLuv(), SeServiceSpecifics.class);
    }
    updateForItemSpecificsList(pReqVars, seServiceSpecificsLst, settingsAdd, goodsInListLuv, tradSet, I18nSeService.class, EShopItemType.SESERVICE);
    pRequestData.setAttribute("totalUpdatedSeServiceSp", seServiceSpecificsLst.size());
    seServiceSpecificsLst = null;
    List<SeServicePrice> seServicePriceLst;
    if (refreshAll != null) {
      seServicePriceLst = retrieveItemPriceLst(pReqVars, null, SeServicePrice.class, defPcs.get(0).getItsId());
    } else {
      seServicePriceLst = retrieveItemPriceLst(pReqVars, goodsInListLuv.getSeServicePriceLuv(), SeServicePrice.class, defPcs.get(0).getItsId());
    }
    updateForItemPriceList(pReqVars, seServicePriceLst, settingsAdd, goodsInListLuv, EShopItemType.SESERVICE);
    pRequestData.setAttribute("totalUpdatedSeServicePr", seServicePriceLst.size());
    seServicePriceLst = null;
    List<SeServicePlace> seServicePlaceLst;
    if (refreshAll != null) {
      seServicePlaceLst = retrieveItemPlaceLst(pReqVars, null, SeServicePlace.class);
    } else {
      seServicePlaceLst = retrieveItemPlaceLst(pReqVars, goodsInListLuv.getSeServicePlaceLuv(), SeServicePlace.class);
    }
    updateForItemPlaceList(pReqVars, seServicePlaceLst, settingsAdd, goodsInListLuv, EShopItemType.SESERVICE);
    pRequestData.setAttribute("totalUpdatedSeServiceAv", seServicePlaceLst.size());
    seServicePlaceLst = null;
    pReqVars.remove("langPreferences");
  }
1339698
public void sendData(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        res.setContentType("text/xml");
        PrintWriter out = res.getWriter();
        this.printXML(req, out);
        out.flush();
    }
332739
public final void adjInvLnsUpdTots(final Map<String, Object> pReqVars,
    final T pInv, final AccSettings pAs,
      final TaxDestination pTxRules) throws Exception {
    List<SalesInvoiceServiceLine> txdLns = this.utlInvBase
      .retrTxdLnsAdjInv(pReqVars, pInv, pAs, pTxRules, this.invTxMeth);
    this.utlInvBase.adjustInvoiceLns(pReqVars, pInv, txdLns, pAs,
      this.invTxMeth);
    this.utlInvBase.updInvTots(pReqVars, pInv, pAs, this.invTxMeth);
  }
416085
@Override
  public final void makeOtherEntries(final Map<String, Object> pReqVars,
    final SalesInvoice pEntity, final IRequestData pRequestData,
      final boolean pIsNew) throws Exception {
    String actionAdd = pRequestData.getParameter("actionAdd");
    if ("makeAccEntries".equals(actionAdd)) {
      if (pEntity.getReversedId() != null) {
        //reverse none-reversed lines:
        SalesInvoiceLine sil = new SalesInvoiceLine();
        SalesInvoice reversed = new SalesInvoice();
        pEntity.setForeignCurrency(reversed.getForeignCurrency());
        pEntity.setForeignSubtotal(reversed.getForeignSubtotal().negate());
        pEntity.setForeignTotalTaxes(reversed.getForeignTotalTaxes().negate());
        pEntity.setForeignTotal(reversed.getForeignTotal().negate());
        reversed.setItsId(pEntity.getReversedId());
        sil.setItsOwner(reversed);
        List<SalesInvoiceLine> reversedLines = getSrvOrm().
          retrieveListForField(pReqVars, sil, "itsOwner");
        String langDef = (String) pReqVars.get("langDef");
        for (SalesInvoiceLine reversedLine : reversedLines) {
          if (reversedLine.getReversedId() == null) {
            SalesInvoiceLine reversingLine = new SalesInvoiceLine();
            reversingLine.setIdDatabaseBirth(getSrvOrm().getIdDatabase());
            reversingLine.setReversedId(reversedLine.getItsId());
            reversingLine.setInvItem(reversedLine.getInvItem());
            reversingLine.setUnitOfMeasure(reversedLine.getUnitOfMeasure());
            reversingLine.setItsPrice(reversedLine.getItsPrice());
            reversingLine.setItsQuantity(reversedLine.getItsQuantity()
              .negate());
            reversingLine.setItsTotal(reversedLine.getItsTotal().negate());
            reversingLine.setSubtotal(reversedLine.getSubtotal().negate());
            reversingLine.setTotalTaxes(reversedLine.getTotalTaxes().negate());
            reversingLine.setTaxesDescription(reversedLine
              .getTaxesDescription());
            reversingLine.setForeignPrice(reversedLine.getForeignPrice());
            reversingLine.setForeignSubtotal(reversedLine.getForeignSubtotal()
              .negate());
            reversingLine.setForeignTotalTaxes(reversedLine
              .getForeignTotalTaxes().negate());
            reversingLine.setForeignTotal(reversedLine.getForeignTotal()
              .negate());
            reversingLine.setIsNew(true);
            reversingLine.setItsOwner(pEntity);
            reversingLine.setDescription(getSrvI18n()
              .getMsg("reversed_n", langDef) + reversedLine.getIdDatabaseBirth()
                + "-" + reversedLine.getItsId()); //local
            getSrvOrm().insertEntity(pReqVars, reversingLine);
            reversingLine.setIsNew(false);
            getSrvWarehouseEntry().reverseDraw(pReqVars, reversingLine);
            getSrvCogsEntry().reverseDraw(pReqVars, reversingLine,
              pEntity.getItsDate(), pEntity.getItsId());
            String descr;
            if (reversedLine.getDescription() == null) {
              descr = "";
            } else {
              descr = reversedLine.getDescription();
            }
            reversedLine.setDescription(descr
              + " " + getSrvI18n().getMsg("reversing_n", langDef)
                + reversingLine.getIdDatabaseBirth() + "-"
                  + reversingLine.getItsId());
            reversedLine.setReversedId(reversingLine.getItsId());
            getSrvOrm().updateEntity(pReqVars, reversedLine);
            SalesInvoiceGoodsTaxLine pigtlt = new SalesInvoiceGoodsTaxLine();
            pigtlt.setItsOwner(reversedLine);
            List<SalesInvoiceGoodsTaxLine> tls = getSrvOrm()
              .retrieveListForField(pReqVars, pigtlt, "itsOwner");
            for (SalesInvoiceGoodsTaxLine pigtl : tls) {
              getSrvOrm().deleteEntity(pReqVars, pigtl);
            }
          }
        }
        SalesInvoiceServiceLine sisl = new SalesInvoiceServiceLine();
        sisl.setItsOwner(reversed);
        List<SalesInvoiceServiceLine> revServLines = getSrvOrm().
          retrieveListForField(pReqVars, sisl, "itsOwner");
        for (SalesInvoiceServiceLine reversedLine : revServLines) {
          if (reversedLine.getReversedId() == null) {
            SalesInvoiceServiceLine reversingLine =
              new SalesInvoiceServiceLine();
            reversingLine.setIdDatabaseBirth(getSrvOrm().getIdDatabase());
            reversingLine.setReversedId(reversedLine.getItsId());
            reversingLine.setService(reversedLine.getService());
            reversingLine.setItsPrice(reversedLine.getItsPrice().negate());
            reversingLine.setUnitOfMeasure(reversedLine.getUnitOfMeasure());
            reversingLine.setItsQuantity(reversedLine.getItsQuantity()
              .negate());
            reversingLine.setSubtotal(reversedLine.getSubtotal().negate());
            reversingLine.setItsTotal(reversedLine.getItsTotal().negate());
            reversingLine.setTotalTaxes(reversedLine.getTotalTaxes().negate());
            reversingLine.setTaxesDescription(reversedLine
              .getTaxesDescription());
            reversingLine.setForeignPrice(reversedLine.getForeignPrice());
            reversingLine.setForeignSubtotal(reversedLine.getForeignSubtotal()
              .negate());
            reversingLine.setForeignTotalTaxes(reversedLine
              .getForeignTotalTaxes().negate());
            reversingLine.setForeignTotal(reversedLine.getForeignTotal()
              .negate());
            reversingLine.setIsNew(true);
            reversingLine.setItsOwner(pEntity);
            getSrvOrm().insertEntity(pReqVars, reversingLine);
            reversingLine.setIsNew(false);
            reversedLine.setReversedId(reversingLine.getItsId());
            getSrvOrm().updateEntity(pReqVars, reversedLine);
            SalesInvoiceServiceTaxLine pigtlt =
              new SalesInvoiceServiceTaxLine();
            pigtlt.setItsOwner(reversedLine);
            List<SalesInvoiceServiceTaxLine> tls = getSrvOrm()
              .retrieveListForField(pReqVars, pigtlt, "itsOwner");
            for (SalesInvoiceServiceTaxLine pigtl : tls) {
              getSrvOrm().deleteEntity(pReqVars, pigtl);
            }
          }
        }
        SalesInvoiceTaxLine sitl = new SalesInvoiceTaxLine();
        sitl.setItsOwner(reversed);
        List<SalesInvoiceTaxLine> reversedTaxLines = getSrvOrm().
          retrieveListForField(pReqVars, sitl, "itsOwner");
        for (SalesInvoiceTaxLine reversedLine : reversedTaxLines) {
          if (reversedLine.getReversedId() == null) {
            SalesInvoiceTaxLine reversingLine = new SalesInvoiceTaxLine();
            reversingLine.setIdDatabaseBirth(getSrvOrm().getIdDatabase());
            reversingLine.setReversedId(reversedLine.getItsId());
            reversingLine.setItsTotal(reversedLine.getItsTotal().negate());
            reversingLine.setForeignTotalTaxes(reversedLine
              .getForeignTotalTaxes().negate());
            reversingLine.setTax(reversedLine.getTax());
            reversingLine.setIsNew(true);
            reversingLine.setItsOwner(pEntity);
            getSrvOrm().insertEntity(pReqVars, reversingLine);
            reversingLine.setIsNew(false);
            reversedLine.setReversedId(reversingLine.getItsId());
            getSrvOrm().updateEntity(pReqVars, reversedLine);
          }
        }
      }
      if (pEntity.getPrepaymentFrom() != null) {
        if (pEntity.getReversedId() != null) {
          pEntity.getPrepaymentFrom().setSalesInvoiceId(null);
        } else {
          pEntity.getPrepaymentFrom().setSalesInvoiceId(pEntity.getItsId());
        }
        getSrvOrm().updateEntity(pReqVars, pEntity.getPrepaymentFrom());
      }
    }
  }
1078603
public void write(Parameter parameter) throws IOException {
        if (parameter.getParameterValueType() == ParameterValueType.PARAMETERS) {
            if (parameter.isArray()) {
                List<Parameters> list = parameter.getValueAsParametersList();
                if (list != null) {
                    if (parameter.isBracketed()) {
                        writeName(parameter);
                        openSquareBracket();
                        for (Parameters p : list) {
                            indent();
                            openCurlyBracket();
                            write(p);
                            closeCurlyBracket();
                        }
                        closeSquareBracket();
                    } else {
                        for (Parameters p : list) {
                            writeName(parameter);
                            openCurlyBracket();
                            write(p);
                            closeCurlyBracket();
                        }
                    }
                }
            } else {
                if (nullWritable || parameter.getValueAsParameters() != null) {
                    writeName(parameter);
                    openCurlyBracket();
                    write(parameter.getValueAsParameters());
                    closeCurlyBracket();
                }
            }
        } else if (parameter.getParameterValueType() == ParameterValueType.VARIABLE) {
            if (parameter.isArray()) {
                List<?> list = parameter.getValueList();
                if (list != null) {
                    if (parameter.isBracketed()) {
                        writeName(parameter);
                        openSquareBracket();
                        for (Object value : list) {
                            indent();
                            if (value instanceof Parameters) {
                                write((Parameters)value);
                            } else if (value != null) {
                                writeString(value.toString());
                            } else {
                                writeNull();
                            }
                        }
                        closeSquareBracket();
                    } else {
                        for (Object value : list) {
                            writeName(parameter);
                            if (value instanceof Parameters) {
                                write((Parameters)value);
                            } else if (value != null) {
                                writeString(value.toString());
                            } else {
                                writeNull();
                            }
                        }
                    }
                }
            } else {
                Object value = parameter.getValue();
                if (nullWritable || value != null) {
                    writeName(parameter);
                    openCurlyBracket();
                    if (value instanceof Parameters) {
                        write((Parameters)value);
                    } else if (value != null) {
                        writeString(value.toString());
                    } else {
                        writeNull();
                    }
                    closeCurlyBracket();
                }
            }
        } else if (parameter.getParameterValueType() == ParameterValueType.STRING) {
            if (parameter.isArray()) {
                List<String> list = parameter.getValueAsStringList();
                if (list != null) {
                    if (parameter.isBracketed()) {
                        writeName(parameter);
                        openSquareBracket();
                        for (String value : list) {
                            indent();
                            writeString(value);
                        }
                        closeSquareBracket();
                    } else {
                        for (String value : list) {
                            writeName(parameter);
                            writeString(value);
                        }
                    }
                }
            } else {
                String s = parameter.getValueAsString();
                if (nullWritable || s != null) {
                    writeName(parameter);
                    writeString(s);
                }
            }
        } else if (parameter.getParameterValueType() == ParameterValueType.TEXT) {
            if (parameter.isArray()) {
                List<String> list = parameter.getValueAsStringList();
                if (list != null) {
                    if (parameter.isBracketed()) {
                        writeName(parameter);
                        openSquareBracket();
                        for (String text : list) {
                            indent();
                            openRoundBracket();
                            writeText(text);
                            closeRoundBracket();
                        }
                        closeSquareBracket();
                    } else {
                        for (String text : list) {
                            writeName(parameter);
                            openRoundBracket();
                            writeText(text);
                            closeRoundBracket();
                        }
                    }
                }
            } else {
                String text = parameter.getValueAsString();
                if (text != null) {
                    writeName(parameter);
                    openRoundBracket();
                    writeText(text);
                    closeRoundBracket();
                } else if (nullWritable) {
                    writeName(parameter);
                    writeNull();
                }
            }
        } else {
            if (parameter.isArray()) {
                List<?> list = parameter.getValueList();
                if (list != null) {
                    if (parameter.isBracketed()) {
                        writeName(parameter);
                        openSquareBracket();
                        for (Object value : list) {
                            indent();
                            write(value);
                        }
                        closeSquareBracket();
                    } else {
                        for (Object value : list) {
                            writeName(parameter);
                            write(value);
                        }
                    }
                }
            } else {
                if (nullWritable || parameter.getValue() != null) {
                    writeName(parameter);
                    write(parameter.getValue());
                }
            }
        }
    }
160575
public static void writePRJ(Connection connection, int srid, File fileName) throws SQLException, FileNotFoundException {
        if (srid != 0) {
            StringBuilder sb = new StringBuilder("SELECT SRTEXT FROM ");
            sb.append("PUBLIC.SPATIAL_REF_SYS ").append(" WHERE SRID = ?");
            PreparedStatement ps = connection.prepareStatement(sb.toString());
            ps.setInt(1, srid);
            PrintWriter printWriter = null;
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                if (rs.next()) {
                    printWriter = new PrintWriter(fileName);
                    printWriter.println(rs.getString(1));
                } else {
                    log.warn("This SRID { "+ srid +" } is not supported. \n The PRJ file won't be created.");
                }
            } finally {
                if (printWriter != null) {
                    printWriter.close();
                }
                if (rs != null) {
                    rs.close();
                }
                ps.close();
            }
        }
    }
592031
@Override
  public final void process(final Map<String, Object> pAddParam,
    final IRequestData pRequestData) throws Exception {
    this.srvEntitiesPage.retrievePage(pAddParam, pRequestData);
  }
1006337
@Override
  public final synchronized void makeWith(final Map<String, Object> pReqVars,
    final FactoryAndServlet pFactoryAndServlet) throws Exception {
    @SuppressWarnings("unchecked")
    AFactoryAppBeans<RS> factoryAppBeans =
      (AFactoryAppBeans<RS>) pFactoryAndServlet.getFactoryAppBeans();
    File webAppPath = new File(pFactoryAndServlet.getHttpServlet().
      getServletContext().getRealPath(""));
    factoryAppBeans.setWebAppPath(webAppPath.getPath());
    String isShowDebugMessagesStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("isShowDebugMessages");
    factoryAppBeans.setIsShowDebugMessages(Boolean
      .valueOf(isShowDebugMessagesStr));
    String detailLevelStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("detailLevel");
    factoryAppBeans.setDetailLevel(Integer.parseInt(detailLevelStr));
    String newDatabaseIdStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("newDatabaseId");
    factoryAppBeans.setNewDatabaseId(Integer.parseInt(newDatabaseIdStr));
    String ormSettingsDir = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("ormSettingsDir");
    factoryAppBeans.setOrmSettingsDir(ormSettingsDir);
    String ormSettingsBaseFile = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("ormSettingsBaseFile");
    factoryAppBeans.setOrmSettingsBaseFile(ormSettingsBaseFile);
    String uvdSettingsDir = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("uvdSettingsDir");
    factoryAppBeans.setUvdSettingsDir(uvdSettingsDir);
    String uvdSettingsBaseFile = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("uvdSettingsBaseFile");
    factoryAppBeans.setUvdSettingsBaseFile(uvdSettingsBaseFile);
    String writeTi = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("writeTi");
    factoryAppBeans.setWriteTi(Integer.parseInt(writeTi));
    String readTi = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("readTi");
    factoryAppBeans.setReadTi(Integer.parseInt(readTi));
    String writeReTi = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("writeReTi");
    factoryAppBeans.setWriteReTi(Integer.parseInt(writeReTi));
    String wrReSpTr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("wrReSpTr");
    factoryAppBeans.setWrReSpTr(Boolean.valueOf(wrReSpTr));
    String fastLoc = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("fastLoc");
    factoryAppBeans.setFastLoc(Boolean.parseBoolean(fastLoc));
    String jdbcUrl = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("databaseName");
    if (jdbcUrl != null && jdbcUrl.contains(ASrvOrm.WORD_CURRENT_DIR)) {
      jdbcUrl = jdbcUrl.replace(ASrvOrm.WORD_CURRENT_DIR,
        factoryAppBeans.getWebAppPath() + File.separator);
    } else if (jdbcUrl != null
      && jdbcUrl.contains(ASrvOrm.WORD_CURRENT_PARENT_DIR)) {
      File fcd = new File(factoryAppBeans.getWebAppPath());
      jdbcUrl = jdbcUrl.replace(ASrvOrm.WORD_CURRENT_PARENT_DIR,
        fcd.getParent() + File.separator);
    }
    String langCountriesStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("langCountries");
    List<String> lngCntLst = new ArrayList<String>();
    for (String str : langCountriesStr.split(",")) {
      lngCntLst.add(str);
    }
    String[] lngCntArr = new String[lngCntLst.size()];
    factoryAppBeans.lazyGetSrvI18n().add(lngCntLst.toArray(lngCntArr));
    LstnDbChanged<RS> lstnDbChanged = new LstnDbChanged<RS>();
    lstnDbChanged.setFactoryAndServlet(pFactoryAndServlet);
    factoryAppBeans.getListenersDbChanged().add(lstnDbChanged);
    factoryAppBeans.setDatabaseName(jdbcUrl);
    String databaseUser = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("databaseUser");
    factoryAppBeans.setDatabaseUser(databaseUser);
    String databasePassword = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("databasePassword");
    factoryAppBeans.setDatabasePassword(databasePassword);
    pFactoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("srvI18n", factoryAppBeans.lazyGet("ISrvI18n"));
    pFactoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("sessionTracker",
        factoryAppBeans.lazyGet("ISessionTracker"));
    //to create/initialize database if need:
    factoryAppBeans.lazyGet("ISrvOrm");
  }
952192
@Override
  public final void make(final Map<String, Object> pReqVars) throws Exception {
    @SuppressWarnings("unchecked")
    AFactoryAppBeans<RS> factoryAppBeans =
      (AFactoryAppBeans<RS>) this.factoryAndServlet.getFactoryAppBeans();
    this.factoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("srvI18n", factoryAppBeans.lazyGet("ISrvI18n"));
    String langCountriesStr = this.factoryAndServlet.getHttpServlet()
      .getInitParameter("langCountries");
    List<String> lngCntLst = new ArrayList<String>();
    for (String str : langCountriesStr.split(",")) {
      lngCntLst.add(str);
    }
    String[] lngCntArr = new String[lngCntLst.size()];
    factoryAppBeans.lazyGetSrvI18n().add(lngCntLst.toArray(lngCntArr));
    this.factoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("sessionTracker",
        factoryAppBeans.lazyGet("ISessionTracker"));
    HndlTradeVarsRequest<RS> hndlTradeVarsRequest =
      new HndlTradeVarsRequest<RS>();
    hndlTradeVarsRequest.setLogger(factoryAppBeans.lazyGetLogger());
    hndlTradeVarsRequest.setSrvDatabase(factoryAppBeans.lazyGetSrvDatabase());
    hndlTradeVarsRequest.setSrvOrm(factoryAppBeans.lazyGetSrvOrm());
    hndlTradeVarsRequest.setUtlTradeJsp((UtlTradeJsp)
      factoryAppBeans.lazyGet("utlTradeJsp"));
    hndlTradeVarsRequest.setSrvSettingsAdd((ISrvSettingsAdd)
      factoryAppBeans.lazyGet("ISrvSettingsAdd"));
    hndlTradeVarsRequest.setSrvTradingSettings((ISrvTradingSettings)
      factoryAppBeans.lazyGet("ISrvTradingSettings"));
    HndlAccVarsRequest<RS> hndlAccVarsRequest = new HndlAccVarsRequest<RS>();
    hndlAccVarsRequest.setAdditionalI18nReqHndl(hndlTradeVarsRequest);
    hndlAccVarsRequest.setLogger(factoryAppBeans.lazyGetLogger());
    hndlAccVarsRequest.setSrvDatabase(factoryAppBeans.lazyGetSrvDatabase());
    hndlAccVarsRequest.setSrvOrm(factoryAppBeans.lazyGetSrvOrm());
    hndlAccVarsRequest.setSrvAccSettings((ISrvAccSettings) factoryAppBeans
      .lazyGet("ISrvAccSettings"));
    factoryAppBeans.lazyGetHndlI18nRequest()
      .setAdditionalI18nReqHndl(hndlAccVarsRequest);
    ISrvDatabase<RS> srvDb = (ISrvDatabase<RS>)
      factoryAppBeans.lazyGet("ISrvDatabase");
    @SuppressWarnings("unchecked")
    SrvAddTheFirstUser<RS> srvAddFiU = (SrvAddTheFirstUser<RS>)
      this.factoryAndServlet.getHttpServlet().getServletContext()
        .getAttribute("srvAddTheFirstUser");
    srvAddFiU.setSrvDatabase(srvDb);
    srvAddFiU.setIsThereAnyUser(false);
    DataBaseLoginService srvDbl = (DataBaseLoginService)
      this.factoryAndServlet.getHttpServlet().getServletContext()
        .getAttribute("JDBCRealm");
    if (srvDbl != null) {
      @SuppressWarnings("unchecked")
      SrvGetUserCredentials<RS> srvCr = (SrvGetUserCredentials<RS>) srvDbl
        .getSrvGetUserCredentials();
      srvCr.setSrvDatabase(srvDb);
      srvDbl.getUsers().clear();
      LstnUserPswdChanged lstnUserPswdChanged = new LstnUserPswdChanged();
      lstnUserPswdChanged.setDbLoginService(srvDbl);
      this.factoryAndServlet.getHttpServlet().getServletContext()
        .setAttribute("ILstnUserPswdChanged", lstnUserPswdChanged);
    }
    //crypto init:
    CryptoHelper ch = (CryptoHelper) factoryAppBeans.lazyGet("ICryptoHelper");
    KeyStore ks = (KeyStore) this.factoryAndServlet.getHttpServlet()
      .getServletContext().getAttribute("ajettyKeystore");
    ch.setKeyStore(ks);
    String passw = (String) this.factoryAndServlet.getHttpServlet()
      .getServletContext().getAttribute("ksPassword");
    ch.setKsPassword(passw.toCharArray());
    Integer ajettyIn = (Integer) this.factoryAndServlet.getHttpServlet()
      .getServletContext().getAttribute("ajettyIn");
    ch.setAjettyIn(ajettyIn);
  }
1302733
public final void makeLine(final Map<String, Object> pReqVars,
    final L pLine, final AccSettings pAs,
      final TaxDestination pTxRules) throws Exception {
    this.utlInvBase
      .makeLine(pReqVars, pLine, pAs, pTxRules, this.invTxMeth, this);
  }
920475
@Override
  public final void process(final Map<String, Object> pRqVs,
    final IRequestData pRqDt) throws Exception {
    pRqDt.setAttribute("catalogs", lazyRetrieveCatalogs(pRqVs));
    TradingSettings ts = (TradingSettings)
      pRqVs.get("tradSet");
    String catalogIdStr = pRqDt.getParameter("catalogId");
    Long catId = null;
    if (catalogIdStr != null) {
      catId = Long.valueOf(catalogIdStr);
    }
    if (catId == null && ts.getCatalogOnStart() != null) {
      catId = ts.getCatalogOnStart().getItsId();
    }
    Cart cart = (Cart) pRqDt.getAttribute("cart");
    if (cart == null) {
      cart = this.srvShoppingCart
        .getShoppingCart(pRqVs, pRqDt, false, false);
    }
    AccSettings as = (AccSettings) pRqVs.get("accSet");
    Currency curr = (Currency) pRqVs.get("wscurr");
    List<CurrRate> currRates = (List<CurrRate>) pRqVs.get("currRates");
    BigDecimal cuRt = BigDecimal.ONE;
    for (CurrRate cr: currRates) {
      if (cr.getCurr().getItsId().equals(curr.getItsId())) {
        cuRt = cr.getRate();
        break;
      }
    }
    if (cart != null) {
      if (cart.getTot().compareTo(BigDecimal.ZERO) == 0) {
        pRqDt.setAttribute("cart", null);
      } else {
        if (!cart.getCurr().getItsId().equals(curr.getItsId())) {
          cart.setCurr(curr);
          cart.setExcRt(cuRt);
          this.srvShoppingCart.handleCurrencyChanged(pRqVs, cart, as, ts);
        }
        if (pRqDt.getAttribute("txRules") == null) {
          TaxDestination txRules = this.srvShoppingCart
            .revealTaxRules(pRqVs, cart, as);
          pRqDt.setAttribute("txRules", txRules);
        }
        Map<EShopItemType, Map<Long, CartLn>> cartMap =
          new HashMap<EShopItemType, Map<Long, CartLn>>();
        for (CartLn ci : cart.getItems()) {
          if (!ci.getDisab()) {
            Map<Long, CartLn> typedMap = cartMap.get(ci.getItTyp());
            if (typedMap == null) {
              typedMap = new HashMap<Long, CartLn>();
              cartMap.put(ci.getItTyp(), typedMap);
            }
            typedMap.put(ci.getItId(), ci);
          }
        }
        pRqDt.setAttribute("cartMap", cartMap);
      }
    }
    if (catId != null) {
      // either selected by user catalog or "on start" must be
      // if user additionally selected filters (include set of subcatalogs)
      // then the main (root) catalog ID still present in request
      TradingCatalog tcat = findTradingCatalogById(this.catalogs, catId);
      if (tcat == null) {
        this.logger.warn(pRqVs, PrcWebstorePage.class,
          "Can't find catalog #" + catId);
      } else {
        String ordb = pRqDt.getParameter("ordb");
        pRqDt.setAttribute("ordb", ordb);
        String orderBy = null;
        if (ordb != null) {
          if (ordb.equals("pa")) {
            orderBy = " order by ITSPRICE asc";
          } else if (ordb.equals("pd")) {
            orderBy = " order by ITSPRICE desc";
          }
        }
        FilterInteger filterPrice = revialFilterPrice(tcat,
          pRqVs, pRqDt);
        FilterItems<CatalogGs> filterCatalog = revialFilterCatalog(tcat,
          pRqVs, pRqDt);
        List<SpecificsFilter> filtersSpecifics = revialFiltersSpecifics(tcat,
          pRqVs, pRqDt);
        String whereAdd = revWhePri(filterPrice, cuRt);
        String whereCatalog = revealWhereCatalog(tcat, filterCatalog);
        //TODO StringBuffer
        String queryg = null;
        String querys = null;
        String queryseg = null;
        String queryses = null;
        if (ts.getUseAdvancedI18n()) {
          String lang = (String) pRqVs.get("lang");
          String langDef = (String) pRqVs.get("langDef");
          if (!lang.equals(langDef)) {
            if (tcat.getCatalog().getHasGoods()) {
              queryg = lazyGetQuItInLstCaIn().replace(":ITTYP", "0")
    .replace(":TITCAT", "GOODSCATALOG").replace(":CATALOGFILTER", whereCatalog)
  .replace(":WHEREADD", whereAdd).replace(":LANG", lang);
            }
            if (tcat.getCatalog().getHasServices()) {
              querys = lazyGetQuItInLstCaIn().replace(":ITTYP", "1")
  .replace(":TITCAT", "SERVICECATALOG").replace(":CATALOGFILTER", whereCatalog)
.replace(":WHEREADD", whereAdd).replace(":LANG", lang);
            }
            if (tcat.getCatalog().getHasSeGoods()) {
              queryseg = lazyGetQuItInLstCaIn().replace(":ITTYP", "2")
   .replace(":TITCAT", "SEGOODCATALOG").replace(":CATALOGFILTER", whereCatalog)
 .replace(":WHEREADD", whereAdd).replace(":LANG", lang);
            }
            if (tcat.getCatalog().getHasSeServices()) {
              queryses = lazyGetQuItInLstCaIn().replace(":ITTYP", "3")
          .replace(":TITCAT", "SESRCA").replace(":CATALOGFILTER", whereCatalog)
        .replace(":WHEREADD", whereAdd).replace(":LANG", lang);
            }
          }
        }
        if (tcat.getCatalog().getHasGoods() && queryg == null) {
          queryg = lazyGetQuItInLstCa().replace(":ITTYP", "0")
    .replace(":TITCAT", "GOODSCATALOG").replace(":CATALOGFILTER", whereCatalog)
  .replace(":WHEREADD", whereAdd);
        }
        if (tcat.getCatalog().getHasServices() && querys == null) {
          querys = lazyGetQuItInLstCa().replace(":ITTYP", "1")
  .replace(":TITCAT", "SERVICECATALOG").replace(":CATALOGFILTER", whereCatalog)
.replace(":WHEREADD", whereAdd);
        }
        if (tcat.getCatalog().getHasSeGoods() && queryseg == null) {
          queryseg = lazyGetQuItInLstCa().replace(":ITTYP", "2")
   .replace(":TITCAT", "SEGOODCATALOG").replace(":CATALOGFILTER", whereCatalog)
 .replace(":WHEREADD", whereAdd);
        }
        if (tcat.getCatalog().getHasSeServices() && queryses == null) {
          queryses = lazyGetQuItInLstCa().replace(":ITTYP", "3")
       .replace(":TITCAT", "SESRCA").replace(":CATALOGFILTER", whereCatalog)
     .replace(":WHEREADD", whereAdd);
        }
        String querygRc = null;
        if (tcat.getCatalog().getHasGoods()) {
          querygRc = lazyGetQuItInLstCaTo().replace(":ITTYP", "0")
    .replace(":TITCAT", "GOODSCATALOG").replace(":CATALOGFILTER", whereCatalog)
  .replace(":WHEREADD", whereAdd);
        }
        String querysRc = null;
        if (tcat.getCatalog().getHasServices()) {
          querysRc = lazyGetQuItInLstCaTo().replace(":ITTYP", "1")
  .replace(":TITCAT", "SERVICECATALOG").replace(":CATALOGFILTER", whereCatalog)
.replace(":WHEREADD", whereAdd);
        }
        String querysegRc = null;
        if (tcat.getCatalog().getHasSeGoods()) {
          querysegRc = lazyGetQuItInLstCaTo().replace(":ITTYP", "2")
   .replace(":TITCAT", "SEGOODCATALOG").replace(":CATALOGFILTER", whereCatalog)
  .replace(":WHEREADD", whereAdd);
        }
        String querysesRc = null;
        if (tcat.getCatalog().getHasSeServices()) {
          querysesRc = lazyGetQuItInLstCaTo().replace(":ITTYP", "3")
           .replace(":TITCAT", "SESRCA").replace(":CATALOGFILTER", whereCatalog)
            .replace(":WHEREADD", whereAdd);
        }
        boolean isDbgSh = getLogger().getDbgSh(this.getClass())
          && getLogger().getDbgFl() < 13011 && getLogger().getDbgCl() > 13013;
        if (filtersSpecifics != null) {
          if (isDbgSh) {
            getLogger().debug(pRqVs, PrcWebstorePage.class,
              "filters apecifics: size: " + filtersSpecifics.size());
          }
          SpecificsFiltersWhere whereSpec =
            revealWhereSpecifics(filtersSpecifics);
          if (whereSpec != null) {
            if (queryg != null) {
              String querySpec = lazyGetQuItSpFlt()
    .replace(":TITSPEC", "GOODSSPECIFICS").replace(":WHESPITFLR", whereSpec
  .getWhere()).replace(":SPITFLTCO", whereSpec.getWhereCount().toString());
              queryg += querySpec;
              querygRc += querySpec;
            }
            if (querys != null) {
              String querySpec = lazyGetQuItSpFlt()
    .replace(":TITSPEC", "SERVICESPECIFICS").replace(":WHESPITFLR", whereSpec
  .getWhere()).replace(":SPITFLTCO", whereSpec.getWhereCount().toString());
              querys += querySpec;
              querysRc += querySpec;
            }
            if (queryseg != null) {
              String querySpec = lazyGetQuItSpFlt()
    .replace(":TITSPEC", "SEGOODSSPECIFICS").replace(":WHESPITFLR", whereSpec
  .getWhere()).replace(":SPITFLTCO", whereSpec.getWhereCount().toString());
              queryseg += querySpec;
              querysegRc += querySpec;
            }
            if (queryses != null) {
              String querySpec = lazyGetQuItSpFlt()
    .replace(":TITSPEC", "SESERVICESPECIFICS").replace(":WHESPITFLR", whereSpec
  .getWhere()).replace(":SPITFLTCO", whereSpec.getWhereCount().toString());
              queryses += querySpec;
              querysesRc += querySpec;
            }
          }
        }
        if (queryg != null || querys != null || queryseg != null
          || queryses != null) {
          String query = null;
          String queryRc = null;
          if (queryg != null) {
            query = queryg;
            queryRc = querygRc;
          }
          if (querys != null) {
            if (query == null) {
              query = querys;
              queryRc = querysRc;
            } else {
              query += "\n union all \n" + querys;
              queryRc += "\n union all \n" + querysRc;
            }
          }
          if (queryseg != null) {
            if (query == null) {
              query = queryseg;
              queryRc = querysegRc;
            } else {
              query += "\n union all \n" + queryseg;
              queryRc += "\n union all \n" + querysegRc;
            }
          }
          if (queryses != null) {
            if (query == null) {
              query = queryses;
              queryRc = querysesRc;
            } else {
              query += "\n union all \n" + queryses;
              queryRc += "\n union all \n" + querysesRc;
            }
          }
          queryRc = "select count(*) as TOTALROWS from (" + queryRc
            + ") as ALL_TOT";
          if (orderBy != null) {
            query += orderBy;
            queryRc += orderBy;
          }
          queryRc += ";";
          Integer rowCount = this.srvOrm
            .evalRowCountByQuery(pRqVs, ItemInList.class, queryRc);
          Set<String> neededFields = new HashSet<String>();
          neededFields.add("itsType");
          neededFields.add("itemId");
          neededFields.add("itsName");
          neededFields.add("imageUrl");
          neededFields.add("specificInList");
          neededFields.add("itsPrice");
          neededFields.add("previousPrice");
          neededFields.add("availableQuantity");
          neededFields.add("itsRating");
          neededFields.add("detailsMethod");
          pRqVs.put("ItemInListneededFields", neededFields);
          String pageStr = pRqDt.getParameter("page");
          Integer page;
          if (pageStr != null) {
            page = Integer.valueOf(pageStr);
          } else {
            page = 1;
          }
          Integer itemsPerPage = ts.getItemsPerPage();
          int totalPages = this.srvPage.evalPageCount(rowCount, itemsPerPage);
          if (page > totalPages) {
            page = totalPages;
          }
          int firstResult = (page - 1) * itemsPerPage; //0-20,20-40
          List<ItemInList> itemsList = getSrvOrm()
            .retrievePageByQuery(pRqVs, ItemInList.class,
              query, firstResult, itemsPerPage);
          pRqVs.remove("ItemInListneededFields");
          if (ts.getIsUsePriceForCustomer() && cart != null
            && cart.getBuyer().getRegEmail() != null) {
            List<BuyerPriceCategory> buyerPrCats = getSrvOrm()
              .retrieveListWithConditions(pRqVs, BuyerPriceCategory.class,
                "where BUYER=" + cart.getBuyer().getItsId());
            if (buyerPrCats.size() > 1) {
              this.logger.error(pRqVs, PrcWebstorePage.class,
                "Several price category for same buyer! buyer ID="
                  + cart.getBuyer().getItsId());
            throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
                "several_price_category_for_same_buyer");
            }
            if (buyerPrCats.size() == 1) {
              StringBuffer sbg = null;
              StringBuffer sbs = null;
              StringBuffer sbsg = null;
              StringBuffer sbss = null;
              for (ItemInList iil : itemsList) {
                if (iil.getItsType().equals(EShopItemType.GOODS)) {
                  if (sbg == null) {
                    sbg = new StringBuffer();
                    sbg.append("(" + iil.getItemId());
                  } else {
                    sbg.append("," + iil.getItemId());
                  }
                } else if (iil.getItsType().equals(EShopItemType.SERVICE)) {
                  if (sbs == null) {
                    sbs = new StringBuffer();
                    sbs.append("(" + iil.getItemId());
                  } else {
                    sbs.append("," + iil.getItemId());
                  }
                } else if (iil.getItsType().equals(EShopItemType.SEGOODS)) {
                  if (sbsg == null) {
                    sbsg = new StringBuffer();
                    sbsg.append("(" + iil.getItemId());
                  } else {
                    sbsg.append("," + iil.getItemId());
                  }
                } else if (iil.getItsType().equals(EShopItemType.SESERVICE)) {
                  if (sbss == null) {
                    sbss = new StringBuffer();
                    sbss.append("(" + iil.getItemId());
                  } else {
                    sbss.append("," + iil.getItemId());
                  }
                }
              }
              StringBuffer sbq = null;
              if (sbg != null) {
                sbq = new StringBuffer();
                sbq.append(
       "select 0 as ITSVERSION, ITEM, ITSPRICE from PRICEGOODS where ITEM in "
    + sbg + ")");
              }
              if (sbs != null) {
                if (sbq == null) {
                  sbq = new StringBuffer();
                } else {
                  sbq.append("\n union all \n");
                }
                sbq.append(
       "select 1 as ITSVERSION, ITEM, ITSPRICE from SERVICEPRICE where ITEM in "
    + sbs + ")");
              }
              if (sbsg != null) {
                if (sbq == null) {
                  sbq = new StringBuffer();
                } else {
                  sbq.append("\n union all \n");
                }
                sbq.append(
       "select 2 as ITSVERSION, ITEM, ITSPRICE from SEGOODSPRICE where ITEM in "
    + sbsg + ")");
              }
              if (sbss != null) {
                if (sbq == null) {
                  sbq = new StringBuffer();
                } else {
                  sbq.append("\n union all \n");
                }
                sbq.append(
     "select 3 as ITSVERSION, ITEM, ITSPRICE from SESERVICEPRICE where ITEM in "
    + sbss + ")");
              }
              if (sbq != null) {
                sbq.append(";");
                Set<String> ndFlPr = new HashSet<String>();
                ndFlPr.add("item");
                ndFlPr.add("itsPrice");
                ndFlPr.add("itsVersion"); //actually item type!
                pRqVs.put("PriceGoodsneededFields", ndFlPr);
                pRqVs.put("PriceGoodsitemdeepLevel", 1);
             List<PriceGoods> prcs = this.srvOrm.retrieveListByQuery(pRqVs,
                  PriceGoods.class, sbq.toString());
                pRqVs.remove("PriceGoodsneededFields");
                pRqVs.remove("PriceGoodsitemdeepLevel");
                for (PriceGoods pri : prcs) {
                  for (ItemInList iil : itemsList) {
                    long itTyp = iil.getItsType().ordinal();
                    if (iil.getItemId().equals(pri.getItem().getItsId())
                      && itTyp == pri.getItsVersion()) {
                      iil.setItsPrice(pri.getItsPrice());
                      break;
                    }
                  }
                }
              }
            }
          }
          Integer paginationTail = Integer.valueOf(mngUvdSettings
            .getAppSettings().get("paginationTail"));
          List<Page> pages = this.srvPage.evalPages(page, totalPages,
            paginationTail);
          pRqDt.setAttribute("pages", pages);
          pRqDt.setAttribute("itemsList", itemsList);
          pRqDt.setAttribute("totalItems", rowCount);
        }
        if (filterPrice != null) {
          pRqDt.setAttribute("filterPrice", filterPrice);
        }
        if (filterCatalog != null) {
          pRqDt.setAttribute("filterCatalog", filterCatalog);
        }
        if (filtersSpecifics != null) {
          pRqDt.setAttribute("filtersSpecifics", filtersSpecifics);
        }
        pRqDt.setAttribute("catalog", tcat.getCatalog());
      }
    }
  }
634088
public final void mkFreBuyr(final Map<String, Object> pRqVs,
    final IRequestData pRqDt, final OnlineBuyer pBuTmp,
      final OnlineBuyer pBuyr) throws Exception {
    long now = new Date().getTime();
    if (!pBuTmp.getIsNew()) {
      pBuTmp.setFre(true);
      pBuTmp.setRegEmail(null);
      pBuTmp.setRegisteredPassword(null);
      pBuTmp.setLsTm(0L);
      this.srvOrm.updateEntity(pRqVs, pBuTmp);
    }
    pBuyr.setLsTm(now);
    UUID buseid = UUID.randomUUID();
    pBuyr.setBuSeId(buseid.toString());
    this.srvOrm.updateEntity(pRqVs, pBuyr);
    pRqDt.setCookieValue("buSeId", pBuyr.getBuSeId());
    pRqDt.setCookieValue("cBuyerId", pBuyr.getItsId().toString());
    pRqDt.setAttribute("buyr", pBuyr);
    Cart oldCrt = this.srvOrm.retrieveEntityById(pRqVs, Cart.class, pBuTmp);
    if (oldCrt != null && oldCrt.getTot().compareTo(BigDecimal.ZERO) == 1) {
      Long obid = pBuTmp.getItsId();
      ColumnsValues cvs = new ColumnsValues();
      cvs.setIdColumnsNames(new String[] {"itsId"});
      cvs.put("itsOwner", pBuyr.getItsId());
      this.srvDb.executeUpdate("CARTLN", cvs, "ITSOWNER=" + obid);
      this.srvDb.executeUpdate("CARTTXLN", cvs, "ITSOWNER=" + obid);
      this.srvDb.executeUpdate("CARTTOT", cvs, "ITSOWNER=" + obid);
      Cart cart = this.srvCart.getShoppingCart(pRqVs, pRqDt, true, false);
      TradingSettings ts = (TradingSettings) pRqVs.get("tradSet");
      AccSettings as = (AccSettings) pRqVs.get("accSet");
      TaxDestination txRules = this.srvCart.revealTaxRules(pRqVs, cart, as);
      if (txRules != null) {
        pRqDt.setAttribute("txRules", txRules);
      }
      cart.setDeliv(oldCrt.getDeliv());
      cart.setPayMeth(oldCrt.getPayMeth());
      //redo prices and taxes:
      CartLn frCl = null;
      for (CartLn cl : cart.getItems()) {
        if (!cl.getDisab()) {
          if (cl.getForc()) {
            frCl = cl;
            this.srvCart.delLine(pRqVs, cl, txRules);
          } else {
            this.srvCart.makeCartLine(pRqVs, cl, as, ts, txRules, true, true);
            this.srvCart.makeCartTotals(pRqVs, ts, cl, as, txRules);
          }
        }
      }
      if (frCl != null) {
         this.srvCart.hndCartChan(pRqVs, cart, txRules);
      }
    }
  }