Esempio n. 1
0
  /**
   * This method is used to generate byte stream of forms
   *
   * @param pdDoc ProposalDevelopmentDocument
   * @param bookmarksList
   * @return ByteArrayOutputStream[] PDF byte Array
   * @throws S2SException
   */
  protected List<Printable> getPDFStream(ProposalDevelopmentDocument pdDoc) throws S2SException {
    FormMappingInfo info = null;
    S2SBaseFormGenerator s2sFormGenerator = null;
    grantsGovXmlDirectoryFile = null;
    List<AuditError> errors = new ArrayList<AuditError>();
    List<String> sortedNameSpaces =
        getSortedNameSpaces(pdDoc.getDevelopmentProposal().getS2sOppForms());

    List<Printable> formPrintables = new ArrayList<Printable>();
    boolean formEntryFlag = true;
    getS2SUtilService().deleteSystemGeneratedAttachments(pdDoc);
    Forms forms = Forms.Factory.newInstance();
    for (String namespace : sortedNameSpaces) {
      try {
        info = new FormMappingLoader().getFormInfo(namespace);
        s2sFormGenerator =
            (S2SBaseFormGenerator) s2SFormGeneratorService.getS2SGenerator(info.getNameSpace());
      } catch (S2SGeneratorNotFoundException e) {
        LOG.info("Form not found for namespace: " + namespace);
        continue;
      }
      s2sFormGenerator.setAuditErrors(errors);
      s2sFormGenerator.setAttachments(new ArrayList<AttachmentData>());
      XmlObject formObject = s2sFormGenerator.getFormObject(pdDoc);

      if (s2SValidatorService.validate(formObject, errors) && errors.isEmpty()) {
        String applicationXml = formObject.xmlText(s2SFormGeneratorService.getXmlOptionsPrefixes());
        String filteredApplicationXml = getS2SUtilService().removeTimezoneFactor(applicationXml);
        byte[] formXmlBytes = filteredApplicationXml.getBytes();
        S2SFormPrint formPrintable = new S2SFormPrint();
        // Linkedhashmap is used to preserve the order of entry.
        Map<String, byte[]> formXmlDataMap = new LinkedHashMap<String, byte[]>();
        formXmlDataMap.put(info.getFormName(), formXmlBytes);
        formPrintable.setXmlDataMap(formXmlDataMap);

        ArrayList<Source> templates = new ArrayList<Source>();
        Source xsltSource =
            new StreamSource(getClass().getResourceAsStream("/" + info.getStylesheet()));
        templates.add(xsltSource);
        formPrintable.setXSLT(templates);

        List<AttachmentData> attachmentList = s2sFormGenerator.getAttachments();
        try {
          if (pdDoc.getDevelopmentProposal().getGrantsGovSelectFlag()) {
            List<S2sAppAttachments> attachmentLists = new ArrayList<S2sAppAttachments>();
            setFormObject(forms, formObject);
            saveGrantsGovXml(pdDoc, formEntryFlag, forms, attachmentList, attachmentLists);
            formEntryFlag = false;
          }
        } catch (Exception e) {
          LOG.error(e.getMessage(), e);
        }
        Map<String, byte[]> formAttachments = new LinkedHashMap<String, byte[]>();
        if (attachmentList != null && !attachmentList.isEmpty()) {
          for (AttachmentData attachmentData : attachmentList) {
            if (!isPdfType(attachmentData.getContent())) continue;
            StringBuilder attachment = new StringBuilder();
            attachment.append("   ATT : ");
            attachment.append(attachmentData.getContentId());
            formAttachments.put(attachment.toString(), attachmentData.getContent());
          }
        }
        if (formAttachments.size() > 0) {
          formPrintable.setAttachments(formAttachments);
        }
        formPrintables.add(formPrintable);
      }
    }
    if (!errors.isEmpty()) {
      setValidationErrorMessage(errors);
    }
    return formPrintables;
  }
Esempio n. 2
0
  /** updates the XMl with hashcode for the files */
  protected BudgetSubAwards updateXML(
      byte xmlContents[], Map fileMap, BudgetSubAwards budgetSubAwardBean, Budget budget)
      throws Exception {

    javax.xml.parsers.DocumentBuilderFactory domParserFactory =
        javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlContents);

    org.w3c.dom.Document document = domParser.parse(byteArrayInputStream);
    byteArrayInputStream.close();
    String namespace = null;
    String formName = null;
    if (document != null) {
      Node node;
      Element element = document.getDocumentElement();
      NamedNodeMap map = element.getAttributes();
      String namespaceHolder =
          element.getNodeName().substring(0, element.getNodeName().indexOf(':'));
      node = map.getNamedItem("xmlns:" + namespaceHolder);
      namespace = node.getNodeValue();
      FormMappingInfo formMappingInfo = new FormMappingLoader().getFormInfo(namespace);
      formName = formMappingInfo.getFormName();
      budgetSubAwardBean.setNamespace(namespace);
      budgetSubAwardBean.setFormName(formName);
    }

    String xpathEmptyNodes =
        "//*[not(node()) and local-name(.) != 'FileLocation' and local-name(.) != 'HashValue']";
    String xpathOtherPers =
        "//*[local-name(.)='ProjectRole' and local-name(../../.)='OtherPersonnel' and count(../NumberOfPersonnel)=0]";
    removeAllEmptyNodes(document, xpathEmptyNodes, 0);
    removeAllEmptyNodes(document, xpathOtherPers, 1);
    removeAllEmptyNodes(document, xpathEmptyNodes, 0);
    changeDataTypeForNumberOfOtherPersons(document);

    List<String> fedNonFedSubAwardForms = getFedNonFedSubawardForms();
    NodeList budgetYearList =
        XPathAPI.selectNodeList(document, "//*[local-name(.) = 'BudgetYear']");
    for (int i = 0; i < budgetYearList.getLength(); i++) {
      Node bgtYearNode = budgetYearList.item(i);
      String period = getValue(XPathAPI.selectSingleNode(bgtYearNode, "BudgetPeriod"));
      if (fedNonFedSubAwardForms.contains(namespace)) {
        Element newBudgetYearElement =
            copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName());
        bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode);
      } else {
        Element newBudgetYearElement =
            copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName() + period);
        bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode);
      }
    }

    Node oldroot = document.removeChild(document.getDocumentElement());
    Node newroot = document.appendChild(document.createElement("Forms"));
    newroot.appendChild(oldroot);

    org.w3c.dom.NodeList lstFileName = document.getElementsByTagName("att:FileName");
    org.w3c.dom.NodeList lstFileLocation = document.getElementsByTagName("att:FileLocation");
    org.w3c.dom.NodeList lstMimeType = document.getElementsByTagName("att:MimeType");
    org.w3c.dom.NodeList lstHashValue = document.getElementsByTagName("glob:HashValue");

    if ((lstFileName.getLength() != lstFileLocation.getLength())
        || (lstFileLocation.getLength() != lstHashValue.getLength())) {
      //            throw new RuntimeException("Tag occurances mismatch in XML File");
    }

    org.w3c.dom.Node fileNode, hashNode, mimeTypeNode;
    org.w3c.dom.NamedNodeMap fileNodeMap, hashNodeMap;
    String fileName;
    byte fileBytes[];
    String contentId;
    List attachmentList = new ArrayList();

    for (int index = 0; index < lstFileName.getLength(); index++) {
      fileNode = lstFileName.item(index);

      Node fileNameNode = fileNode.getFirstChild();
      fileName = fileNameNode.getNodeValue();

      fileBytes = (byte[]) fileMap.get(fileName);

      if (fileBytes == null) {
        throw new RuntimeException("FileName mismatch in XML and PDF extracted file");
      }
      String hashVal = GrantApplicationHash.computeAttachmentHash(fileBytes);

      hashNode = lstHashValue.item(index);
      hashNodeMap = hashNode.getAttributes();

      Node temp = document.createTextNode(hashVal);
      hashNode.appendChild(temp);

      hashNode = hashNodeMap.getNamedItem("glob:hashAlgorithm");

      hashNode.setNodeValue(S2SConstants.HASH_ALGORITHM);

      fileNode = lstFileLocation.item(index);
      fileNodeMap = fileNode.getAttributes();
      fileNode = fileNodeMap.getNamedItem("att:href");

      contentId = fileNode.getNodeValue();
      String encodedContentId = cleanContentId(contentId);
      fileNode.setNodeValue(encodedContentId);

      mimeTypeNode = lstMimeType.item(0);
      String contentType = mimeTypeNode.getFirstChild().getNodeValue();

      BudgetSubAwardAttachment budgetSubAwardAttachmentBean = new BudgetSubAwardAttachment();
      budgetSubAwardAttachmentBean.setAttachment(fileBytes);
      budgetSubAwardAttachmentBean.setContentId(encodedContentId);

      budgetSubAwardAttachmentBean.setContentType(contentType);
      budgetSubAwardAttachmentBean.setBudgetId(budgetSubAwardBean.getBudgetId());
      budgetSubAwardAttachmentBean.setSubAwardNumber(budgetSubAwardBean.getSubAwardNumber());

      attachmentList.add(budgetSubAwardAttachmentBean);
    }

    budgetSubAwardBean.setBudgetSubAwardAttachments(attachmentList);

    javax.xml.transform.Transformer transformer =
        javax.xml.transform.TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    javax.xml.transform.stream.StreamResult result =
        new javax.xml.transform.stream.StreamResult(bos);
    javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document);

    transformer.transform(source, result);

    budgetSubAwardBean.setSubAwardXmlFileData(new String(bos.toByteArray()));

    bos.close();

    return budgetSubAwardBean;
  }
Esempio n. 3
0
  /**
   * This method is to write the submitted application data to a pdfStream
   *
   * @param pdDoc Proposal Development Document.
   * @return ByteArrayOutputStream[] of the submitted application data.
   * @throws S2SException
   */
  protected List<Printable> getSubmittedPDFStream(ProposalDevelopmentDocument pdDoc)
      throws S2SException {
    GrantApplicationDocument submittedDocument;
    String frmXpath = null;
    String frmAttXpath = null;
    grantsGovXmlDirectoryFile = null;
    try {
      S2sAppSubmission s2sAppSubmission = getLatestS2SAppSubmission(pdDoc);
      String submittedApplicationXml = findSubmittedXml(s2sAppSubmission);
      String submittedApplication =
          getS2SUtilService().removeTimezoneFactor(submittedApplicationXml);
      submittedDocument = GrantApplicationDocument.Factory.parse(submittedApplication);
    } catch (XmlException e) {
      LOG.error(e.getMessage(), e);
      throw new S2SException(e);
    }
    FormMappingInfo info = null;
    S2SFormGenerator s2sFormGenerator = null;
    List<AuditError> errors = new ArrayList<AuditError>();
    List<String> sortedNameSpaces =
        getSortedNameSpaces(pdDoc.getDevelopmentProposal().getS2sOppForms());
    boolean formEntryFlag = true;
    List<Printable> formPrintables = new ArrayList<Printable>();
    for (String namespace : sortedNameSpaces) {
      XmlObject formFragment = null;
      try {
        info = new FormMappingLoader().getFormInfo(namespace);
        formFragment = getFormObject(submittedDocument, info);
        frmXpath = "//*[namespace-uri(.) = '" + namespace + "']";
        frmAttXpath =
            "//*[namespace-uri(.) = '"
                + namespace
                + "']//*[local-name(.) = 'FileLocation' and namespace-uri(.) = 'http://apply.grants.gov/system/Attachments-V1.0']";
      } catch (S2SGeneratorNotFoundException e) {
        // Form generator not available for the namespace
        continue;
      }

      //			XmlObject formObject = s2sFormGenerator.getFormObject(formFragment);
      //			if (s2SValidatorService.validate(formObject, errors)) {
      byte[] formXmlBytes = formFragment.xmlText().getBytes();
      S2SFormPrint formPrintable = new S2SFormPrint();

      ArrayList<Source> templates = new ArrayList<Source>();
      Source xsltSource =
          new StreamSource(getClass().getResourceAsStream("/" + info.getStyleSheet()));
      templates.add(xsltSource);
      formPrintable.setXSLT(templates);

      // Linkedhashmap is used to preserve the order of entry.
      Map<String, byte[]> formXmlDataMap = new LinkedHashMap<String, byte[]>();
      formXmlDataMap.put(info.getFormName(), formXmlBytes);
      formPrintable.setXmlDataMap(formXmlDataMap);
      //				S2sAppSubmission submittedS2SAppSubmission = getLatestS2SAppSubmission(pdDoc);
      S2sApplication s2sApplciation =
          getBusinessObjectService()
              .findBySinglePrimaryKey(
                  S2sApplication.class,
                  pdDoc
                      .getDevelopmentProposal()
                      .getProposalNumber()); // submittedS2SAppSubmission.getS2sApplication();
      List<S2sAppAttachments> attachmentList = s2sApplciation.getS2sAppAttachmentList();

      Map<String, byte[]> formAttachments = new LinkedHashMap<String, byte[]>();

      try {
        XPathExecutor executer = new XPathExecutor(formFragment.toString());
        org.w3c.dom.Node d = executer.getNode(frmXpath);
        org.w3c.dom.NodeList attList = XPathAPI.selectNodeList(d, frmAttXpath);
        int attLen = attList.getLength();

        for (int i = 0; i < attLen; i++) {
          org.w3c.dom.Node attNode = attList.item(i);
          String contentId =
              ((Element) attNode)
                  .getAttributeNS("http://apply.grants.gov/system/Attachments-V1.0", "href");

          if (attachmentList != null && !attachmentList.isEmpty()) {
            for (S2sAppAttachments attAppAttachments : attachmentList) {
              if (attAppAttachments.getContentId().equals(contentId)) {
                ByteArrayOutputStream attStream = new ByteArrayOutputStream();
                try {
                  attStream.write(getAttContent(pdDoc, attAppAttachments.getContentId()));
                } catch (IOException e) {
                  LOG.error(e.getMessage(), e);
                  throw new S2SException(e);
                }
                StringBuilder attachment = new StringBuilder();
                attachment.append("   ATT : ");
                attachment.append(attAppAttachments.getContentId());
                formAttachments.put(
                    attachment.toString(), getAttContent(pdDoc, attAppAttachments.getContentId()));
              }
            }
          }
        }
      } catch (Exception e) {
        LOG.error(e.getMessage(), e);
      }
      try {
        if (pdDoc.getDevelopmentProposal().getGrantsGovSelectFlag()) {
          List<AttachmentData> attachmentLists = new ArrayList<AttachmentData>();
          saveGrantsGovXml(pdDoc, formEntryFlag, formFragment, attachmentLists, attachmentList);
          formEntryFlag = false;
        }
      } catch (Exception e) {
        LOG.error(e.getMessage(), e);
      }
      formPrintable.setAttachments(formAttachments);
      formPrintables.add(formPrintable);
      //			}
    }
    return formPrintables;
  }