public ModelAndView save(
      @ModelAttribute("KualiForm") DocumentFormBase form,
      BindingResult result,
      HttpServletRequest request,
      HttpServletResponse response,
      Class<? extends DocumentEventBase> eventClazz)
      throws Exception {
    ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) form;
    ProposalDevelopmentDocument proposalDevelopmentDocument =
        (ProposalDevelopmentDocument) pdForm.getDocument();
    proposalDevelopmentService.initializeUnitOrganizationLocation(proposalDevelopmentDocument);
    proposalDevelopmentService.initializeProposalSiteNumbers(proposalDevelopmentDocument);

    saveAnswerHeaders(pdForm, request.getParameter(UifParameters.PAGE_ID));

    if (eventClazz == null) {
      getTransactionalDocumentControllerService().save(form);
    } else {
      performCustomSave(proposalDevelopmentDocument, SaveDocumentSpecialReviewEvent.class);
    }

    populateAdHocRecipients(pdForm.getProposalDevelopmentDocument());

    String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
    final ModelAndView view;
    if (StringUtils.isNotBlank(pageId)
        && getGlobalVariableService().getMessageMap().hasNoErrors()) {
      form.setDirtyForm(false);
      view = getModelAndViewService().getModelAndView(form, pageId);
    } else {
      view = getModelAndViewService().getModelAndView(form);
    }

    if (pdForm.getProposalDevelopmentDocument().getDevelopmentProposal() != null
        && pdForm.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews()
            != null) {
      pdForm
          .getProposalDevelopmentDocument()
          .getDevelopmentProposal()
          .getPropSpecialReviews()
          .stream()
          .filter(specialReview -> !specialReview.isLinkedToProtocol())
          .forEach(
              specialReview ->
                  pdForm.getSpecialReviewHelper().prepareProtocolLinkViewFields(specialReview));
    }
    getProjectPublisher()
        .publishProject(
            getPropDevProjectRetrievalService()
                .retrieveProject(
                    pdForm
                        .getProposalDevelopmentDocument()
                        .getDevelopmentProposal()
                        .getProposalNumber()));

    return view;
  }
 protected ModelAndView navigate(
     ProposalDevelopmentDocumentForm form,
     BindingResult result,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   if (form.getDevelopmentProposal().getS2sOpportunity() != null
       && !getProposalDevelopmentService()
           .isGrantsGovEnabledForProposal(form.getDevelopmentProposal())) {
     ((ProposalDevelopmentViewHelperServiceImpl) form.getViewHelperService())
         .clearOpportunity(form.getDevelopmentProposal());
   }
   populateAdHocRecipients(form.getProposalDevelopmentDocument());
   String navigateToPageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
   if (isNavigateToDeliveryInfoPage(navigateToPageId)) {
     if (form.getDevelopmentProposal().getS2sOpportunity() != null) {
       getGlobalVariableService()
           .getMessageMap()
           .putInfo(
               ProposalDevelopmentConstants.KradConstants.DELIVERY_INFO_PAGE,
               KeyConstants.DELIVERY_INFO_NOT_NEEDED);
     }
   }
   if (form.isCanEditView()) {
     return save(form);
   } else {
     return getNavigationControllerService().navigate(form);
   }
 }
 public void saveAnswerHeaders(ProposalDevelopmentDocumentForm pdForm, String pageId) {
   if (StringUtils.equalsIgnoreCase(pageId, Constants.KEY_PERSONNEL_PAGE)
       || StringUtils.equalsIgnoreCase(pageId, Constants.CERTIFICATION_PAGE)) {
     saveUpdatePersonAnswerHeaders(
         pdForm.getProposalDevelopmentDocument().getDevelopmentProposal(), pageId);
   } else if (StringUtils.equalsIgnoreCase(pageId, Constants.QUESTIONS_PAGE)) {
     saveUpdateQuestionnaireAnswerHeaders(pdForm.getQuestionnaireHelper(), pageId);
     saveUpdateQuestionnaireAnswerHeaders(pdForm.getS2sQuestionnaireHelper(), pageId);
   }
 }
 /**
  * Method calls the permissions service, where it will determine if any user permissions need to
  * be added and/or removed.
  *
  * @param pdForm ProposalDevelopmentDocumentForm that contains the permissions helper
  */
 public void saveDocumentPermissions(ProposalDevelopmentDocumentForm pdForm) {
   List<String> editableLines =
       pdForm
           .getEditableCollectionLines()
           .get(Constants.PERMISSION_PROPOSAL_USERS_COLLECTION_PROPERTY_KEY);
   if (editableLines != null && editableLines.size() > 0) {
     getGlobalVariableService()
         .getMessageMap()
         .putErrorForSectionId(
             Constants.PERMISSION_PROPOSAL_USERS_COLLECTION_ID_KEY,
             KeyConstants.ERROR_UNFINISHED_PERMISSIONS);
   } else if (arePermissionsValid(
       pdForm.getProposalDevelopmentDocument(), pdForm.getWorkingUserRoles())) {
     getProposalDevelopmentPermissionsService()
         .savePermissions(
             pdForm.getProposalDevelopmentDocument(),
             getProposalDevelopmentPermissionsService()
                 .getPermissions(pdForm.getProposalDevelopmentDocument()),
             pdForm.getWorkingUserRoles());
   }
 }
 @Transactional
 @RequestMapping(
     value = "/proposalDevelopment",
     params = {"methodToCall=refreshSubmissionDetails"})
 public ModelAndView refreshSubmissionDetails(ProposalDevelopmentDocumentForm form)
     throws Exception {
   ProposalDevelopmentDocument document = form.getProposalDevelopmentDocument();
   try {
     getS2sSubmissionService().refreshGrantsGov(document);
   } catch (S2sCommunicationException ex) {
     LOG.error(ex.getMessage(), ex);
     getGlobalVariableService()
         .getMessageMap()
         .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessage());
   }
   return getRefreshControllerService().refresh(form);
 }
 @Transactional
 @RequestMapping(
     value = "/proposalDevelopment",
     params = {"methodToCall=deleteUserAttachedForm"})
 public ModelAndView deleteUserAttachedForm(
     ProposalDevelopmentDocumentForm form,
     HttpServletResponse response,
     @RequestParam("selectedLine") String selectedLine)
     throws Exception {
   S2sUserAttachedForm deleteForm =
       form.getDevelopmentProposal()
           .getS2sUserAttachedForms()
           .remove(Integer.parseInt(selectedLine));
   getDataObjectService().delete(deleteForm);
   getS2sUserAttachedFormService()
       .resetFormAvailability(form.getProposalDevelopmentDocument(), deleteForm.getNamespace());
   return getModelAndViewService().getModelAndView(form);
 }
  @Transactional
  @RequestMapping(
      value = "/proposalDevelopment",
      params = {"methodToCall=addUserAttachedForm"})
  public ModelAndView addUserAttachedForm(
      @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form) throws Exception {
    S2sUserAttachedForm s2sUserAttachedForm = form.getS2sUserAttachedForm();
    ProposalDevelopmentDocument proposalDevelopmentDocument = form.getProposalDevelopmentDocument();

    MultipartFile userAttachedFormFile = s2sUserAttachedForm.getNewFormFile();

    s2sUserAttachedForm.setNewFormFileBytes(userAttachedFormFile.getBytes());
    s2sUserAttachedForm.setFormFileName(userAttachedFormFile.getOriginalFilename());
    s2sUserAttachedForm.setProposalNumber(
        proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber());
    try {
      List<S2sUserAttachedForm> userAttachedForms =
          getS2sUserAttachedFormService()
              .extractNSaveUserAttachedForms(proposalDevelopmentDocument, s2sUserAttachedForm);
      proposalDevelopmentDocument
          .getDevelopmentProposal()
          .getS2sUserAttachedForms()
          .addAll(userAttachedForms);
      form.setS2sUserAttachedForm(new S2sUserAttachedForm());
    } catch (S2SException ex) {
      LOG.error(ex.getMessage(), ex);
      if (ex.getTabErrorKey() != null) {
        if (getGlobalVariableService()
                .getMessageMap()
                .getErrorMessagesForProperty(ex.getTabErrorKey())
            == null) {
          getGlobalVariableService()
              .getMessageMap()
              .putError(ex.getTabErrorKey(), ex.getErrorKey(), ex.getParams());
        }
      } else {
        getGlobalVariableService()
            .getMessageMap()
            .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessageWithParams());
      }
    }

    return super.save(form);
  }
  public ModelAndView save(ProposalDevelopmentDocumentForm form) throws Exception {
    ProposalDevelopmentDocument proposalDevelopmentDocument =
        (ProposalDevelopmentDocument) form.getDocument();

    if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.PROP_DEV_PERMISSIONS_PAGE)) {
      saveDocumentPermissions(form);
    }

    if (StringUtils.equalsIgnoreCase(
        form.getPageId(), ProposalDevelopmentDataValidationConstants.ATTACHMENT_PAGE_ID)) {
      ((ProposalDevelopmentViewHelperServiceImpl) form.getViewHelperService())
          .populateAttachmentReferences(form.getDevelopmentProposal());
    }

    if (getGlobalVariableService().getMessageMap().getErrorCount() == 0
        && form.getEditableCollectionLines() != null) {
      form.getEditableCollectionLines().clear();
    }
    if (StringUtils.equalsIgnoreCase(
        form.getPageId(), ProposalDevelopmentDataValidationConstants.DETAILS_PAGE_ID)) {
      handleSponsorChange(proposalDevelopmentDocument);
    }

    preSave(proposalDevelopmentDocument);

    proposalDevelopmentService.initializeUnitOrganizationLocation(proposalDevelopmentDocument);
    proposalDevelopmentService.initializeProposalSiteNumbers(proposalDevelopmentDocument);

    for (ProposalPersonBiography biography : form.getDevelopmentProposal().getPropPersonBios()) {
      getProposalPersonBiographyService()
          .prepareProposalPersonBiographyForSave(form.getDevelopmentProposal(), biography);
    }

    ((ProposalDevelopmentViewHelperServiceImpl) form.getViewHelperService())
        .setOrdinalPosition(form.getDevelopmentProposal().getProposalPersons());
    saveAnswerHeaders(form, form.getPageId());

    getTransactionalDocumentControllerService().save(form);
    if (form.isAuditActivated()) {
      getAuditHelper().auditConditionally(form);
    }

    populateAdHocRecipients(form.getProposalDevelopmentDocument());

    if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.CREDIT_ALLOCATION_PAGE)) {
      ((ProposalDevelopmentViewHelperServiceImpl) form.getViewHelperService())
          .populateCreditSplits(form);
    }

    if (StringUtils.equalsIgnoreCase(form.getPageId(), Constants.QUESTIONS_PAGE)) {
      ((ProposalDevelopmentViewHelperServiceImpl) form.getViewHelperService())
          .populateQuestionnaires(form);
    }
    String pageId = form.getActionParamaterValue(UifParameters.NAVIGATE_TO_PAGE_ID);
    final ModelAndView view;
    if (StringUtils.isNotBlank(pageId)
        && getGlobalVariableService().getMessageMap().hasNoErrors()) {
      form.setDirtyForm(false);
      view = getModelAndViewService().getModelAndView(form, pageId);
    } else {
      view = getModelAndViewService().getModelAndView(form);
    }

    if (form.getProposalDevelopmentDocument().getDevelopmentProposal() != null
        && form.getProposalDevelopmentDocument().getDevelopmentProposal().getPropSpecialReviews()
            != null) {
      form.getProposalDevelopmentDocument()
          .getDevelopmentProposal()
          .getPropSpecialReviews()
          .stream()
          .filter(specialReview -> !specialReview.isLinkedToProtocol())
          .forEach(
              specialReview ->
                  form.getSpecialReviewHelper().prepareProtocolLinkViewFields(specialReview));
    }
    getProjectPublisher()
        .publishProject(
            getPropDevProjectRetrievalService()
                .retrieveProject(
                    form.getProposalDevelopmentDocument()
                        .getDevelopmentProposal()
                        .getProposalNumber()));

    return view;
  }
  @Transactional
  @RequestMapping(
      value = "/proposalDevelopment",
      params = {"methodToCall=printForms"})
  public ModelAndView printForms(
      @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form,
      HttpServletResponse response)
      throws Exception {
    ProposalDevelopmentDocument proposalDevelopmentDocument = form.getProposalDevelopmentDocument();

    proposalDevelopmentDocumentViewAuthorizer.initializeDocumentAuthorizerIfNecessary(
        form.getProposalDevelopmentDocument());

    if (!((ProposalDevelopmentDocumentAuthorizer)
            proposalDevelopmentDocumentViewAuthorizer.getDocumentAuthorizer())
        .isAuthorizedToPrint(
            proposalDevelopmentDocument, globalVariableService.getUserSession().getPerson())) {
      throw new AuthorizationException(
          globalVariableService.getUserSession().getPrincipalName(), "printForms", "Proposal");
    }

    if (proposalDevelopmentDocument.getDevelopmentProposal().getSelectedS2sOppForms().isEmpty()) {
      getGlobalVariableService()
          .getMessageMap()
          .putError("noKey", ERROR_NO_GRANTS_GOV_FORM_SELECTED);
      return getModelAndViewService().getModelAndView(form);
    }
    FormPrintResult formPrintResult = getFormPrintService().printForm(proposalDevelopmentDocument);

    setValidationErrorMessage(formPrintResult.getErrors());
    KcFile attachmentDataSource = formPrintResult.getFile();
    if (((attachmentDataSource == null
                || attachmentDataSource.getData() == null
                || attachmentDataSource.getData().length == 0)
            && !proposalDevelopmentDocument.getDevelopmentProposal().getGrantsGovSelectFlag())
        || CollectionUtils.isNotEmpty(formPrintResult.getErrors())) {
      boolean grantsGovErrorExists =
          copyAuditErrorsToPage(Constants.GRANTSGOV_ERRORS, "grantsGovFormValidationErrors");
      if (grantsGovErrorExists) {
        getGlobalVariableService()
            .getMessageMap()
            .putError(
                "grantsGovFormValidationErrors",
                KeyConstants.VALIDATTION_ERRORS_BEFORE_GRANTS_GOV_SUBMISSION);
      }
      proposalDevelopmentDocument.getDevelopmentProposal().setGrantsGovSelectFlag(false);
      return getModelAndViewService().getModelAndView(form);
    }
    if (proposalDevelopmentDocument.getDevelopmentProposal().getGrantsGovSelectFlag()) {
      File grantsGovXmlDirectoryFile =
          getS2sSubmissionService().getGrantsGovSavedFile(proposalDevelopmentDocument);
      byte[] bytes = new byte[(int) grantsGovXmlDirectoryFile.length()];
      FileInputStream fileInputStream = new FileInputStream(grantsGovXmlDirectoryFile);
      fileInputStream.read(bytes);
      int size = bytes.length;
      try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(size)) {
        outputStream.write(bytes);
        ControllerFileUtils.streamOutputToResponse(
            response,
            outputStream,
            "binary/octet-stream",
            grantsGovXmlDirectoryFile.getName(),
            size);
        response.flushBuffer();
      }
      proposalDevelopmentDocument.getDevelopmentProposal().setGrantsGovSelectFlag(false);
      return getModelAndViewService().getModelAndView(form);
    }

    ControllerFileUtils.streamToResponse(attachmentDataSource, response);
    return getModelAndViewService().getModelAndView(form);
  }
  @Transactional
  @RequestMapping(
      value = "/proposalDevelopment",
      params = {"methodToCall=refresh", "refreshCaller=S2sOpportunity-LookupView"})
  public ModelAndView refresh(
      @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form,
      BindingResult result,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    ProposalDevelopmentDocument document = form.getProposalDevelopmentDocument();
    DevelopmentProposal proposal = document.getDevelopmentProposal();
    if (form.getNewS2sOpportunity() != null
        && StringUtils.isNotEmpty(form.getNewS2sOpportunity().getOpportunityId())) {

      proposal.setS2sOpportunity(form.getNewS2sOpportunity());
      proposal.getS2sOpportunity().setDevelopmentProposal(proposal);

      // Set default S2S Submission Type
      if (StringUtils.isBlank(form.getNewS2sOpportunity().getS2sSubmissionTypeCode())) {
        String defaultS2sSubmissionTypeCode =
            getProposalTypeService().getDefaultSubmissionTypeCode(proposal.getProposalTypeCode());
        proposal.getS2sOpportunity().setS2sSubmissionTypeCode(defaultS2sSubmissionTypeCode);
        getDataObjectService()
            .wrap(proposal.getS2sOpportunity())
            .fetchRelationship("s2sSubmissionType");
      }

      final String opportunityTitle = form.getNewS2sOpportunity().getOpportunityTitle();
      String trimmedTitle =
          StringUtils.substring(
              opportunityTitle, 0, ProposalDevelopmentConstants.S2sConstants.OPP_TITLE_MAX_LENGTH);
      // Set Opportunity Title and Opportunity ID in the Sponsor & Program Information section
      proposal.setProgramAnnouncementTitle(trimmedTitle);
      proposal.setCfdaNumber(form.getNewS2sOpportunity().getCfdaNumber());
      proposal.setProgramAnnouncementNumber(form.getNewS2sOpportunity().getOpportunityId());
      form.setNewS2sOpportunity(new S2sOpportunity());
    }

    S2sOpportunity s2sOpportunity = proposal.getS2sOpportunity();

    try {
      if (s2sOpportunity != null && s2sOpportunity.getSchemaUrl() != null) {
        List<String> missingMandatoryForms =
            s2sSubmissionService.setMandatoryForms(proposal, s2sOpportunity);

        if (!CollectionUtils.isEmpty(missingMandatoryForms)) {
          globalVariableService
              .getMessageMap()
              .putError(
                  Constants.NO_FIELD,
                  KeyConstants.ERROR_IF_OPPORTUNITY_ID_IS_INVALID,
                  s2sOpportunity.getOpportunityId(),
                  StringUtils.join(missingMandatoryForms, ","));
          proposal.setS2sOpportunity(null);
        }
      }
    } catch (S2sCommunicationException ex) {
      if (ex.getErrorKey().equals(KeyConstants.ERROR_GRANTSGOV_NO_FORM_ELEMENT)) {
        ex.setMessage(s2sOpportunity.getOpportunityId());
      }
      globalVariableService
          .getMessageMap()
          .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessageWithParams());
      proposal.setS2sOpportunity(new S2sOpportunity());
    }
    super.save(form, result, request, response);
    return getRefreshControllerService().refresh(form);
  }