<p>Retrieve entity from DB.</p>
@param <T> entity type
@param pAddParam additional params, e.g. already retrieved TableSql.
@param pEntityClass entity class
@param pRecordSet record set
@return entity
@throws Exception - an exception
482603
public final <T> T retrieveEntity(final Map<String, Object> pAddParam,
    final Class<T> pEntityClass,
      final IRecordSet<RS> pRecordSet) throws Exception {
    @SuppressWarnings("unchecked")
    IFactorySimple<T> facEn = (IFactorySimple<T>) this.entitiesFactoriesFatory
      .lazyGet(pAddParam, pEntityClass);
    T entity = facEn.create(pAddParam);
    String foreignFieldNmsNm = "foreignFieldNms";
    List<String> foreignFieldNms = new ArrayList<String>();
    pAddParam.put(foreignFieldNmsNm, foreignFieldNms);
    String currentLevelNm = "currentLevel";
    List<Integer> currentLevel = new ArrayList<Integer>();
    currentLevel.add(1);
    pAddParam.put(currentLevelNm, currentLevel);
    String deepLevelNm = "deepLevel";
    List<Integer> deepLevel = new ArrayList<Integer>();
    deepLevel.add(2); //default top level
    pAddParam.put(deepLevelNm, deepLevel);
    this.fillerEntitiesFromRs.fill(pAddParam, entity, pRecordSet);
    //(TODO itself) exit from all recursions:
    pAddParam.remove(currentLevelNm);
    pAddParam.remove(deepLevelNm);
    pAddParam.remove(foreignFieldNmsNm);
    return entity;
  }
587222
protected final PrcPageWithSubaccTypes<RS>
    createPutPrcPageWithSubaccTypes(
      final Map<String, Object> pAddParam) throws Exception {
    PrcPageWithSubaccTypes<RS> proc = new PrcPageWithSubaccTypes<RS>();
    PrcEntitiesPage procDlg = (PrcEntitiesPage) this.fctBnProcessors
      .lazyGet(pAddParam, PrcEntitiesPage.class.getSimpleName());
    proc.setPrcAccEntitiesPage(procDlg);
    proc.setSrvTypeCode(getSrvTypeCode());
    //assigning fully initialized object:
    this.processorsMap
      .put(PrcPageWithSubaccTypes.class.getSimpleName(), proc);
    return proc;
  }
1033693
@Override
  public final void process(final Map<String, Object> pAddParam,
    final IRequestData pRequestData) throws Exception {
    this.prcAccEntitiesPage.process(pAddParam, pRequestData);
    pRequestData.setAttribute("typeCodeSubaccMap",
      this.srvTypeCode.getTypeCodeMap());
  }
544227
@Deprecated
  protected byte[] getPayloadBytes(GenericRecord inputRecord) {
    try {
      return getFieldAsBytes(inputRecord, payloadField);
    } catch (Exception e) {
      return null;
    }
  }
666177
@PostMapping(
      value = "/{entityTypeId}/{id}",
      params = "_method=GET",
      produces = APPLICATION_JSON_VALUE)
  @ResponseBody
  public Map<String, Object> retrieveEntity(
      @PathVariable("entityTypeId") String entityTypeId,
      @PathVariable("id") String untypedId,
      @Valid @RequestBody EntityTypeRequest request) {
    Set<String> attributesSet = toAttributeSet(request != null ? request.getAttributes() : null);
    Map<String, Set<String>> attributeExpandSet =
        toExpandMap(request != null ? request.getExpand() : null);

    EntityType meta = dataService.getEntityType(entityTypeId);
    Object id = getTypedValue(untypedId, meta.getIdAttribute());
    Entity entity = dataService.findOneById(entityTypeId, id);

    if (entity == null) {
      throw new UnknownEntityException(meta, untypedId);
    }

    return getEntityAsMap(entity, meta, attributesSet, attributeExpandSet);
  }
839398
protected final PrcEntityFfolDelete<RS, IHasId<Object>, Object>
    createPutPrcEntityFfolDelete(
      final Map<String, Object> pAddParam) throws Exception {
    @SuppressWarnings("unchecked")
    PrcEntityFfolDelete<RS, IHasId<Object>, Object> proc =
      (PrcEntityFfolDelete<RS, IHasId<Object>, Object>)
        this.fctBnEntitiesProcessors
          .lazyGet(pAddParam, PrcEntityFfolDelete.class.getSimpleName());
    //assigning fully initialized object:
    this.processorsMap.put(PrcEntityFfolDelete.class.getSimpleName(), proc);
    return proc;
  }
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;
  }
1325623
@Override
  public final IEntityFileReporter lazyGet(
    final Map<String, Object> pAddParam,
      final String pBeanName) throws Exception {
    IEntityFileReporter proc =
      this.reportersMap.get(pBeanName);
    if (proc == null) {
      // locking:
      synchronized (this) {
        // make sure again whether it's null after locking:
        proc = this.reportersMap.get(pBeanName);
        if (proc == null
          && pBeanName.equals(InvoiceReportPdf.class.getSimpleName())) {
          proc = lazyGetInvoiceReportPdf(pAddParam);
        }
      }
    }
    if (proc == null) {
      throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
        "There is no entity processor with name " + pBeanName);
    }
    return proc;
  }
1346225
@Override
  public final String getFor(final Class<?> pClass, final String pThingName) {
    if ("entityEdit".equals(pThingName)) {
      if (IPersistableBase.class.isAssignableFrom(pClass)) {
        return PrcEntityPbEditDelete.class.getSimpleName();
      } else {
        return PrcEntityRetrieve.class.getSimpleName();
      }
    } else if ("entityPrint".equals(pThingName)) {
      return PrcEntityRetrieve.class.getSimpleName();
    } else if ("entityCopy".equals(pThingName)) {
      if (IPersistableBase.class.isAssignableFrom(pClass)) {
        return PrcEntityPbCopy.class.getSimpleName();
      } else {
        return PrcEntityCopy.class.getSimpleName();
      }
    } else if ("entitySave".equals(pThingName)) {
      if (IPersistableBase.class.isAssignableFrom(pClass)) {
        return PrcEntityPbSave.class.getSimpleName();
      } else if (EmailMsg.class == pClass) {
        return PrcEmailMsgSave.class.getSimpleName();
      } else {
        return PrcEntitySave.class.getSimpleName();
      }
    } else if ("entityFolDelete".equals(pThingName)) {
      if (Eattachment.class == pClass) {
        return PrcEntityFfolDelete.class.getSimpleName();
      }
      return PrcEntityFolDelete.class.getSimpleName();
    } else if ("entityFolSave".equals(pThingName)) {
      if (Eattachment.class == pClass) {
        return PrcEntityFfolSave.class.getSimpleName();
      }
      return PrcEntityFolSave.class.getSimpleName();
    } else if ("entityDelete".equals(pThingName)) {
      if (IPersistableBase.class.isAssignableFrom(pClass)) {
        return PrcEntityPbDelete.class.getSimpleName();
      } else {
        return PrcEntityDelete.class.getSimpleName();
      }
    } else if ("entityCreate".equals(pThingName)) {
      if (CsvColumn.class == pClass) {
        return PrcCsvColumnCreate.class.getSimpleName();
      } else if (MatchForeignLine.class == pClass) {
        return PrcMatchForeignLineCreate.class.getSimpleName();
      } else {
        return PrcEntityCreate.class.getSimpleName();
      }
    } else if ("entityConfirmDelete".equals(pThingName)) {
      if (IPersistableBase.class.isAssignableFrom(pClass)) {
        return PrcEntityPbEditDelete.class.getSimpleName();
      } else {
        return PrcEntityRetrieve.class.getSimpleName();
      }
    }
    return null;
  }
78172
public final <T extends IHasIdLongVersionName> void makeIt(
    final Map<String, Object> pAddParam, final IRequestData pRequestData,
      final Class<T> pItemClass) throws Exception {
    Set<String> filterAppearance = new HashSet<String>();
    pAddParam.put("filterAppearance", filterAppearance);
    StringBuffer sbWhere = this.srvEntitiesPage
      .revealPageFilterData(pAddParam, pRequestData, pItemClass);
    if (sbWhere.length() == 0) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "filter_must_be_not_empty");
    }
    String itemsCatalogAction = pRequestData
      .getParameter("itemsCatalogAction");
    if (!("add".equals(itemsCatalogAction)
      || "remove".equals(itemsCatalogAction))) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "wrong_action");
    }
    Long catalogId = Long.valueOf(pRequestData
      .getParameter(CatalogGs.class.getSimpleName() + ".itsId"));
    if (catalogId == null) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "catalog_must_be_not_empty");
    }
    CatalogGs catalogOfGoods = this.srvOrm
      .retrieveEntityById(pAddParam, CatalogGs.class, catalogId);
    if (catalogOfGoods == null) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "catalog_must_be_not_empty");
    }
    if (catalogOfGoods.getHasSubcatalogs()) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "catalog_must_not_has_subcatalog");
    }
    String whereStr = sbWhere.toString();
    Integer rowCount = this.srvOrm.evalRowCountWhere(pAddParam, pItemClass,
        whereStr);
    TradingSettings ts = (TradingSettings) pAddParam.get("tradSet");
    if (rowCount > ts.getMaxQuantityOfBulkItems()) {
      throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
        "filtered_list_size_exceed_max_bulk");
    }
    Integer totalItems = Integer
      .valueOf(pRequestData.getParameter("totalItems"));
    if (!rowCount.equals(totalItems)) {
      throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
        "filtered_list_has_changed");
    }
    List<T> itemsList = this.srvOrm.retrieveListWithConditions(pAddParam,
      pItemClass, "where " + whereStr);
    for (T items : itemsList) {
      AItemCatalog ic;
      if (pItemClass == InvItem.class) {
        ic = new GoodsCatalog();
      } else if (pItemClass == ServiceToSale.class) {
        ic = new ServiceCatalog();
      } else {
        throw new Exception("NEI: " + pItemClass);
      }
      ic.setItsCatalog(catalogOfGoods);
      ic.setItem(items);
      if ("add".equals(itemsCatalogAction)) {
        // add items to catalog
        this.srvOrm.insertEntity(pAddParam, ic);
      } else {
        // remove items from catalog
        this.srvOrm.deleteEntity(pAddParam, ic);
      }
    }
    pRequestData.setAttribute("itemsCatalogAction", itemsCatalogAction);
    pRequestData.setAttribute("filterAppearance", filterAppearance);
    pRequestData.setAttribute("totalItems", totalItems);
    pRequestData.setAttribute("itemsList", itemsList);
    pRequestData.setAttribute("catalogOfItems", catalogOfGoods);
  }
941824
static Object getPostgreSqlValue(Entity entity, Attribute attr) {
    String attrName = attr.getName();
    AttributeType attrType = attr.getDataType();

    switch (attrType) {
      case BOOL:
        return entity.getBoolean(attrName);
      case CATEGORICAL:
      case XREF:
        Entity xrefEntity = entity.getEntity(attrName);
        return xrefEntity != null
            ? getPostgreSqlValue(xrefEntity, xrefEntity.getEntityType().getIdAttribute())
            : null;
      case CATEGORICAL_MREF:
      case MREF:
      case ONE_TO_MANY:
        Iterable<Entity> entities = entity.getEntities(attrName);
        return stream(entities)
            .map(
                mrefEntity ->
                    getPostgreSqlValue(mrefEntity, mrefEntity.getEntityType().getIdAttribute()))
            .collect(toList());
      case DATE:
        return entity.getLocalDate(attrName);
      case DATE_TIME:
        // As a workaround for #5674, we don't store milliseconds
        Instant instant = entity.getInstant(attrName);
        return instant != null ? instant.truncatedTo(ChronoUnit.SECONDS).atOffset(UTC) : null;
      case DECIMAL:
        return entity.getDouble(attrName);
      case EMAIL:
      case ENUM:
      case HTML:
      case HYPERLINK:
      case SCRIPT:
      case STRING:
      case TEXT:
        return entity.getString(attrName);
      case FILE:
        FileMeta fileEntity = entity.getEntity(attrName, FileMeta.class);
        return fileEntity != null
            ? getPostgreSqlValue(fileEntity, fileEntity.getEntityType().getIdAttribute())
            : null;
      case INT:
        return entity.getInt(attrName);
      case LONG:
        return entity.getLong(attrName);
      case COMPOUND:
        throw new IllegalAttributeTypeException(attrType);
      default:
        throw new UnexpectedEnumException(attrType);
    }
  }
1141471
protected final PrcBankStatementLineGfe<RS> lazyGetPrcBankStatementLineGfe(
    final Map<String, Object> pAddParam) throws Exception {
    @SuppressWarnings("unchecked")
    PrcBankStatementLineGfe<RS> proc = (PrcBankStatementLineGfe<RS>)
      this.processorsMap.get(PrcBankStatementLineGfe.class.getSimpleName());
    if (proc == null) {
      proc = new PrcBankStatementLineGfe<RS>();
      proc.setSrvOrm(getSrvOrm());
      proc.setSrvTypeCode(getSrvTypeCode());
      @SuppressWarnings("unchecked")
      PrcEntityPbEditDelete<RS, BankStatementLine> procDlg =
    (PrcEntityPbEditDelete<RS, BankStatementLine>) this.fctBnEntitiesProcessors
  .lazyGet(pAddParam, PrcEntityPbEditDelete.class.getSimpleName());
      proc.setPrcEntityPbEditDelete(procDlg);
      //assigning fully initialized object:
      this.processorsMap
        .put(PrcBankStatementLineGfe.class.getSimpleName(), proc);
    }
    return proc;
  }
922112
@Override
  public final <T> Integer evalRowCount(
    final Map<String, Object> pAddParam,
      final Class<T> pEntityClass) throws Exception {
    String query = "select count(*) as TOTALROWS from " + pEntityClass
      .getSimpleName().toUpperCase() + ";";
    return evalRowCountByQuery(pAddParam, pEntityClass, query);
  }
467462
@Override
  public final SeGoodsSpecifics process(final Map<String, Object> pReqVars,
    final SeGoodsSpecifics pEntity,
      final IRequestData pRequestData) throws Exception {
    SeSeller ses = findSeSeller.find(pReqVars, pRequestData.getUserName());
    pEntity.setSeller(ses);
    pEntity.setSpecifics(getSrvOrm().retrieveEntity(pReqVars,
      pEntity.getSpecifics()));
    if (pEntity.getSpecifics().getChooseableSpecificsType() != null) {
      pEntity.setLongValue2(pEntity.getSpecifics().getChooseableSpecificsType()
        .getItsId());
      pEntity.setStringValue2(pEntity.getSpecifics()
        .getChooseableSpecificsType().getItsName());
    }
    if (pEntity.getIsNew()) {
      this.srvOrm.insertEntity(pReqVars, pEntity);
      pEntity.setIsNew(false);
    } else {
      SeGoodsSpecifics 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;
  }
948379
@Override
  public final synchronized BalanceSheet retrieveBalance(
    final Map<String, Object> pAddParam,
      final Date pDate) throws Exception {
    getSrvBalance().recalculateAllIfNeed(pAddParam, pDate);
    BalanceSheet result = new BalanceSheet();
    result.setItsDate(pDate);
    String query = evalQueryBalance(pAddParam, pDate);
    IRecordSet<RS> recordSet = null;
    try {
      recordSet = getSrvDatabase().retrieveRecords(query);
      if (recordSet.moveToFirst()) {
        do {
          String accName = recordSet.getString("ACCOUNTNAME");
          Integer accType = recordSet.getInteger("ITSTYPE");
          String accNumber = recordSet.getString("ITSNUMBER");
          Double debit = recordSet.getDouble("DEBIT");
          Double credit = recordSet.getDouble("CREDIT");
          if (debit != 0 || credit != 0) {
            BalanceLine bl = new BalanceLine();
            bl.setAccName(accName);
            bl.setAccNumber(accNumber);
            bl.setAccType(accType);
            bl.setDebit(BigDecimal.valueOf(debit).setScale(
              getSrvAccSettings().lazyGetAccSettings(pAddParam)
                .getBalancePrecision(), getSrvAccSettings()
                  .lazyGetAccSettings(pAddParam).getRoundingMode()));
            bl.setCredit(BigDecimal.valueOf(credit).setScale(
              getSrvAccSettings().lazyGetAccSettings(pAddParam)
                .getBalancePrecision(), getSrvAccSettings()
                  .lazyGetAccSettings(pAddParam).getRoundingMode()));
            if (bl.getDebit().doubleValue() != 0
              || bl.getCredit().doubleValue() != 0) {
              result.getItsLines().add(bl);
              if (accType == 0) {
                result.setTotalLinesAssets(result.getTotalLinesAssets() + 1);
                result.setTotalAssets(result.getTotalAssets().add(bl.getDebit()
                  .subtract(bl.getCredit())));
              } else if (accType == 1) {
                result.setTotalLinesLiabilities(result
                  .getTotalLinesLiabilities() + 1);
                result.setTotalLiabilities(result.getTotalLiabilities()
                  .add(bl.getCredit().subtract(bl.getDebit())));
              } else if (accType == 2) {
                result.setTotalLinesOwnersEquity(result
                  .getTotalLinesOwnersEquity() + 1);
                result.setTotalOwnersEquity(result.getTotalOwnersEquity()
                  .add(bl.getCredit().subtract(bl.getDebit())));
              }
            }
          }
        } while (recordSet.moveToNext());
      }
    } finally {
      if (recordSet != null) {
        recordSet.close();
      }
    }
    result.setDetailRowsCount(Math.max(result.getTotalLinesAssets(),
      result.getTotalLinesLiabilities() + result
        .getTotalLinesOwnersEquity() + 3)); //3 -total l, title e ,total e
    return result;
  }
653997
public EntityType getEntityType(Class<?> entityClass) {
    String className = entityClass.getName();
    EntityType type = entityTypes.get(className);
    if (null != type) { return type; }

    type = classEntityTypes.get(className);
    if (null == type) {
      List<EntityType> matched = CollectUtils.newArrayList();
      for (EntityType entityType : entityTypes.values()) {
        if (className.equals(entityType.getEntityName())
            || className.equals(entityType.getEntityClass().getName())) {
          matched.add(entityType);
        }
      }
      if (matched.size() > 1) { throw new RuntimeException("multi-entityName for class:" + className); }
      if (matched.isEmpty()) {
        EntityType tmp = new EntityType(entityClass);
        classEntityTypes.put(className, tmp);
        return tmp;
      } else {
        classEntityTypes.put(className, matched.get(0));
        type = (EntityType) matched.get(0);
      }
    }
    return type;
  }
461183
@Override
  public final <T> void fill(final Map<String, Object> pAddParam,
    final T pEntity, final IRequestData pReq) throws Exception {
    boolean isDbgSh = this.logger.getDbgSh(this.getClass())
      && this.logger.getDbgFl() < 7010 && this.logger.getDbgCl() > 7015;
    if (isDbgSh) {
      this.logger.debug(null, FillEntityFromReq.class,
        "Default charset = " + Charset.defaultCharset());
    }
    @SuppressWarnings("unchecked")
    IFillerObjectFields<T> filler = (IFillerObjectFields<T>)
      this.fillersFieldsFactory.lazyGet(pAddParam, pEntity.getClass());
    for (String fieldName : filler.getFieldsNames()) {
      try {
        String valStr = pReq.getParameter(pEntity.getClass().getSimpleName()
          + "." + fieldName); // standard
        if (valStr != null) { // e.g. Boolean checkbox or none-editable
          String convName = this.fieldConverterNamesHolder.getFor(pEntity
           .getClass(), fieldName);
          if (isDbgSh) {
            this.logger.debug(null, FillEntityFromReq.class,
              "Try fill field/inClass/converterName/value: " + fieldName + "/"
                + pEntity.getClass().getCanonicalName() + "/" + convName
                  + "/" + valStr);
          }
          IConverterToFromString conv = this.convertersFieldsFatory
            .lazyGet(pAddParam, convName);
          Object fieldVal = conv.fromString(pAddParam,  valStr);
          if (fieldVal != null && isDbgSh) {
              this.logger.debug(null, FillEntityFromReq.class,
                "Converted fieldClass/toString: " + fieldVal.getClass()
                  .getCanonicalName() + "/" + fieldVal);
          }
          filler.fill(pAddParam, pEntity, fieldVal, fieldName);
        }
      } catch (Exception ex) {
        String msg = "Can't fill field/class: " + fieldName + "/"
          + pEntity.getClass().getCanonicalName();
        throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG, msg, ex);
      }
    }
  }