<p>Process entity request.</p>
@param pReqVars additional request scoped parameters
@param pRequestData Request Data
@param pEntity Entity to process
@return Entity processed for farther process or null
@throws Exception - an exception
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;
  }
3605
@Override
  public final void addCheckIsReadyToAccount(
    final Map<String, Object> pReqVars,
      final PurchaseInvoice pEntity,
        final IRequestData pRequestData) throws Exception {
    // nothing
  }
729910
public static Object parsePrimitive(
            final String fieldName, final PrimitiveAttribute<?> pAtt, final PObject requestData) {
        Class<?> valueClass = pAtt.getValueClass();
        Object value;
        try {
            value = parseValue(false, new String[0], valueClass, fieldName, requestData);
        } catch (UnsupportedTypeException e) {
            String type = e.type.getName();
            if (e.type.isArray()) {
                type = e.type.getComponentType().getName() + "[]";
            }
            throw new RuntimeException(
                    "The type '" + type + "' is not a supported type when parsing json.  " +
                            "See documentation for supported types.\n\nUnsupported type found in attribute " +
                            fieldName
                            + "\n\nTo support more types add the type to " +
                            "parseValue and parseArrayValue in this class and add a test to the test class",
                    e);
        }
        pAtt.validateValue(value);

        return value;
    }
309295
@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 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"));
    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);
    @SuppressWarnings("unchecked")
    ISrvDatabase<RS> srvDb = (ISrvDatabase<RS>)
      factoryAppBeans.lazyGet("ISrvDatabase");
    SrvAddTheFirstUser<RS> srvAddFiU = new SrvAddTheFirstUser<RS>();
    srvAddFiU.setSrvDatabase(srvDb);
    pFactoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("srvAddTheFirstUser", srvAddFiU);
    DataBaseLoginService srvDbl = (DataBaseLoginService)
      pFactoryAndServlet.getHttpServlet().getServletContext()
        .getAttribute("JDBCRealm");
    if (srvDbl != null) {
      SrvGetUserCredentials<RS> srvCr = new SrvGetUserCredentials<RS>();
      srvCr.setSrvDatabase(srvDb);
      srvDbl.setSrvGetUserCredentials(srvCr);
      LstnUserPswdChanged lstnUserPswdChanged = new LstnUserPswdChanged();
      lstnUserPswdChanged.setDbLoginService(srvDbl);
      pFactoryAndServlet.getHttpServlet().getServletContext()
        .setAttribute("ILstnUserPswdChanged", lstnUserPswdChanged);
    }
    //crypto init:
    CryptoHelper ch = (CryptoHelper) factoryAppBeans.lazyGet("ICryptoHelper");
    KeyStore ks = (KeyStore) pFactoryAndServlet.getHttpServlet()
      .getServletContext().getAttribute("ajettyKeystore");
    ch.setKeyStore(ks);
    String passw = (String) pFactoryAndServlet.getHttpServlet()
      .getServletContext().getAttribute("ksPassword");
    ch.setKsPassword(passw.toCharArray());
    Integer ajettyIn = (Integer) pFactoryAndServlet.getHttpServlet()
      .getServletContext().getAttribute("ajettyIn");
    ch.setAjettyIn(ajettyIn);
  }
157655
@Override
  public final SeServiceSpecifics process(
    final Map<String, Object> pReqVars,
      final SeServiceSpecifics pEntity,
        final IRequestData pRequestData) throws Exception {
    SeSeller ses = this.findSeSeller.find(pReqVars, pRequestData.getUserName());
    pEntity.setSeller(ses);
    SeServiceSpecifics 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());
    }
    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;
  }
1293903
@Override
  public final List<Node<String>> getSampleDataRow(
    final Map<String, Object> pReqVars) throws Exception {
    String lang = (String) pReqVars.get("lang");
    List<Node<String>> result = new ArrayList<Node<String>>();
    Integer idx = 1;
    Node<String> nodeGoods = new Node<String>();
    result.add(nodeGoods);
    nodeGoods.setItsName(getSrvI18n().getMsg("goods", lang));
    nodeGoods.setItsNodes(new ArrayList<Node<String>>());
    Node<String> nodeGoodsName = new Node<String>();
    nodeGoods.getItsNodes().add(nodeGoodsName);
    nodeGoodsName.setItsName(getSrvI18n().getMsg("itsName", lang));
    nodeGoodsName.setItsValue(idx.toString() + ";itsName");
    Node<String> nodeGoodsId = new Node<String>();
    nodeGoods.getItsNodes().add(nodeGoodsId);
    nodeGoodsId.setItsName(getSrvI18n().getMsg("itsId", lang));
    nodeGoodsId.setItsValue(idx.toString() + ";itsId");
    Node<String> nodeGoodsItsCategory = new Node<String>();
    nodeGoods.getItsNodes().add(nodeGoodsItsCategory);
    nodeGoodsItsCategory.setItsName(getSrvI18n().getMsg("itsCategory", lang));
    nodeGoodsItsCategory.setItsNodes(new ArrayList<Node<String>>());
    Node<String> nodeGoodsItsCategoryName = new Node<String>();
    nodeGoodsItsCategory.getItsNodes().add(nodeGoodsItsCategoryName);
    nodeGoodsItsCategoryName.setItsName(getSrvI18n().getMsg("itsName", lang));
    nodeGoodsItsCategoryName
      .setItsValue(idx.toString() + ";itsCategory,itsName");
    Node<String> nodeGoodsItsCategoryId = new Node<String>();
    nodeGoodsItsCategory.getItsNodes().add(nodeGoodsItsCategoryId);
    nodeGoodsItsCategoryId.setItsName(getSrvI18n().getMsg("itsId", lang));
    nodeGoodsItsCategoryId.setItsValue(idx.toString() + ";itsCategory,itsId");
    Node<String> nodeGoodsDefUnitOfMeasure = new Node<String>();
    nodeGoods.getItsNodes().add(nodeGoodsDefUnitOfMeasure);
    nodeGoodsDefUnitOfMeasure.setItsName(getSrvI18n()
      .getMsg("defUnitOfMeasure", lang));
    nodeGoodsDefUnitOfMeasure.setItsNodes(new ArrayList<Node<String>>());
    Node<String> nodeGoodsDefUnitOfMeasureName = new Node<String>();
    nodeGoodsDefUnitOfMeasure.getItsNodes().add(nodeGoodsDefUnitOfMeasureName);
    nodeGoodsDefUnitOfMeasureName
      .setItsName(getSrvI18n().getMsg("itsName", lang));
    nodeGoodsDefUnitOfMeasureName
      .setItsValue(idx.toString() + ";defUnitOfMeasure,itsName");
    Node<String> nodeGoodsDefUnitOfMeasureId = new Node<String>();
    nodeGoodsDefUnitOfMeasure.getItsNodes().add(nodeGoodsDefUnitOfMeasureId);
    nodeGoodsDefUnitOfMeasureId.setItsName(getSrvI18n().getMsg("itsId", lang));
    nodeGoodsDefUnitOfMeasureId
      .setItsValue(idx.toString() + ";defUnitOfMeasure,itsId");
    idx++;
    Node<String> nodePrice = new Node<String>();
    result.add(nodePrice);
    nodePrice.setItsName(getSrvI18n().getMsg("itsPrice", lang));
    nodePrice.setItsValue(idx.toString());
    idx++;
    Node<String> nodeCost = new Node<String>();
    result.add(nodeCost);
    nodeCost.setItsName(getSrvI18n().getMsg("itsCost", lang));
    nodeCost.setItsValue(idx.toString());
    idx++;
    Node<String> nodeQuantity = new Node<String>();
    result.add(nodeQuantity);
    nodeQuantity.setItsName(getSrvI18n().getMsg("itsQuantity", lang));
    nodeQuantity.setItsValue(idx.toString());
    idx++;
    Node<String> nodeIsAvailable = new Node<String>();
    result.add(nodeIsAvailable);
    nodeIsAvailable.setItsName(getSrvI18n().getMsg("isAvailable", lang));
    nodeIsAvailable.setItsValue(idx.toString());
    idx++;
    Node<String> nodeWarehouseSite = new Node<String>();
    result.add(nodeWarehouseSite);
    nodeWarehouseSite.setItsName(getSrvI18n().getMsg("WarehouseSite", lang));
    nodeWarehouseSite.setItsNodes(new ArrayList<Node<String>>());
    Node<String> nodeWarehouseSiteName = new Node<String>();
    nodeWarehouseSite.getItsNodes().add(nodeWarehouseSiteName);
    nodeWarehouseSiteName.setItsName(getSrvI18n().getMsg("itsName", lang));
    nodeWarehouseSiteName.setItsValue(idx.toString() + ";itsName");
    Node<String> nodeWarehouseSiteId = new Node<String>();
    nodeWarehouseSite.getItsNodes().add(nodeWarehouseSiteId);
    nodeWarehouseSiteId.setItsName(getSrvI18n().getMsg("itsId", lang));
    nodeWarehouseSiteId.setItsValue(idx.toString() + ";itsId");
    Node<String> nodeWarehouseSiteWarehouse = new Node<String>();
    nodeWarehouseSite.getItsNodes().add(nodeWarehouseSiteWarehouse);
    nodeWarehouseSiteWarehouse
      .setItsName(getSrvI18n().getMsg("warehouse", lang));
    nodeWarehouseSiteWarehouse.setItsNodes(new ArrayList<Node<String>>());
    Node<String> nodeWarehouseSiteWarehouseName = new Node<String>();
    nodeWarehouseSiteWarehouse.getItsNodes()
      .add(nodeWarehouseSiteWarehouseName);
    nodeWarehouseSiteWarehouseName
      .setItsName(getSrvI18n().getMsg("itsName", lang));
    nodeWarehouseSiteWarehouseName
      .setItsValue(idx.toString() + ";warehouse,itsName");
    Node<String> nodeWarehouseSiteWarehouseId = new Node<String>();
    nodeWarehouseSiteWarehouse.getItsNodes().add(nodeWarehouseSiteWarehouseId);
    nodeWarehouseSiteWarehouseId.setItsName(getSrvI18n().getMsg("itsId", lang));
    nodeWarehouseSiteWarehouseId
      .setItsValue(idx.toString() + ";warehouse,itsId");
    Set<String> ndFlIdNm = new HashSet<String>();
    ndFlIdNm.add("itsId");
    ndFlIdNm.add("itsName");
    pReqVars.put("InvItemTaxCategoryneededFields", ndFlIdNm);
    pReqVars.put("TaxneededFields", ndFlIdNm);
    List<InvItemTaxCategoryLine> allTaxCatsLns = getSrvOrm()
      .retrieveList(pReqVars, InvItemTaxCategoryLine.class);
    pReqVars.remove("InvItemTaxCategoryneededFields");
    pReqVars.remove("TaxneededFields");
    List<Tax> usedTaxes = new ArrayList<Tax>();
    List<InvItemTaxCategory> usedTaxCats = new ArrayList<InvItemTaxCategory>();
    for (InvItemTaxCategoryLine tcl : allTaxCatsLns) {
      boolean txListed = false;
      for (Tax tx : usedTaxes) {
        if (tx.getItsId().equals(tcl.getTax().getItsId())) {
          txListed = true;
          break;
        }
      }
      if (!txListed) {
        usedTaxes.add(tcl.getTax());
      }
      int tci = -1;
      for (InvItemTaxCategory tc : usedTaxCats) {
        if (tc.getItsId().equals(tcl.getItsOwner().getItsId())) {
          tci = usedTaxCats.indexOf(tc);
          break;
        }
      }
      if (tci == -1) {
        usedTaxCats.add(tcl.getItsOwner());
        tcl.getItsOwner().setTaxes(new ArrayList<InvItemTaxCategoryLine>());
        tcl.getItsOwner().getTaxes().add(tcl);
      } else {
        usedTaxCats.get(tci).getTaxes().add(tcl);
      }
    }
    boolean isOnlyTax = true;
    for (InvItemTaxCategory txc : usedTaxCats) {
      if (txc.getTaxes().size() > 1) {
        isOnlyTax = false;
        break;
      }
    }
    if (isOnlyTax) {
      idx++;
      addTaxWr(result, idx.toString(),
        getSrvI18n().getMsg("OnlyTax", lang), lang);
    } else {
      idx++;
      addTaxCatWr(result, idx.toString(),
        getSrvI18n().getMsg("taxCategory", lang), lang);
      Collections.sort(usedTaxes, new CmprHasIdLong<Tax>());
      for (Tax tx : usedTaxes) {
        idx++;
        addTaxWr(result, idx.toString(), tx.getItsName(), lang);
      }
      Collections.sort(usedTaxCats, new CmprHasIdLong<InvItemTaxCategory>());
      for (InvItemTaxCategory txc : usedTaxCats) {
        idx++;
        addTaxCatWr(result, idx.toString(), txc.getItsName(), lang);
      }
    }
    return result;
  }
165055
@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"));
    this.factoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("sessionTracker",
        factoryAppBeans.lazyGet("ISessionTracker"));
  }
974830
public QueryResponse<DatastoreKey> executeKeyQueryRequest(KeyQueryRequest request) {
    try {
      GqlQuery.Builder<Key> queryBuilder = Query.newGqlQueryBuilder(ResultType.KEY,
          request.getQuery());
      queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
      queryBuilder.setAllowLiteral(request.isAllowLiterals());
      QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
      QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
      GqlQuery<Key> gqlQuery = queryBuilder.build();
      QueryResults<Key> results = nativeReader.run(gqlQuery);
      List<DatastoreKey> entities = new ArrayList<>();
      DefaultQueryResponse<DatastoreKey> response = new DefaultQueryResponse<>();
      response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
      while (results.hasNext()) {
        Key result = results.next();
        DatastoreKey datastoreKey = new DefaultDatastoreKey(result);
        entities.add(datastoreKey);
      }
      response.setResults(entities);
      response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
      response.setQueryResponseMetadata(
          new DefaultQueryResponseMetadata(
              QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
      return response;
    } catch (DatastoreException exp) {
      throw new EntityManagerException(exp);
    }
  }
1224571
@Override
  public final void process(final Map<String, Object> pRqVs,
    final IRequestData pRqDt) throws Exception {
    Cart cart = this.srvCart.getShoppingCart(pRqVs, pRqDt, false, true);
    if (cart == null) {
      redir(pRqVs, pRqDt);
      return;
    }
    if (EPaymentMethod.PAYPAL.equals(cart.getPayMeth())) {
      //TODO partially online, SE
      List<PayMd> payMds = this.srvOrm.retrieveListWithConditions(pRqVs,
        PayMd.class, "where ITSNAME='PAYPAL'");
      if (payMds.size() != 1) {
        throw new Exception("There is no properly PPL PayMd");
      } else {
        pRqDt.setAttribute("pmde", payMds.get(0).getMde());
      }
    }
    TradingSettings ts = (TradingSettings) pRqVs.get("tradSet");
    AccSettings as = (AccSettings) pRqVs.get("accSet");
    TaxDestination txRules = this.srvCart.revealTaxRules(pRqVs, cart, as);
    //redo prices and taxes:
    for (CartLn cl : cart.getItems()) {
      if (!cl.getDisab() && !cl.getForc()) {
        this.srvCart.makeCartLine(pRqVs, cl, as, ts, txRules, true, true);
        this.srvCart.makeCartTotals(pRqVs, ts, cl, as, txRules);
      }
    }
    boolean isCompl = true;
    Purch pur = retNewOrds(pRqVs, cart.getBuyer());
    String cond;
    for (CartLn cl : cart.getItems()) {
      if (cl.getDisab()) {
        continue;
      }
      Class<?> itPlCl;
      String serBus = null;
      if (cl.getItTyp().equals(EShopItemType.GOODS)) {
        itPlCl = GoodsPlace.class;
      } else if (cl.getItTyp().equals(EShopItemType.SERVICE)) {
        itPlCl = ServicePlace.class;
        serBus = SerBus.class.getSimpleName();
      } else if (cl.getItTyp().equals(EShopItemType.SESERVICE)) {
        itPlCl = SeServicePlace.class;
        serBus = SeSerBus.class.getSimpleName();
      } else {
        itPlCl = SeGoodsPlace.class;
      }
      if (serBus == null || cl.getDt1() == null) {
        // good or non-bookable service
        cond = "where ITSQUANTITY>0 and ITEM=" + cl.getItId();
      } else {
        cond = "left join (select distinct SERV from " + serBus + " where SERV="
      + cl.getItId() + " and FRTM>=" + cl.getDt1().getTime() + " and TITM<"
    + cl.getDt2().getTime() + ") as " + serBus + " on " + serBus + ".SERV="
  + itPlCl.getSimpleName() + ".ITEM where ITEM=" + cl.getItId()
+ " and ITSQUANTITY>0 and " + serBus + ".SERV is null";
      }
      Set<String> ndFlNm = new HashSet<String>();
      ndFlNm.add("itsId");
      ndFlNm.add("itsName");
      pRqVs.put("PickUpPlaceneededFields", ndFlNm);
      pRqVs.put(itPlCl.getSimpleName() + "itemdeepLevel", 1); //only ID
      @SuppressWarnings("unchecked")
      List<AItemPlace<?, ?>> places = (List<AItemPlace<?, ?>>) getSrvOrm()
        .retrieveListWithConditions(pRqVs, itPlCl, cond);
      pRqVs.remove(itPlCl.getSimpleName() + "itemdeepLevel");
      pRqVs.remove("PickUpPlaceneededFields");
      if (places.size() > 1 && serBus != null && cl.getDt1() != null) {
        //for bookable service it's ambiguous - same service (e.g. appointment
        //to DR.Jonson) is available at same time in two different places)
        //for non-bookable service, e.g. for delivering place means
        //starting-point, but it should be selected automatically TODO
        //for goods: TODO
        //1. buyer chooses place (in filter), so use this place
        //2. buyer will pickups by yourself from different places,
        // but it must chooses them (in filter) in this case.
        // As a result places should ordered by itsQuantity and removed items
        // that are out of filter.
        isCompl = false;
        String errs = "!Wrong places for item name/ID/type: " + cl.getItsName()
          + "/" + cl.getItId() + "/" + cl.getItTyp();
        if (cart.getDescr() == null) {
          cart.setDescr(errs);
        } else {
          cart.setDescr(cart.getDescr() + errs);
        }
        cart.setErr(true);
        getSrvOrm().updateEntity(pRqVs, cart);
        this.log.warn(pRqVs, PrcCheckOut.class, errs);
        break;
      } else { //only/multiply place/s with non-zero availability
        BigDecimal avQu = BigDecimal.ZERO;
        for (AItemPlace<?, ?> pl : places) {
          avQu = avQu.add(pl.getItsQuantity());
        }
        if (avQu.compareTo(cl.getQuant()) == -1) {
          isCompl = false;
          cl.setAvQuan(avQu);
          String errs = "!Not available item name/ID/type/quant/avail: "
            + cl.getItsName() + "/" + cl.getItId() + "/" + cl.getItTyp()
              + "/" + cl.getQuant() + "/" + avQu;
          this.log.warn(pRqVs, PrcCheckOut.class, errs);
        }
      }
      if (isCompl && cl.getPrice().compareTo(BigDecimal.ZERO) == 1) {
        //without free delivering:
        if (cl.getSeller() == null) {
          makeOrdLn(pRqVs, pur.getOrds(), null, cl, ts);
        } else {
          makeSeOrdLn(pRqVs, pur.getSords(), cl.getSeller(), null, cl, ts);
        }
      } else {
        getSrvOrm().updateEntity(pRqVs, cl);
      }
    }
    pRqDt.setAttribute("cart", cart);
    if (txRules != null) {
      pRqDt.setAttribute("txRules", txRules);
    }
    if (!isCompl) {
      redir(pRqVs, pRqDt);
    } else {
      saveOrds(pRqVs, pur, cart);
      saveSords(pRqVs, pur, cart);
      pRqDt.setAttribute("orders", pur.getOrds());
      pRqDt.setAttribute("sorders", pur.getSords());
    }
  }
461179
@Override
  public final void makeFirstPrepareForSave(final Map<String, Object> pAddParam,
    final Manufacture pEntity,
      final IRequestData pRequestData) throws Exception {
    // Beige-ORM refresh:
    pEntity.setManufacturingProcess(getSrvOrm()
      .retrieveEntity(pAddParam, pEntity.getManufacturingProcess()));
    pEntity.setInvItem(getSrvOrm()
      .retrieveEntity(pAddParam, pEntity.getInvItem()));
    if (!(InvItem.FINISHED_PRODUCT_ID.equals(pEntity.getInvItem()
      .getItsType().getItsId()) || InvItem.MATERIAL_ID
        .equals(pEntity.getInvItem().getItsType().getItsId()))) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "type_must_be_product_material");
    }
    if (pEntity.getItsQuantity().compareTo(pEntity.getManufacturingProcess()
      .getItsQuantity()) > 0) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "source_has_no_enough_item");
    }
    if (!pEntity.getUnitOfMeasure().getItsId().equals(pEntity
      .getManufacturingProcess().getUnitOfMeasure().getItsId())) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "UnitOfMeasure_fiffer_with_source");
    }
    if (pEntity.getItsQuantity().doubleValue() < 0
      && pEntity.getReversedId() == null) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "reversed_manufacture_is_null");
    }
    pEntity.setItsQuantity(pEntity.getItsQuantity().setScale(
      getSrvAccSettings().lazyGetAccSettings(pAddParam).getQuantityPrecision(),
        getSrvAccSettings().lazyGetAccSettings(pAddParam).getRoundingMode()));
    if (pEntity.getReversedId() != null) {
      Manufacture reversed = getSrvOrm().retrieveEntityById(pAddParam,
        Manufacture.class, pEntity.getReversedId());
      if (reversed.getReversedId() != null) {
        throw new ExceptionWithCode(ExceptionWithCode.FORBIDDEN,
          "Attempt to double reverse" + pAddParam.get("user"));
      }
      if (!reversed.getItsQuantity().equals(reversed.getTheRest())) {
        throw new ExceptionWithCode(ExceptionWithCode
          .WRONG_PARAMETER, "where_is_withdrawals_from_this_source");
      }
      reversed.setTheRest(BigDecimal.ZERO);
      getSrvOrm().updateEntity(pAddParam, reversed);
      pEntity.setTheRest(BigDecimal.ZERO);
    } else {
      pEntity.setTheRest(pEntity.getItsQuantity());
    }
    pEntity.setItsCost(pEntity.getManufacturingProcess().getItsCost());
    if (pEntity.getItsQuantity()
      .compareTo(pEntity.getManufacturingProcess().getItsQuantity()) == 0) {
      //to reduce rounding error:
      pEntity.setItsTotal(pEntity.getManufacturingProcess().getItsTotal());
    } else {
      pEntity.setItsTotal(pEntity.getItsCost()
        .multiply(pEntity.getItsQuantity()).setScale(getSrvAccSettings()
          .lazyGetAccSettings(pAddParam).getCostPrecision(), getSrvAccSettings()
            .lazyGetAccSettings(pAddParam).getRoundingMode()));
    }
  }
696945
@Override
  public final void process(final Map<String, Object> pRqVs,
    final IRequestData pRqDt) throws Exception {
    Cart cart = this.srvShoppingCart
      .getShoppingCart(pRqVs, pRqDt, false, false);
    if (cart == null) {
      redir(pRqVs, pRqDt);
      return;
    }
    String lnIdStr = pRqDt.getParameter("lnId");
    if (lnIdStr != null) {
      Long lnId = Long.valueOf(lnIdStr);
      CartLn cartLn = null;
      for (CartLn ci : cart.getItems()) {
        if (ci.getItsId().equals(lnId)) {
          if (ci.getDisab()) {
            throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
              "requested_item_disabled");
          }
          cartLn = ci;
          break;
        }
      }
      if (cartLn == null) {
        throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
          "requested_item_not_found");
      }
      if (cartLn.getForc()) {
        throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
          "requested_item_forced");
      }
      AccSettings as = (AccSettings) pRqVs.get("accSet");
      TaxDestination txRules = this.srvShoppingCart.revealTaxRules(pRqVs,
        cart, as);
      this.srvShoppingCart.delLine(pRqVs, cartLn, txRules);
      this.srvShoppingCart.hndCartChan(pRqVs, cart, txRules);
      if (txRules != null) {
        pRqDt.setAttribute("txRules", txRules);
      }
      redir(pRqVs, pRqDt);
    } else {
      throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
        "there_is_no_cart_item_id");
    }
  }
823563
@Override
  public final synchronized void handleSeSellerChanged(
    final Map<String, Object> pReqVars,
      final String pName) throws Exception {
    this.sesellers = null;
  }
207448
@Override
  public final void makeWarehouseRest(final Map<String, Object> pAddParam,
    final IMakingWarehouseEntry pEntity,
      final WarehouseSite pWhSite,
        final BigDecimal pQuantity) throws Exception {
    if (!pEntity.getIdDatabaseBirth()
      .equals(getSrvOrm().getIdDatabase())) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "can_not_make_ws_entry_for_foreign_src");
    }
    WarehouseRest wr = getSrvOrm().retrieveEntityWithConditions(pAddParam,
      WarehouseRest.class, "where WAREHOUSESITE="
        + pWhSite.getItsId() + " and INVITEM="
          + pEntity.getInvItem().getItsId() + " and UNITOFMEASURE="
            + pEntity.getUnitOfMeasure().getItsId());
    if (wr == null) {
      if (pQuantity.doubleValue() < 0) {
        throw new ExceptionWithCode(ExceptionWithCode.FORBIDDEN,
          "attempt_reverse_non_existent_good_in_warehouse");
      }
      wr = new WarehouseRest();
      wr.setIsNew(true);
      wr.setWarehouseSite(pWhSite);
      wr.setUnitOfMeasure(pEntity.getUnitOfMeasure());
      wr.setInvItem(pEntity.getInvItem());
    }
    wr.setTheRest(wr.getTheRest().add(pQuantity));
    if (wr.getTheRest().doubleValue() < 0) {
      throw new ExceptionWithCode(PurchaseInvoice.THERE_IS_NO_GOODS,
        "there_is_no_goods_in_stock");
    }
    if (wr.getIsNew()) {
      getSrvOrm().insertEntity(pAddParam, wr);
      wr.setIsNew(false);
    } else {
      if (this.fastLoc) {
        ColumnsValues cvs = new ColumnsValues();
        cvs.getFormula().add("itsVersion");
        cvs.getFormula().add("theRest");
        cvs.put("itsVersion", "ITSVERSION+1");
        if (pQuantity.compareTo(BigDecimal.ZERO) == -1) {
          cvs.put("theRest", "THEREST" + pQuantity);
        } else {
          cvs.put("theRest", "THEREST+" + pQuantity);
        }
        this.srvDb.executeUpdate("WAREHOUSEREST", cvs, "WAREHOUSESITE="
      + wr.getWarehouseSite().getItsId() + " and INVITEM=" + wr.getInvItem()
    .getItsId() + " and UNITOFMEASURE=" + wr.getUnitOfMeasure().getItsId());
      } else {
        getSrvOrm().updateEntity(pAddParam, wr);
      }
    }
  }
785159
@Override
  public final <T> void deleteEntity(
    final Map<String, Object> pAddParam,
      final T pEntity) throws Exception {
    pAddParam.put("isOnlyId", Boolean.TRUE);
    ColumnsValues columnsValues = evalColumnsValues(pAddParam, pEntity);
    pAddParam.remove("isOnlyId");
    String whereId = evalWhereId(pEntity, columnsValues);
    getSrvDatabase().executeDelete(pEntity.getClass()
      .getSimpleName().toUpperCase(), whereId);
  }
576635
@Override
  public final void handle(final Map<String, Object> pReqVars,
    final IRequestData pRequestData,
      final OutputStream pSous) throws Exception {
    try {
      String nmEnt = pRequestData.getParameter("nmEnt");
      Class entityClass = this.entitiesMap.get(nmEnt);
      this.srvDatabase.setIsAutocommit(false);
      this.srvDatabase.setTransactionIsolation(this.readTi);
      this.srvDatabase.beginTransaction();
      IHasId<?> entity = null;
      @SuppressWarnings("unchecked")
      IFactorySimple<IHasId<?>> entFac = (IFactorySimple<IHasId<?>>)
        this.entitiesFactoriesFatory.lazyGet(pReqVars, entityClass);
      entity = entFac.create(pReqVars);
      this.fillEntityFromReq.fill(pReqVars, entity, pRequestData);
      String reporterNm = pRequestData.getParameter("reporterNm");
      @SuppressWarnings("unchecked")
      IEntityFileReporter<IHasId<?>, ?> efr =
        (IEntityFileReporter<IHasId<?>, ?>)
          this.fctEntitiesFileReporters.lazyGet(pReqVars, reporterNm);
      efr.makeReport(pReqVars, entity, pRequestData, pSous);
      this.srvDatabase.commitTransaction();
    } catch (Exception ex) {
      if (!this.srvDatabase.getIsAutocommit()) {
        this.srvDatabase.rollBackTransaction();
      }
      throw ex;
    } finally {
      this.srvDatabase.releaseResources();
    }
  }
902209
@Override
  public final void makeFirstPrepareForSave(final Map<String, Object> pReqVars,
    final SalesInvoice pEntity,
      final IRequestData pRequestData) throws Exception {
    if (pEntity.getPrepaymentFrom() != null) {
      pEntity.setPrepaymentFrom(getSrvOrm()
        .retrieveEntity(pReqVars, pEntity.getPrepaymentFrom()));
      if (pEntity.getReversedId() == null && pEntity.getPrepaymentFrom()
        .getSalesInvoiceId() != null && !pEntity.getHasMadeAccEntries()) {
        throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
          "prepayment_already_in_use");
      }
      if (pEntity.getReversedId() == null && !pEntity.getPrepaymentFrom()
        .getCustomer().getItsId().equals(pEntity.getCustomer().getItsId())) {
        throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
          "prepayment_for_different_vendor");
      }
    }
    if (pEntity.getReversedId() != null && pEntity.getPrepaymentFrom() != null
      && pEntity.getPaymentTotal().compareTo(pEntity.getPrepaymentFrom()
        .getItsTotal()) != 0) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "reverse_payments_first");
    }
    if (pEntity.getReversedId() != null && pEntity.getPrepaymentFrom() == null
      && pEntity.getPaymentTotal().compareTo(BigDecimal.ZERO) != 0) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "reverse_payments_first");
    }
    if (pEntity.getReversedId() == null) {
      calculateTotalPayment(pReqVars, pEntity);
    }
    if (!pEntity.getIsNew()) {
      pReqVars.put("DebtorCreditortaxDestinationdeepLevel", 2);
      Set<String> ndFlDc = new HashSet<String>();
      ndFlDc.add("itsId");
      ndFlDc.add("isForeigner");
      ndFlDc.add("taxDestination");
      pReqVars.put("DebtorCreditorneededFields", ndFlDc);
    }
  }
886228
@Override
  public final void makeOtherEntries(final Map<String, Object> pAddParam,
    final GoodsLoss pEntity, final IRequestData pRequestData,
      final boolean pIsNew) throws Exception {
    String actionAdd = pRequestData.getParameter("actionAdd");
    if ("makeAccEntries".equals(actionAdd)
      && pEntity.getReversedId() != null) {
      //reverse none-reversed lines:
      GoodsLossLine gll = new GoodsLossLine();
      GoodsLoss reversed = new GoodsLoss();
      reversed.setItsId(pEntity.getReversedId());
      gll.setItsOwner(reversed);
      List<GoodsLossLine> reversedLines = getSrvOrm().
        retrieveListForField(pAddParam, gll, "itsOwner");
      String langDef = (String) pAddParam.get("langDef");
      for (GoodsLossLine reversedLine : reversedLines) {
        if (reversedLine.getReversedId() == null) {
          GoodsLossLine reversingLine = new GoodsLossLine();
          reversingLine.setIdDatabaseBirth(getSrvOrm().getIdDatabase());
          reversingLine.setReversedId(reversedLine.getItsId());
          reversingLine.setInvItem(reversedLine.getInvItem());
          reversingLine.setUnitOfMeasure(reversedLine.getUnitOfMeasure());
          reversingLine.setItsQuantity(reversedLine.getItsQuantity()
            .negate());
          reversingLine.setIsNew(true);
          reversingLine.setItsOwner(pEntity);
          reversingLine.setDescription(getSrvI18n()
            .getMsg("reversed_n", langDef) + reversedLine
              .getIdDatabaseBirth() + "-" + reversedLine.getItsId()); //local
          getSrvOrm().insertEntity(pAddParam, reversingLine);
          reversingLine.setIsNew(false);
          getSrvWarehouseEntry().reverseDraw(pAddParam, reversingLine);
          getSrvCogsEntry().reverseDraw(pAddParam, 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(pAddParam, reversedLine);
        }
      }
    }
  }