public static Map<?, ?> getNamespaces(XmlObject xmlObject) { XmlCursor cursor = xmlObject.newCursor(); Map<?, ?> nsMap = Maps.newHashMap(); cursor.getAllNamespaces(nsMap); cursor.dispose(); return nsMap; }
private int determineMinMaxForSample(SchemaParticle sp, XmlCursor xmlc) { int minOccurs = sp.getIntMinOccurs(); int maxOccurs = sp.getIntMaxOccurs(); if (minOccurs == maxOccurs) return minOccurs; if (minOccurs == 0 && ignoreOptional) return 0; int result = minOccurs; if (result == 0) result = 1; if (sp.getParticleType() != SchemaParticle.ELEMENT) return result; // it probably only makes sense to put comments in front of individual // elements that repeat if (!_skipComments) { if (sp.getMaxOccurs() == null) { // xmlc.insertComment("The next " + getItemNameOrType(sp, xmlc) + " // may // be repeated " + minOccurs + " or more times"); if (minOccurs == 0) xmlc.insertComment("Zero or more repetitions:"); else xmlc.insertComment(minOccurs + " or more repetitions:"); } else if (sp.getIntMaxOccurs() > 1) { xmlc.insertComment( minOccurs + " to " + String.valueOf(sp.getMaxOccurs()) + " repetitions:"); } else { xmlc.insertComment("Optional:"); } } return result; }
/** * add a new paragraph at position of the cursor * * @param cursor * @return the inserted paragraph */ public XWPFParagraph insertNewParagraph(XmlCursor cursor) { if (isCursorInHdrF(cursor)) { String uri = CTP.type.getName().getNamespaceURI(); String localPart = "p"; cursor.beginElement(localPart, uri); cursor.toParent(); CTP p = (CTP) cursor.getObject(); XWPFParagraph newP = new XWPFParagraph(p, this); XmlObject o = null; while (!(o instanceof CTP) && (cursor.toPrevSibling())) { o = cursor.getObject(); } if ((!(o instanceof CTP)) || (CTP) o == p) { paragraphs.add(0, newP); } else { int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; paragraphs.add(pos, newP); } int i = 0; cursor.toCursor(p.newCursor()); while (cursor.toPrevSibling()) { o = cursor.getObject(); if (o instanceof CTP || o instanceof CTTbl) i++; } bodyElements.add(i, newP); cursor.toCursor(p.newCursor()); cursor.toEndToken(); return newP; } return null; }
public static String getGlobalStateDefinitionsXML(JmxAgentUser jmxAgentUser) { String globalStateDefinitionsXML = null; // SWAgent agent = convertToSwAgent(jmxUser.getSwAgentXML()); // SWAgent swAgent = // TlosSpaceWide.getSpaceWideRegistry().getHeartBeatListenerRef().getSwAgentsCache().get(agent.getIpAddress()+"."+agent.getJmxPort()); SWAgent swAgent = TlosSpaceWide.getSpaceWideRegistry() .getAgentManagerReference() .getSwAgentsCache() .get(jmxAgentUser.getAgentId() + ""); GlobalStateDefinition globalStateDefinition = GlobalStateDefinition.Factory.newInstance(); globalStateDefinition = copyGlobalStateDefinitionsXML( TlosSpaceWide.getSpaceWideRegistry().getGlobalStateDefinition()); for (State state : globalStateDefinition.getGlobalStateArray()) { for (Substate substate : state.getSubstateArray()) { for (Status status : substate.getSubStateStatusesArray()) { for (ReturnCodeList returnCodeList : status.getReturnCodeListArray()) { if (!returnCodeList.getOsType().equals(swAgent.getOsType())) { XmlCursor xmlCursor = returnCodeList.newCursor(); xmlCursor.removeXml(); } } } } } globalStateDefinitionsXML = getGlobalStateDefinitionsXML(globalStateDefinition); return globalStateDefinitionsXML; }
/** * verifies that cursor is on the right position * * @param cursor */ private boolean isCursorInHdrF(XmlCursor cursor) { XmlCursor verify = cursor.newCursor(); verify.toParent(); if (verify.getObject() == this.headerFooter) { return true; } return false; }
/** * Cursor position Before: <theElement>^</theElement> After: <theElement><lots of * stuff/>^</theElement> */ public void createSampleForType(SchemaType stype, XmlCursor xmlc) { _exampleContent = SoapUI.getSettings().getBoolean(WsdlSettings.XML_GENERATION_TYPE_EXAMPLE_VALUE); _typeComment = SoapUI.getSettings().getBoolean(WsdlSettings.XML_GENERATION_TYPE_COMMENT_TYPE); _skipComments = SoapUI.getSettings().getBoolean(WsdlSettings.XML_GENERATION_SKIP_COMMENTS); QName nm = stype.getName(); if (nm == null && stype.getContainerField() != null) nm = stype.getContainerField().getName(); if (nm != null && excludedTypes.contains(nm)) { if (!_skipComments) xmlc.insertComment("Ignoring type [" + nm + "]"); return; } if (_typeStack.contains(stype)) return; _typeStack.add(stype); try { if (stype.isSimpleType() || stype.isURType()) { processSimpleType(stype, xmlc); return; } // complex Type // <theElement>^</theElement> processAttributes(stype, xmlc); // <theElement attri1="string">^</theElement> switch (stype.getContentType()) { case SchemaType.NOT_COMPLEX_TYPE: case SchemaType.EMPTY_CONTENT: // noop break; case SchemaType.SIMPLE_CONTENT: { processSimpleType(stype, xmlc); } break; case SchemaType.MIXED_CONTENT: xmlc.insertChars(pick(WORDS) + " "); if (stype.getContentModel() != null) { processParticle(stype.getContentModel(), xmlc, true); } xmlc.insertChars(pick(WORDS)); break; case SchemaType.ELEMENT_CONTENT: if (stype.getContentModel() != null) { processParticle(stype.getContentModel(), xmlc, false); } break; } } finally { _typeStack.remove(_typeStack.size() - 1); } }
private static final String formatQName(XmlCursor xmlc, QName qName) { XmlCursor parent = xmlc.newCursor(); parent.toParent(); String prefix = parent.prefixForNamespace(qName.getNamespaceURI()); parent.dispose(); String name; if (prefix == null || prefix.length() == 0) name = qName.getLocalPart(); else name = prefix + ":" + qName.getLocalPart(); return name; }
@SuppressWarnings("unused") private void moveToken(int numToMove, XmlCursor xmlc) { for (int i = 0; i < Math.abs(numToMove); i++) { if (numToMove < 0) { xmlc.toPrevToken(); } else { xmlc.toNextToken(); } } }
/** * @param cursor * @return the inserted table */ public XWPFTable insertNewTbl(XmlCursor cursor) { if (isCursorInHdrF(cursor)) { String uri = CTTbl.type.getName().getNamespaceURI(); String localPart = "tbl"; cursor.beginElement(localPart, uri); cursor.toParent(); CTTbl t = (CTTbl) cursor.getObject(); XWPFTable newT = new XWPFTable(t, this); cursor.removeXmlContents(); XmlObject o = null; while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { o = cursor.getObject(); } if (!(o instanceof CTTbl)) { tables.add(0, newT); } else { int pos = tables.indexOf(getTable((CTTbl) o)) + 1; tables.add(pos, newT); } int i = 0; cursor = t.newCursor(); while (cursor.toPrevSibling()) { o = cursor.getObject(); if (o instanceof CTP || o instanceof CTTbl) i++; } bodyElements.add(i, newT); cursor = t.newCursor(); cursor.toEndToken(); return newT; } return null; }
private void processAll(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { SchemaParticle[] spc = sp.getParticleChildren(); if (!_skipComments) xmlc.insertComment( "You may enter the following " + String.valueOf(spc.length) + " items in any order"); for (int i = 0; i < spc.length; i++) { processParticle(spc[i], xmlc, mixed); if (mixed && i < spc.length - 1) xmlc.insertChars(pick(WORDS)); } }
private void processSimpleType(SchemaType stype, XmlCursor xmlc) { if (_soapEnc) { QName typeName = stype.getName(); if (typeName != null) { xmlc.insertAttributeWithValue(XSI_TYPE, formatQName(xmlc, typeName)); } } String sample = sampleDataForSimpleType(stype); xmlc.insertChars(sample); }
/** * Check the subcomponent * * @param subcomponentObj the subcomponent object (from profile) * @param subcomponent the subcomponent string (from ER7) */ private void checkSubComponent(XmlObject subcomponentObj, String subcomponent) { XmlCursor cur = subcomponentObj.newCursor(); /* Check usage */ String usage = cur.getAttributeText(QName.valueOf("Usage")); boolean usageError = checkUsage(subcomponentObj, subcomponent); if (!usageError) { if (usage.equals("R") || !subcomponent.equals("")) { /* Check value */ checkValue(subcomponentObj, subcomponent); } } }
public void setNodeValue(String xpath, Object value) throws XmlException { xpath = initXPathNamespaces(xpath); XmlCursor cursor = xmlObject.newCursor(); try { cursor.selectPath(xpath); if (cursor.toNextSelection()) { XmlUtils.setNodeValue(cursor.getDomNode(), value == null ? null : value.toString()); } } finally { cursor.dispose(); } }
protected void addSchemaLocations(XmlObject xmlObject, Map<String, String> locations) { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : locations.entrySet()) { if (sb.length() > 0) { sb.append(" "); } sb.append(entry.getKey() + " " + entry.getValue()); } XmlCursor cursor = xmlObject.newCursor(); if (cursor.toFirstChild()) { cursor.setAttributeText( new QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation"), sb.toString()); } }
public QName getContentsQName(EDXLDistribution edxl) { QName qname = null; XmlCursor c = edxl.getContentObjectArray(0).getXmlContent().getEmbeddedXMLContentArray(0).newCursor(); try { if (c.toFirstChild()) { qname = c.getObject().schemaType().getOuterType().getDocumentElementName(); } } catch (Exception e) { log.error("Error finding EDXL-DE content type: " + e.getMessage()); log.error("From EDXL-DE: " + edxl.toString()); } finally { c.dispose(); } return qname; }
/** * Validate an XmlObject against the contained inferred schemas. Upon validation errors, the * ConflictHandler is used to determine if a schema should be adjusted, or if validation should * fail. * * @param xmlo An XmlObject containing the document to be validated. * @param handler A ConflictHandler to use on validation errors. * @throws XmlException On unresolvable validation error. */ public void validate(XmlObject xmlo, ConflictHandler handler) throws XmlException { XmlCursor cursor = xmlo.newCursor(); cursor.toFirstChild(); Schema s = getSchemaForNamespace(cursor.getName().getNamespaceURI()); boolean created = false; if (s == null) { s = newSchema(cursor.getName().getNamespaceURI()); created = true; } Context context = new Context(this, handler, cursor); try { s.validate(context); } catch (XmlException e) { if (created) schemas.remove(s.getNamespace()); throw e; } }
private void processSequence(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { SchemaParticle[] spc = sp.getParticleChildren(); for (int i = 0; i < spc.length; i++) { // / <parent>maybestuff^</parent> processParticle(spc[i], xmlc, mixed); // <parent>maybestuff...morestuff^</parent> if (mixed && i < spc.length - 1) xmlc.insertChars(pick(WORDS)); } }
private void processAttributes(SchemaType stype, XmlCursor xmlc) { if (_soapEnc) { QName typeName = stype.getName(); if (typeName != null) { xmlc.insertAttributeWithValue(XSI_TYPE, formatQName(xmlc, typeName)); } } SchemaProperty[] attrProps = stype.getAttributeProperties(); for (int i = 0; i < attrProps.length; i++) { SchemaProperty attr = attrProps[i]; if (attr.getMinOccurs().intValue() == 0 && ignoreOptional) continue; if (attr.getName().equals(new QName("http://www.w3.org/2005/05/xmlmime", "contentType"))) { xmlc.insertAttributeWithValue(attr.getName(), "application/?"); continue; } if (_soapEnc) { if (SKIPPED_SOAP_ATTRS.contains(attr.getName())) continue; if (ENC_ARRAYTYPE.equals(attr.getName())) { SOAPArrayType arrayType = ((SchemaWSDLArrayType) stype.getAttributeModel().getAttribute(attr.getName())) .getWSDLArrayType(); if (arrayType != null) xmlc.insertAttributeWithValue( attr.getName(), formatQName(xmlc, arrayType.getQName()) + arrayType.soap11DimensionString()); continue; } } String value = null; if (multiValues != null) { String[] values = multiValues.get(attr.getName()); if (values != null) value = StringUtils.join(values, ","); } if (value == null) value = attr.getDefaultText(); if (value == null) value = sampleDataForSimpleType(attr.getType()); xmlc.insertAttributeWithValue(attr.getName(), value); } }
private void processChoice(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { SchemaParticle[] spc = sp.getParticleChildren(); if (!_skipComments) xmlc.insertComment( "You have a CHOICE of the next " + String.valueOf(spc.length) + " items at this level"); for (int i = 0; i < spc.length; i++) { processParticle(spc[i], xmlc, mixed); } }
public static String createSampleForElement(SchemaGlobalElement element) { XmlObject xml = XmlObject.Factory.newInstance(); XmlCursor c = xml.newCursor(); c.toNextToken(); c.beginElement(element.getName()); new SampleXmlUtil(false).createSampleForType(element.getType(), c); c.dispose(); XmlOptions options = new XmlOptions(); options.put(XmlOptions.SAVE_PRETTY_PRINT); options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 3); options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES); options.setSaveOuter(); String result = xml.xmlText(options); return result; }
private void processElement(SchemaParticle sp, XmlCursor xmlc, boolean mixed) { // cast as schema local element SchemaLocalElement element = (SchemaLocalElement) sp; // Add comment about type addElementTypeAndRestricionsComment(element, xmlc); // / ^ -> <elemenname></elem>^ if (_soapEnc) xmlc.insertElement(element.getName().getLocalPart()); // soap // encoded? // drop // namespaces. else xmlc.insertElement(element.getName().getLocalPart(), element.getName().getNamespaceURI()); // / -> <elem>^</elem> // processAttributes( sp.getType(), xmlc ); xmlc.toPrevToken(); // -> <elem>stuff^</elem> String[] values = null; if (multiValues != null) values = multiValues.get(element.getName()); if (values != null) xmlc.insertChars(StringUtils.join(values, ",")); else if (sp.isDefault()) xmlc.insertChars(sp.getDefaultText()); else createSampleForType(element.getType(), xmlc); // -> <elem>stuff</elem>^ xmlc.toNextToken(); }
public static void fixNamespaceForXsiType(XmlObject content, Map<?, ?> namespaces) { final XmlCursor cursor = content.newCursor(); while (cursor.hasNextToken()) { if (cursor.toNextToken().isStart()) { final String xsiType = cursor.getAttributeText(W3CConstants.QN_XSI_TYPE); if (xsiType != null) { final String[] toks = xsiType.split(":"); if (toks.length > 1) { String prefix = toks[0]; String localName = toks[1]; String namespace = (String) namespaces.get(prefix); if (Strings.isNullOrEmpty(namespace)) { namespace = CodingRepository.getInstance().getNamespaceFor(prefix); } if (StringHelper.isNotEmpty(namespace)) { cursor.setAttributeText( W3CConstants.QN_XSI_TYPE, Joiner.on(Constants.COLON_CHAR) .join( XmlHelper.getPrefixForNamespace(content, (String) namespaces.get(prefix)), localName)); } } } } } cursor.dispose(); }
public static void fixNamespaceForXsiType(final XmlObject object, final QName value) { final XmlCursor cursor = object.newCursor(); while (cursor.hasNextToken()) { if (cursor.toNextToken().isStart()) { final String xsiType = cursor.getAttributeText(W3CConstants.QN_XSI_TYPE); if (xsiType != null) { final String[] toks = xsiType.split(":"); String localName; String prefix; if (toks.length > 1) { prefix = toks[0]; localName = toks[1]; } else { localName = toks[0]; } if (localName.equals(value.getLocalPart())) { cursor.setAttributeText( W3CConstants.QN_XSI_TYPE, Joiner.on(Constants.COLON_CHAR) .join( XmlHelper.getPrefixForNamespace(object, value.getNamespaceURI()), value.getLocalPart())); } } } } cursor.dispose(); }
/** * get the TableCell which belongs to the TableCell * * @param cell */ public XWPFTableCell getTableCell(CTTc cell) { XmlCursor cursor = cell.newCursor(); cursor.toParent(); XmlObject o = cursor.getObject(); if (!(o instanceof CTRow)) { return null; } CTRow row = (CTRow) o; cursor.toParent(); o = cursor.getObject(); cursor.dispose(); if (!(o instanceof CTTbl)) { return null; } CTTbl tbl = (CTTbl) o; XWPFTable table = getTable(tbl); if (table == null) { return null; } XWPFTableRow tableRow = table.getRow(row); if (row == null) { return null; } return tableRow.getTableCell(cell); }
/** * Utility method to append the contents of the child docment to the end of the parent XmlObject. * This is useful when dealing with elements without generated methods (like elements with xs:any) * * @param parent Parent to append contents to * @param childDoc Xml document containing contents to be appended */ public static void append(final XmlObject parent, final XmlObject childDoc) { final XmlCursor parentCursor = parent.newCursor(); parentCursor.toEndToken(); final XmlCursor childCursor = childDoc.newCursor(); childCursor.toFirstChild(); childCursor.moveXml(parentCursor); parentCursor.dispose(); childCursor.dispose(); }
private void addElementTypeAndRestricionsComment(SchemaLocalElement element, XmlCursor xmlc) { SchemaType type = element.getType(); if (_typeComment && (type != null && type.isSimpleType())) { String info = ""; XmlAnySimpleType[] values = type.getEnumerationValues(); if (values != null && values.length > 0) { info = " - enumeration: ["; for (int c = 0; c < values.length; c++) { if (c > 0) info += ","; info += values[c].getStringValue(); } info += "]"; } if (type.isAnonymousType()) xmlc.insertComment("anonymous type" + info); else xmlc.insertComment("type: " + type.getName().getLocalPart() + info); } }
@Test public void shouldCreateValidNotification() throws XmlException, IOException, OXFException { String sesUrl = "http://ses.host"; String dialect = "http://my-funny/dialect"; ParameterContainer parameters = new ParameterContainer(); parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_SES_URL, sesUrl); parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_TOPIC_DIALECT, dialect); parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_TOPIC, "<start>topic</start>"); parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_XML_MESSAGE, readMessage()); SESRequestBuilder_00 request = new SESRequestBuilder_00(); String asText = request.buildNotifyRequest(parameters); EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(asText); XMLBeansParser.registerLaxValidationCase(SASamplingPointCase.getInstance()); Collection<XmlError> errors = XMLBeansParser.validate(envelope); Assert.assertTrue("Notification is not valid: " + errors, errors.isEmpty()); XmlCursor bodyCur = envelope.getEnvelope().getBody().newCursor(); bodyCur.toFirstChild(); Assert.assertTrue(bodyCur.getObject() instanceof Notify); XmlCursor tmpCur = ((Notify) bodyCur.getObject()).getNotificationMessageArray()[0].getMessage().newCursor(); tmpCur.toFirstChild(); Assert.assertTrue(tmpCur.getObject() instanceof ObservationType); Assert.assertTrue( ((Notify) bodyCur.getObject()) .getNotificationMessageArray()[0] .getTopic() .getDialect() .trim() .equals(dialect)); tmpCur = ((Notify) bodyCur.getObject()).getNotificationMessageArray()[0].getTopic().newCursor(); Assert.assertTrue(tmpCur.getObject().xmlText().contains("<start>")); }
public static String createSampleForType(SchemaType sType) { XmlObject object = XmlObject.Factory.newInstance(); XmlCursor cursor = object.newCursor(); // Skip the document node cursor.toNextToken(); // Using the type and the cursor, call the utility method to get a // sample XML payload for that Schema element new SampleXmlUtil(false).createSampleForType(sType, cursor); // Cursor now contains the sample payload // Pretty print the result. Note that the cursor is positioned at the // end of the doc so we use the original xml object that the cursor was // created upon to do the xmlText() against. cursor.dispose(); XmlOptions options = new XmlOptions(); options.put(XmlOptions.SAVE_PRETTY_PRINT); options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 3); options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES); options.setSaveOuter(); String result = object.xmlText(options); return result; }
public void readHdrFtr() { bodyElements = new ArrayList<IBodyElement>(); paragraphs = new ArrayList<XWPFParagraph>(); tables = new ArrayList<XWPFTable>(); // parse the document with cursor and add // the XmlObject to its lists XmlCursor cursor = headerFooter.newCursor(); cursor.selectPath("./*"); while (cursor.toNextSelection()) { XmlObject o = cursor.getObject(); if (o instanceof CTP) { XWPFParagraph p = new XWPFParagraph((CTP) o, this); paragraphs.add(p); bodyElements.add(p); } if (o instanceof CTTbl) { XWPFTable t = new XWPFTable((CTTbl) o, this); tables.add(t); bodyElements.add(t); } } cursor.dispose(); getAllPictures(); }
/** * Remove namespace declarations from an xml fragment (useful for moving all declarations to a * document root * * @param x The fragment to localize */ public static void removeNamespaces(final XmlObject x) { final XmlCursor c = x.newCursor(); while (c.hasNextToken()) { if (c.isNamespace()) { c.removeXml(); } else { c.toNextToken(); } } c.dispose(); }