/**
  * {@inheritDoc}<br>
  * Обрабатываем лишь специфичные для детальной формы состояния.
  */
 @Override
 protected boolean isAcceptableWorkstate(WorkstateEnum workstate) {
   return SEARCH.equals(workstate)
       || CREATE.equals(workstate)
       || VIEW_DETAILS.equals(workstate)
       || EDIT.equals(workstate);
 }
  /**
   * Обработчик события сохранения 'save' В зависимости от состояния выполняет сохранение
   * существующего или создание нового объекта.
   *
   * <p>Метод используется в случае использования стандартного сервиса работы с данными
   * JepStandardService. При реализации в прикладном модуле собственного сервиса необходимо в
   * презентере-наследнике прикладного модуля реализовать перекрывающий метод onSave().
   */
  public void onSave(SaveEvent event) {
    if (fields.isValid()) {
      JepRecord formProperties = fields.getValues();

      logger.debug(this.getClass() + ".onSave(): formProperties = " + formProperties);

      // Для подчинённых объектов добавляется foreignKey.
      if (JepScopeStack.instance.size() > 1 || !JepScopeStack.instance.peek().isMainActive()) {
        JepClientUtil.addForeignKey(formProperties);
      }

      // Для режима редактирования текущую запись
      // необходимо дополнить или переписать значениями с формы.
      if (EDIT.equals(_workstate)) {
        JepRecord updatedRecord = new JepRecord(currentRecord);
        updatedRecord.update(formProperties);
        formProperties = updatedRecord;
      }

      // Если не выполнены первоначальные условия проверки, то выходим из сохранения.
      if (!beforeSave(formProperties)) return;

      eventBus.setSaveButtonEnabled(false);

      if (CREATE.equals(_workstate)) {
        saveOnCreate(formProperties);
      } else if (EDIT.equals(_workstate)) {
        saveOnEdit(formProperties);
      }

    } else {
      messageBox.showError(clientFactory.getTexts().errors_dialog_form_incorrectInputData());
    }
  }
  protected void onChangeWorkstate(WorkstateEnum workstate) {
    fields.changeWorkstate(workstate);

    if (VIEW_DETAILS.equals(workstate)) {
      fields.setValues(currentRecord);
      updateScope(workstate);
    } else if (EDIT.equals(workstate)) {
      fields.setValues(currentRecord);
      updateScope(workstate);
    } else if (CREATE.equals(workstate)) {
      fields.clear();
      resetScope();
    } else if (SEARCH.equals(workstate)) {
      if (searchTemplate != null) {
        // Если есть сохраненные поисковые параметры, то восстановим их.
        fields.setValues(searchTemplate);
      } else {
        // Очистим поля, если сохраненные поисковые параметры отсутствуют.
        fields.clear();
      }

      resetScope();
    }
  }
  private AuthorizationContext getAuthCtx() {

    String resource = getPath();

    SolrParams params = getQueryParams();
    final ArrayList<CollectionRequest> collectionRequests = new ArrayList<>();
    if (getCollectionsList() != null) {
      for (String collection : getCollectionsList()) {
        collectionRequests.add(new CollectionRequest(collection));
      }
    }

    // Extract collection name from the params in case of a Collection Admin request
    if (getPath().equals("/admin/collections")) {
      if (CREATE.isEqual(params.get("action"))
          || RELOAD.isEqual(params.get("action"))
          || DELETE.isEqual(params.get("action")))
        collectionRequests.add(new CollectionRequest(params.get("name")));
      else if (params.get(COLLECTION_PROP) != null)
        collectionRequests.add(new CollectionRequest(params.get(COLLECTION_PROP)));
    }

    // Handle the case when it's a /select request and collections are specified as a param
    if (resource.equals("/select") && params.get("collection") != null) {
      collectionRequests.clear();
      for (String collection : params.get("collection").split(",")) {
        collectionRequests.add(new CollectionRequest(collection));
      }
    }

    // Populate the request type if the request is select or update
    if (requestType == RequestType.UNKNOWN) {
      if (resource.startsWith("/select") || resource.startsWith("/get"))
        requestType = RequestType.READ;
      if (resource.startsWith("/update")) requestType = RequestType.WRITE;
    }

    // There's no collection explicitly mentioned, let's try and extract it from the core if one
    // exists for
    // the purpose of processing this request.
    if (getCore() != null && (getCollectionsList() == null || getCollectionsList().size() == 0)) {
      collectionRequests.add(
          new CollectionRequest(getCore().getCoreDescriptor().getCollectionName()));
    }

    if (getQueryParams().get(COLLECTION_PROP) != null)
      collectionRequests.add(new CollectionRequest(getQueryParams().get(COLLECTION_PROP)));

    return new AuthorizationContext() {
      @Override
      public SolrParams getParams() {
        return solrReq.getParams();
      }

      @Override
      public Principal getUserPrincipal() {
        return getReq().getUserPrincipal();
      }

      @Override
      public String getHttpHeader(String s) {
        return getReq().getHeader(s);
      }

      @Override
      public Enumeration getHeaderNames() {
        return getReq().getHeaderNames();
      }

      @Override
      public List<CollectionRequest> getCollectionRequests() {
        return collectionRequests;
      }

      @Override
      public RequestType getRequestType() {
        return requestType;
      }

      public String getResource() {
        return path;
      }

      @Override
      public String getHttpMethod() {
        return getReq().getMethod();
      }

      @Override
      public Object getHandler() {
        return handler;
      }

      @Override
      public String toString() {
        StringBuilder response =
            new StringBuilder("userPrincipal: [")
                .append(getUserPrincipal())
                .append("]")
                .append(" type: [")
                .append(requestType.toString())
                .append("], collections: [");
        for (CollectionRequest collectionRequest : collectionRequests) {
          response.append(collectionRequest.collectionName).append(", ");
        }
        if (collectionRequests.size() > 0)
          response.delete(response.length() - 1, response.length());

        response.append("], Path: [").append(resource).append("]");
        response.append(" path : ").append(path).append(" params :").append(solrReq.getParams());
        return response.toString();
      }

      @Override
      public String getRemoteAddr() {
        return getReq().getRemoteAddr();
      }

      @Override
      public String getRemoteHost() {
        return getReq().getRemoteHost();
      }
    };
  }