Java Code Examples for org.apache.xmlbeans.XmlCursor#dispose()

The following examples show how to use org.apache.xmlbeans.XmlCursor#dispose() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XML.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 * @return
 */
boolean hasSimpleContent()
{
    boolean simpleContent = false;

    XmlCursor curs = newCursor();

    if (curs.isAttr() || curs.isText()) {
        return true;
    }

    if (curs.isStartdoc())
    {
        curs.toFirstContentToken();
    }

    simpleContent = !(curs.toFirstChild());

    curs.dispose();

    return simpleContent;
}
 
Example 2
Source File: XML.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
static XML createFromXmlObject(XMLLibImpl lib, XmlObject xo)
{
    XScriptAnnotation anno;
    XmlCursor curs = xo.newCursor();
    if (curs.currentTokenType().isStartdoc())
    {
        curs.toFirstContentToken();
    }
    try {
        anno = new XScriptAnnotation(curs);
        curs.setBookmark(anno);
    } finally {
        curs.dispose();
    }
    return new XML(lib, anno);
}
 
Example 3
Source File: XMLLibImpl.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Escapes the reserved characters in a value of an attribute
 *
 * @param value Unescaped text
 * @return The escaped text
 */
public String escapeAttributeValue(Object value)
{
    String text = ScriptRuntime.toString(value);

    if (text.length() == 0) return "";

    XmlObject xo = XmlObject.Factory.newInstance();

    XmlCursor cursor = xo.newCursor();
    cursor.toNextToken();
    cursor.beginElement("a");
    cursor.insertAttributeWithValue("a", text);
    cursor.dispose();

    String elementText = xo.toString();
    int begin = elementText.indexOf('"');
    int end = elementText.lastIndexOf('"');
    return elementText.substring(begin + 1, end);
}
 
Example 4
Source File: EbicsXmlFactory.java    From ebics-java-client with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
  * Qualifies a valid member of a substitution group. This method tries to use the
  * built-in {@link XmlObject#substitute(QName, SchemaType)} and if succesful returns
  * a valid substitution which is usable (not disconnected). If it fails, it uses
  * low-level {@link XmlCursor} manipulation to qualify the substitution group. Note
  * that if the latter is the case the resulting document is disconnected and should
  * no longer be manipulated. Thus, use it as a final step after all markup is included.
  *
  * If newType is null, this method will skip {@link XmlObject#substitute(QName, SchemaType)}
  * and directly use {@link XmlCursor}. This can be used, if you are sure that the substitute
  * is not in the list of (pre-compiled) valid substitutions (this is the case if a schema
  * uses another schema's type as a base for elements. E.g. om:Observation uses gml:_Feature
  * as the base type).
  *
  * @param xobj
  * 		the abstract element
  * @param newInstance
  * 		the new {@link QName} of the instance
  * @param newType the new schemaType. if null, cursors will be used and the resulting object
  * 		will be disconnected.
  * @return if successful applied {@link XmlObject#substitute(QName, SchemaType)} a living object with a
  * 		type == newType is returned. Otherwise null is returned as you can no longer manipulate the object.
  */
 public static XmlObject qualifySubstitutionGroup(XmlObject xobj, QName newInstance, SchemaType newType) {
   XmlObject	substitute = null;

   if (newType != null) {
     substitute = xobj.substitute(newInstance, newType);
     if (substitute != null && substitute.schemaType() == newType
  && substitute.getDomNode().getLocalName().equals(newInstance.getLocalPart()))
     {
return substitute;
     }
   }

   XmlCursor cursor = xobj.newCursor();
   cursor.setName(newInstance);
   QName qName = new QName("http://www.w3.org/2001/XMLSchema-instance", "type");
   cursor.removeAttribute(qName);
   cursor.toNextToken();
   if (cursor.isNamespace()) {
     cursor.removeXml();
   }

   cursor.dispose();

   return null;
 }
 
Example 5
Source File: XML.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 */
void remove ()
{
    XmlCursor childCurs = newCursor();

    if (childCurs.currentTokenType().isStartdoc())
    {
        // Remove on the document removes all children.
        TokenType tt = childCurs.toFirstContentToken();
        while (!tt.isEnd() && !tt.isEnddoc())
        {
            removeToken(childCurs);
            tt = childCurs.currentTokenType();      // Now see where we're pointing after the delete -- next token.
        }
    }
    else
    {
            removeToken(childCurs);
    }

    childCurs.dispose();
}
 
Example 6
Source File: Iso19139GmdEncoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private void encodeCiCitation(CICitationPropertyType cicpt, GmdCitation citation) {
    CICitationType cict = cicpt.addNewCICitation();
    cict.addNewTitle().setCharacterString(citation.getTitle());
    CIDateType cidt = cict.addNewDate().addNewCIDate();
    CodeListValueType clvt = cidt.addNewDateType().addNewCIDateTypeCode();
    GmdCitationDate gmdCitationDate = citation.getDate();
    GmdDateType gmdDateType = gmdCitationDate.getDateType();
    clvt.setCodeList(gmdDateType.getCodeList());
    clvt.setCodeListValue(gmdDateType.getCodeListValue());
    if (gmdDateType.getCodeSpace() != null && !gmdDateType.getCodeSpace().isEmpty()) {
        clvt.setCodeSpace(gmdDateType.getCodeSpace());
    }
    clvt.setStringValue(gmdDateType.getValue());
    XmlCursor newCursor = cidt.addNewDate().newCursor();
    newCursor.toNextToken();
    newCursor.beginElement(QN_GCO_DATE);
    newCursor.insertChars(gmdCitationDate.getDate());
    newCursor.dispose();
}
 
Example 7
Source File: XmlHelper.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
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];
                    if (namespaces.containsKey(prefix)) {
                        cursor.setAttributeText(
                                W3CConstants.QN_XSI_TYPE,
                                Joiner.on(":").join(
                                        XmlHelper.getPrefixForNamespace(content, (String) namespaces.get(prefix)),
                                        localName));
                    }
                }

            }
        }
    }
    cursor.dispose();

}
 
Example 8
Source File: SweCommonEncoderv101.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private XmlObject createTimeGeometricPrimitivePropertyType(TimePeriod timePeriod) throws EncodingException {
    TimeGeometricPrimitivePropertyType xbTimeGeometricPrimitiveProperty =
            TimeGeometricPrimitivePropertyType.Factory.newInstance(getXmlOptions());
    if (timePeriod.isSetStart() && timePeriod.isSetEnd()) {
        xbTimeGeometricPrimitiveProperty.addNewTimeGeometricPrimitive()
                .set(encodeObjectToXml(GmlConstants.NS_GML, timePeriod));
    }
    // TODO check GML 311 rename nodename of geometric primitive to
    // gml:timePeriod
    XmlCursor timeCursor = xbTimeGeometricPrimitiveProperty.newCursor();
    boolean hasTimePrimitive =
            timeCursor.toChild(new QName(GmlConstants.NS_GML, GmlConstants.EN_ABSTRACT_TIME_GEOM_PRIM));
    if (hasTimePrimitive) {
        timeCursor.setName(new QName(GmlConstants.NS_GML, GmlConstants.EN_TIME_PERIOD));
    }
    timeCursor.dispose();
    return xbTimeGeometricPrimitiveProperty;
}
 
Example 9
Source File: NiceXWPFDocument.java    From poi-tl with Apache License 2.0 5 votes vote down vote up
private void mergeNamespaces(NiceXWPFDocument docMerge) {
    CTDocument1 document = this.getDocument();
    XmlCursor newCursor = document.newCursor();
    if (toStartCursor(newCursor)) {
        CTDocument1 documentMerge = docMerge.getDocument();
        XmlCursor mergeCursor = documentMerge.newCursor();
        if (toStartCursor(mergeCursor)) {
            Map<String, String> addToThis = new HashMap<>();
            mergeCursor.getAllNamespaces(addToThis);
            addToThis.forEach(newCursor::insertNamespace);
        }
        mergeCursor.dispose();
    }
    newCursor.dispose();
}
 
Example 10
Source File: EbicsXmlFactory.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Qualifies a valid member of a substitution group. This method tries to use the built-in {@link
 * XmlObject#substitute(QName, SchemaType)} and if succesful returns a valid substitution which is
 * usable (not disconnected). If it fails, it uses low-level {@link XmlCursor} manipulation to
 * qualify the substitution group. Note that if the latter is the case the resulting document is
 * disconnected and should no longer be manipulated. Thus, use it as a final step after all markup
 * is included.
 *
 * <p>If newType is null, this method will skip {@link XmlObject#substitute(QName, SchemaType)}
 * and directly use {@link XmlCursor}. This can be used, if you are sure that the substitute is
 * not in the list of (pre-compiled) valid substitutions (this is the case if a schema uses
 * another schema's type as a base for elements. E.g. om:Observation uses gml:_Feature as the base
 * type).
 *
 * @param xobj the abstract element
 * @param newInstance the new {@link QName} of the instance
 * @param newType the new schemaType. if null, cursors will be used and the resulting object will
 *     be disconnected.
 * @return if successful applied {@link XmlObject#substitute(QName, SchemaType)} a living object
 *     with a type == newType is returned. Otherwise null is returned as you can no longer
 *     manipulate the object.
 */
public static XmlObject qualifySubstitutionGroup(
    XmlObject xobj, QName newInstance, SchemaType newType) {
  XmlObject substitute = null;

  if (newType != null) {
    substitute = xobj.substitute(newInstance, newType);
    if (substitute != null
        && substitute.schemaType() == newType
        && substitute.getDomNode().getLocalName().equals(newInstance.getLocalPart())) {
      return substitute;
    }
  }

  XmlCursor cursor = xobj.newCursor();
  cursor.setName(newInstance);
  QName qName = new QName("http://www.w3.org/2001/XMLSchema-instance", "type");
  cursor.removeAttribute(qName);
  cursor.toNextToken();
  if (cursor.isNamespace()) {
    cursor.removeXml();
  }

  cursor.dispose();

  return null;
}
 
Example 11
Source File: XML.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
XmlObject getXmlObject()
{
    XmlObject xo;
    XmlCursor cursor = newCursor();
    try {
        xo = cursor.getObject();
    } finally {
        cursor.dispose();
    }
    return xo;
}
 
Example 12
Source File: XML.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
static XML createEmptyXML(XMLLibImpl lib)
{
    XScriptAnnotation anno;

    XmlObject xo = XmlObject.Factory.newInstance();
    XmlCursor curs = xo.newCursor();
    try {
        anno = new XScriptAnnotation(curs);
        curs.setBookmark(anno);
    } finally {
        curs.dispose();
    }

    return new XML(lib, anno);
}
 
Example 13
Source File: GetCapabilitiesResponseEncoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
private void renameContentsElementNames(final Contents xbContents) {
    for (final Offering offering : xbContents.getContents().getOfferingArray()) {
        final XmlCursor cursor = offering.getAbstractOffering().newCursor();
        cursor.setName(Sos2Constants.QN_OBSERVATION_OFFERING);
        cursor.removeAttribute(W3CConstants.QN_XSI_TYPE);
        if (cursor.toChild(Sos2Constants.QN_SOS_OBSERVED_AREA)) {
            cursor.setName(Sos2Constants.QN_SOS_OBSERVED_AREA);
            cursor.toParent();
        }
        if (cursor.toChild(Sos2Constants.QN_SOS_PHENOMENON_TIME)) {
            cursor.setName(Sos2Constants.QN_SOS_PHENOMENON_TIME);
            cursor.toParent();
        }
        if (cursor.toChild(Sos2Constants.QN_SOS_RESULT_TIME)) {
            cursor.setName(Sos2Constants.QN_SOS_RESULT_TIME);
            cursor.toParent();
        }
        if (cursor.toChild(Sos2Constants.QN_SOS_RESPONSE_FORMAT)) {
            cursor.setName(Sos2Constants.QN_SOS_RESPONSE_FORMAT);
            while (cursor.toNextSibling(Sos2Constants.QN_SOS_RESPONSE_FORMAT)) {
                cursor.setName(Sos2Constants.QN_SOS_RESPONSE_FORMAT);
            }
            cursor.toParent();
        }
        if (cursor.toChild(Sos2Constants.QN_SOS_OBSERVATION_TYPE)) {
            cursor.setName(Sos2Constants.QN_SOS_OBSERVATION_TYPE);
            while (cursor.toNextSibling(Sos2Constants.QN_SOS_OBSERVATION_TYPE)) {
                cursor.setName(Sos2Constants.QN_SOS_OBSERVATION_TYPE);
            }
            cursor.toParent();
        }
        if (cursor.toChild(Sos2Constants.QN_SOS_FEATURE_OF_INTEREST_TYPE)) {
            cursor.setName(Sos2Constants.QN_SOS_FEATURE_OF_INTEREST_TYPE);
            while (cursor.toNextSibling(Sos2Constants.QN_SOS_FEATURE_OF_INTEREST_TYPE)) {
                cursor.setName(Sos2Constants.QN_SOS_FEATURE_OF_INTEREST_TYPE);
            }
        }
        cursor.dispose();
    }
}
 
Example 14
Source File: XML.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param index
 * @return
 */
XML getXmlChild(long index)
{
    XML result = null;
    XmlCursor curs = newCursor();

    if (moveToChild(curs, index, false, true))
    {
        result = createXML(lib, curs);
    }

    curs.dispose();

    return result;
}
 
Example 15
Source File: XML.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param value
 */
void replaceAll(XML value)
{
    XmlCursor curs = newCursor();

    replace(curs, value);
    _anno = value._anno;

    curs.dispose();
}
 
Example 16
Source File: DhlXTeeServiceImpl.java    From j-road with Apache License 2.0 5 votes vote down vote up
private XRoadAttachment setDokumendidHrefToAttachment(byte[] base64Attachment, XmlObject request) {
    final String cid = AttachmentUtil.getUniqueCid();
    final XRoadAttachment attachment = new XRoadAttachment(cid, "{http://www.w3.org/2001/XMLSchema}base64Binary", base64Attachment);

    XmlCursor cursor = request.newCursor();
    cursor.toNextToken();
    Element node = (Element) cursor.getDomNode();
    node.setAttribute("href", "cid:" + cid);
    cursor.dispose();
    return attachment;
}
 
Example 17
Source File: AbstractSwesXmlStreamWriter.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
protected void writeExtension(SweAbstractDataComponent sweAbstractDataComponent)
        throws EncodingException, XMLStreamException {
    EncodingContext ctx = EncodingContext.of(XmlBeansEncodingFlags.PROPERTY_TYPE, "true");
    XmlObject extension = encodeSwe(ctx, sweAbstractDataComponent);
    if (extension.xmlText().contains(XML_FRAGMENT)) {
        XmlObject set =
                ExtensibleResponseType.Factory.newInstance(getXmlOptions())
                        .addNewExtension().set(extension);
        writeXmlObject(set, SwesStreamingConstants.QN_EXTENSION);
    } else {
        if (checkExtension(extension)) {
            QName name = extension.schemaType().getName();
            String prefix = name.getPrefix();
            if (Strings.isNullOrEmpty(prefix)) {
                XmlCursor newCursor = extension.newCursor();
                prefix = newCursor.prefixForNamespace(name.getNamespaceURI());
                newCursor.setAttributeText(W3CConstants.QN_XSI_TYPE,
                        prefix + ":" + name.getLocalPart());
                newCursor.dispose();
            }
            writeXmlObject(extension, SwesStreamingConstants.QN_EXTENSION);
        } else {
            start(SwesStreamingConstants.QN_EXTENSION);
            writeXmlObject(extension, SwesStreamingConstants.QN_EXTENSION);
            end(SwesStreamingConstants.QN_EXTENSION);
        }
    }
}
 
Example 18
Source File: XML.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 *
 * @return
 */
private XMLList matchDescendantChildren(XMLName xmlName)
{
    XMLList result = new XMLList(lib);
    XmlCursor curs = newCursor();
    TokenType tt = curs.currentTokenType();

    // Set the targets for this XMLList.
    result.setTargets(this, null);

    if (tt.isStartdoc())
    {
        tt = curs.toFirstContentToken();
    }

    if (tt.isContainer())
    {
        int nestLevel = 1;

        while (nestLevel > 0)
        {
            tt = curs.toNextToken();

            if (!tt.isAttr() && !tt.isEnd() && !tt.isEnddoc())
            {
                // Only try to match names for elements or processing instructions.
                if (!tt.isStart() && !tt.isProcinst())
                {
                    // Not an element or procinst, only add if qname is all
                    if (xmlName.localName().equals("*"))
                    {
                        result.addToList(findAnnotation(curs));
                    }
                }
                else
                {
                    if (qnameMatches(xmlName, curs.getName()))
                    {
                        result.addToList(findAnnotation(curs));
                    }
                }
            }

            if (tt.isStart())
            {
                nestLevel++;
            }
            else if (tt.isEnd())
            {
                nestLevel--;
            }
            else if (tt.isEnddoc())
            {
                // Shouldn't get here, but just in case.
                break;
            }
        }
    }

    curs.dispose();

    return result;
}
 
Example 19
Source File: XML.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
     *
     * @param target
     * @return
     */
    boolean equivalentXml(Object target)
    {
        boolean result = false;

        if (target instanceof XML)
        {
            XML otherXml = (XML) target;

            // Compare with toString() if either side is text node or attribute
            // otherwise compare as XML
            XmlCursor.TokenType thisTT = tokenType();
            XmlCursor.TokenType otherTT = otherXml.tokenType();
            if (thisTT == XmlCursor.TokenType.ATTR || otherTT == XmlCursor.TokenType.ATTR ||
                thisTT == XmlCursor.TokenType.TEXT || otherTT == XmlCursor.TokenType.TEXT)
            {
                result = toString().equals(otherXml.toString());
            }
            else
            {
                XmlCursor cursOne = newCursor();
                XmlCursor cursTwo = otherXml.newCursor();

                result = LogicalEquality.nodesEqual(cursOne, cursTwo);

                cursOne.dispose();
                cursTwo.dispose();

// Old way of comparing by string.
//                boolean orgPrettyPrinting = prototype.prettyPrinting;
//                prototype.prettyPrinting = true;
//                result = toXMLString(0).equals(otherXml.toXMLString(0));
//                prototype.prettyPrinting = orgPrettyPrinting;
            }
        }
        else if (target instanceof XMLList)
        {
            XMLList otherList = (XMLList) target;

            if (otherList.length() == 1)
            {
                result = equivalentXml(otherList.getXmlFromAnnotation(0));
            }
        }
        else if (hasSimpleContent())
        {
            String otherStr = ScriptRuntime.toString(target);

            result = toString().equals(otherStr);
        }

        return result;
    }
 
Example 20
Source File: XML.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 *
 * @return
 */
String toXMLString(int indent)
{
    // XXX indent is ignored

    String result;

    XmlCursor curs = newCursor();

    if (curs.isStartdoc())
    {
        curs.toFirstContentToken();
    }

    try
    {
        if (curs.isText())
        {
            result = curs.getChars();
        }
        else if (curs.isAttr())
        {
            result = curs.getTextValue();
        }
        else if (curs.isComment() || curs.isProcinst())
        {
            result = XML.dumpNode(curs, getOptions());

            // todo: XBeans-dependent hack here
            // If it's a comment or PI, take off the xml-frament stuff
            String start = "<xml-fragment>";
            String end = "</xml-fragment>";

            if (result.startsWith(start))
            {
                result = result.substring(start.length());
            }

            if (result.endsWith(end))
            {
                result = result.substring(0, result.length() - end.length());
            }
        }
        else
        {
            result = XML.dumpNode(curs, getOptions());
        }
    }
    finally
    {
        curs.dispose();
    }

    return result;
}