/** * Prints the XML bound to <em>empDoc</em>, uses XPath to retrieve elements containing work phone * numbers, changes the numbers to another number, then prints the XML again to display the * changes. * * <p>This method demonstrates the following characteristics of the selectPath method: * * <p>- it supports expressions that include predicates - the XML it returns is the XML queried * against -- not a copy, as with results returned via execQuery methods and XQuery. Changes to * this XML update the XML queried against. - selectPath called from an XMLBean type (instead of a * cursor) returns an array of results (if any). These results can be cast to a matching type * generated from schema. * * @param empDoc The incoming XML. * @return <code>true</code> if the XPath expression returned results; otherwise, <code>false * </code>. */ public boolean updateWorkPhone(XmlObject empDoc) { boolean hasResults = false; // Print the XML received. System.out.println("XML as received by updateWorkPhone method: \n\n" + empDoc.toString()); // Create a variable with the query expression. String pathExpression = "$this/xq:employees/xq:employee/xq:phone[@location='work']"; // Execute the query. XmlObject[] results = empDoc.selectPath(m_namespaceDeclaration + pathExpression); if (results.length > 0) { hasResults = true; // <phone> elements returned from the expression will conform to the // schema, so bind them to the appropriate XMLBeans type generated // from the schema. PhoneType[] phones = (PhoneType[]) results; // Change all the work phone numbers to the same number. for (int i = 0; i < phones.length; i++) { phones[i].setStringValue("(206)555-1234"); } // Print the XML with updates. System.out.println( "\nXML as updated by updateWorkPhone method (each work \n" + "phone number has been changed to the same number): \n\n" + empDoc.toString() + "\n"); } return hasResults; }
@Override public String encode(Resource resource, List<String> includeAttributes) { try { x0.scimSchemasCore1.Resource xmlResource = this.internalEncode(resource, includeAttributes); Complex complex = resource.getClass().getAnnotation(Complex.class); Class<?> factory = ReflectionHelper.getFactory(complex.xmlDoc()); XmlObject doc = (XmlObject) factory.getMethod("newInstance").invoke(null); String name = complex.xmlType().getName(); String setterName = "set"; setterName += name.substring(name.lastIndexOf('.') + 1); doc.getClass().getMethod(setterName, complex.xmlType()).invoke(doc, xmlResource); return (PRETTY_PRINT ? doc.toString() : doc.xmlText()); } catch (FactoryNotFoundException e) { throw new RuntimeException("Internal error, xml encode failed", e); } catch (NoSuchMethodException e) { throw new RuntimeException("Internal error, xml encode failed", e); } catch (SecurityException e) { throw new RuntimeException("Internal error, xml encode failed", e); } catch (IllegalAccessException e) { throw new RuntimeException("Internal error, xml encode failed", e); } catch (IllegalArgumentException e) { throw new RuntimeException("Internal error, xml encode failed", e); } catch (InvocationTargetException e) { throw new RuntimeException("Internal error, xml encode failed", e); } }
private String getCurrentValue(String xpath) { XmlObject[] paths = outlineEditor.getOutlineTable().getXmlObjectTreeModel().getXmlObject().selectPath(xpath); String v = ""; for (XmlObject obj : paths) v += obj.toString(); return v; }
@Override protected void checkMessageStructure() throws MessageValidationException { boolean messageStructureFailure = false; try { // Create a pseudo XML message XmlObject pseudoMessage = XmlObject.Factory.newInstance(); XmlCursor pmCursor = pseudoMessage.newCursor(); pmCursor.toNextToken(); pmCursor.beginElement(profile.getMessageStructureID(), "urn:hl7-org:v2xml"); BufferedReader br = new BufferedReader(new StringReader(message.getMessageAsString())); String line = null; while ((line = br.readLine()) != null) { if (!line.matches("\\s*")) { String fieldSep = ((Er7Message) message).getFieldSeparatorChar(); try { int idx = line.indexOf(fieldSep); if (idx == -1 && line.length() <= 3) { idx = 3; } line = line.substring(0, idx); if (!line.startsWith("Z")) { pmCursor.beginElement(line, "urn:hl7-org:v2xml"); pmCursor.toNextToken(); } } catch (StringIndexOutOfBoundsException e) { if (line.length() > 3) { System.out.println(line); } } } } pmCursor.dispose(); // Create a schema StreamSource xsltStream = new StreamSource( MessageStructureValidationV2Er7.class .getClassLoader() .getResourceAsStream(MessageValidationConstants.XSLT_CHECK_STRUCTURE)); Transformer t = TransformerFactory.newInstance().newTransformer(xsltStream); t.setParameter("groups", "false"); t.setParameter("xml", "false"); StreamSource src = new StreamSource(profile.getDocument().newInputStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); t.transform(src, new StreamResult(out)); XmlObject schemaDoc = XmlObject.Factory.parse( new ByteArrayInputStream(out.toByteArray()), (new XmlOptions()).setLoadLineNumbers()); // pseudoMessage.save(new File("tmp/mu/PseudoMessage.xml")); // schemaDoc.save(new File("tmp/mu/Schema.xsd")); // Load the schema SchemaTypeLoader sLoader = null; Collection<Object> compErrors = new ArrayList<Object>(); XmlOptions schemaOptions = new XmlOptions(); schemaOptions.setErrorListener(compErrors); XmlObject[] schemas = new XmlObject[1]; schemas[0] = schemaDoc; sLoader = XmlBeans.compileXsd(schemas, sLoader, schemaOptions); // Load the Message XmlObject xobj = sLoader.parse(pseudoMessage.toString(), null, (new XmlOptions()).setLoadLineNumbers()); // Validate the Message against the schema Collection<XmlValidationError> errors = new ArrayList<XmlValidationError>(); xobj.validate(new XmlOptions().setErrorListener(errors)); Iterator<XmlValidationError> it = errors.iterator(); while (it.hasNext()) { XmlValidationError xve = it.next(); messageFailures.add(interpretSchemaError(xve)); messageStructureFailure = true; } } catch (XmlException xmle) { // This type of exception is thrown when the generated schema is // ambiguous MessageFailureV2 mf = new MessageFailureV2(message.getEncoding()); mf.setDescription( "The message validation can't be performed because the profile is ambiguous." + " Possible reasons for this problem include an ambiguous message definition" + " specified in the standard or an ambiguous message definition caused by the" + " user changing the Usage settings for segments during profile creation." + " Remember that a segment with the same name MUST be separated by at least one" + " non-optional segment with a different name."); mf.setFailureSeverity(ErrorSeverityConstants.FATAL); mf.setFailureType(AssertionTypeV2Constants.AMBIGUOUS_PROFILE); messageFailures.add(mf); } catch (Exception e) { throw new MessageValidationException(e.getMessage()); } finally { if (!messageStructureFailure) { MessageFailureV2 mf = new MessageFailureV2(message.getEncoding()); mf.setDescription("The message structure at the segment level is correct."); mf.setFailureSeverity(ErrorSeverityConstants.NORMAL); mf.setFailureType(AssertionTypeV2Constants.CHECKED); messageFailures.add(mf); } } }
/** * 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; }