/**
   * @param accessCode - строковой код доступа к документу
   * @param organID - номер-�?Д субьекта-органа оператора документа
   * @param docTypeID - номер-�?Д типа документа (опционально)
   * @param password - строка-пароль (опционально)
   */
  @RequestMapping(
      value = "/getDocumentAccessByHandler",
      method = RequestMethod.GET,
      headers = {"Accept=application/json"})
  public @ResponseBody Document getDocumentAccessByHandler(
      @RequestParam(value = "sCode_DocumentAccess") String accessCode,
      @RequestParam(value = "nID_DocumentOperator_SubjectOrgan") Long organID,
      @RequestParam(value = "nID_DocumentType", required = false) Long docTypeID,
      @RequestParam(value = "sPass", required = false) String password,
      HttpServletResponse resp) {

    Document document =
        handlerFactory
            .buildHandlerFor(documentDao.getOperator(organID))
            .setDocumentType(docTypeID)
            .setAccessCode(accessCode)
            .setPassword(password)
            .getDocument();
    try {
      createHistoryEvent(
          HistoryEventType.GET_DOCUMENT_ACCESS_BY_HANDLER,
          document.getSubject().getId(),
          subjectOrganDao.getSubjectOrgan(organID).getName(),
          null,
          document);
    } catch (Exception e) {
      log.warn("can`t create history event!", e);
    }
    return document;
  }
 @RequestMapping(value = "/getDocumentContent", method = RequestMethod.GET)
 public @ResponseBody String getDocumentContent(
     @RequestParam(value = "nID") Long id, @RequestParam(value = "nID_Subject") long nID_Subject)
     throws ActivitiRestException {
   Document document = documentDao.getDocument(id);
   if (nID_Subject != document.getSubject().getId()) {
     throw new ActivitiRestException("401", "You don't have access!");
   } else {
     return Util.contentByteToString(
         documentDao.getDocumentContent(document.getContentKey())); // ????
   }
 }
 @RequestMapping(value = "/getDocument", method = RequestMethod.GET)
 public @ResponseBody Document getDocument(
     @RequestParam(value = "nID") Long id, @RequestParam(value = "nID_Subject") long nID_Subject)
     throws ActivitiRestException {
   Document document = documentDao.getDocument(id);
   if (nID_Subject != document.getSubject().getId()) {
     throw new ActivitiRestException(
         "401",
         "You don't have access! Your nID = "
             + nID_Subject
             + " Document's Subject's nID = "
             + document.getSubject().getId());
   } else {
     return document;
   }
 }
 private void createHistoryEvent(
     HistoryEventType eventType,
     Long nID_Subject,
     String sSubjectName_Upload,
     Long nID_Document,
     Document document) {
   Map<String, String> values = new HashMap<>();
   try {
     Document oDocument = document == null ? documentDao.getDocument(nID_Document) : document;
     values.put(HistoryEventMessage.DOCUMENT_TYPE, oDocument.getDocumentType().getName());
     values.put(HistoryEventMessage.DOCUMENT_NAME, oDocument.getName());
     values.put(HistoryEventMessage.ORGANIZATION_NAME, sSubjectName_Upload);
   } catch (Throwable e) {
     log.warn("can't get document info!", e);
   }
   try {
     String eventMessage = HistoryEventMessage.createJournalMessage(eventType, values);
     historyEventDao.setHistoryEvent(nID_Subject, eventType.getnID(), eventMessage, eventMessage);
   } catch (IOException e) {
     log.error("error during creating HistoryEvent", e);
   }
 }
  @RequestMapping(value = "/getDocumentFile", method = RequestMethod.GET)
  public @ResponseBody byte[] getDocumentFile(
      @RequestParam(value = "nID") Long id,
      @RequestParam(value = "nID_Subject") long nID_Subject,
      @RequestParam(value = "sCode_DocumentAccess", required = false) String accessCode,
      @RequestParam(value = "nID_DocumentOperator_SubjectOrgan", required = false) Long organID,
      @RequestParam(value = "nID_DocumentType", required = false) Long docTypeID,
      @RequestParam(value = "sPass", required = false) String password,
      HttpServletRequest request,
      HttpServletResponse httpResponse)
      throws ActivitiRestException {
    Document document = documentDao.getDocument(id);
    if (nID_Subject != document.getSubject().getId()) {

      if (accessCode != null) {
        Document oDocument =
            handlerFactory
                .buildHandlerFor(documentDao.getOperator(organID))
                .setDocumentType(docTypeID)
                .setAccessCode(accessCode)
                .setPassword(password)
                .getDocument();
        if (oDocument == null) {
          throw new ActivitiRestException("401", "You don't have access by accessCode!");
        }
      } else {
        throw new ActivitiRestException("401", "You don't have access!");
      }
    }
    byte[] content = documentDao.getDocumentContent(document.getContentKey());
    // byte[] content = "".getBytes();

    httpResponse.setHeader("Content-disposition", "attachment; filename=" + document.getFile());
    // httpResponse.setHeader("Content-Type", document.getDocumentContentType()
    //		.getName() + ";charset=UTF-8");
    httpResponse.setHeader("Content-Type", document.getContentType() + ";charset=UTF-8");
    httpResponse.setContentLength(content.length);
    return content;
  }
  public Document getDocument() {
    Document doc = new Document();
    String sessionId;
    String keyIdParam;
    String callBackKey = "&callbackUrl=";
    String callBackValue = generalConfig.sURL_DocumentKvitanciiCallback();
    String keyID = this.accessCode;
    Collection<Long> correctDocTypes = Lists.newArrayList(0L, 1L);
    String uriDoc;

    if (this.documentTypeId == null || !correctDocTypes.contains(this.documentTypeId)) {
      LOG.error("DocumentTypeId = " + this.documentTypeId);
      throw new DocumentTypeNotSupportedException(
          "Incorrect DocumentTypeId. DocumentTypeId = " + this.documentTypeId);
    } else {
      uriDoc =
          Long.valueOf(0L).equals(this.documentTypeId)
              ? generalConfig.sURL_DocumentKvitanciiForIgov()
              : generalConfig.sURL_DocumentKvitanciiForAccounts();

      keyIdParam = Long.valueOf(0L).equals(this.documentTypeId) ? "?keyID=" : "?id=";
    }

    String finalUri = uriDoc + keyIdParam + keyID + callBackKey + callBackValue;

    // if (generalConfig.bTest()) {
    SSLCertificateValidation.disable();
    // }

    try {
      sessionId = getSessionId();
      String authHeader = "sid:" + sessionId;
      byte[] authHeaderBytes = Base64.encode(authHeader.getBytes(StandardCharsets.UTF_8));
      String authHeaderEncoded = new String(authHeaderBytes);

      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Collections.singletonList(MediaType.ALL));
      headers.set("Authorization", "Basic " + authHeaderEncoded);
      LOG.debug("try to final url: {}", finalUri);
      ResponseEntity<byte[]> documentEntity =
          new RestRequest()
              .getEntity(finalUri, null, StandardCharsets.UTF_8, byte[].class, headers);

      String contentType = documentEntity.getHeaders().getContentType().toString();
      String contentDispositionHeader =
          documentEntity.getHeaders().get("Content-Disposition").get(0);
      ContentDisposition header = new ContentDisposition(contentDispositionHeader);
      String documentName = header.getParameter("name");

      if (isBlank(documentName)) {
        documentName = header.getParameter("filename");
      }

      if (this.withContent) {
        doc.setFileBody(getFileFromRespEntity(documentEntity));
      }

      doc.setDocumentType(documentTypeDao.findByIdExpected(0L));
      doc.setSubject(subjectDao.getSubject(this.nID_Subject));
      doc.setFile(documentName);
      doc.setContentType(contentType);
      doc.setDate_Upload(DateTime.now());
      doc.setsID_subject_Upload(null);
      doc.setContentKey(null);
      doc.setoSignData(null);

    } catch (ParseException | ResourceAccessException e) {
      LOG.error("Can't get document: ", e);
      throw new DocumentNotFoundException("Can't get document: ", e);
    }

    return doc;
  }