Example usage for org.w3c.dom Element getAttributeNS

List of usage examples for org.w3c.dom Element getAttributeNS

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttributeNS.

Prototype

public String getAttributeNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Retrieves an attribute value by local name and namespace URI.

Usage

From source file:org.chiba.xml.xforms.test.ChibaBeanTest.java

/**
 * Tests instance URI assignment./*w ww .jav a 2 s . com*/
 *
 * @throws Exception in any error occurred during the test.
 */
public void testSetInstanceURI() throws Exception {
    this.processor.setXMLContainer(this.form);
    this.processor.setInstanceURI("instance-1", "test-uri");

    Element instance = (Element) this.processor.getXMLContainer()
            .getElementsByTagNameNS(NamespaceCtx.XFORMS_NS, "instance").item(1);

    assertTrue(instance.hasAttributeNS(NamespaceCtx.XFORMS_NS, "src"));
    assertTrue(instance.getAttributeNS(NamespaceCtx.XFORMS_NS, "src").equals("test-uri"));
}

From source file:org.chiba.xml.xforms.test.ChibaBeanTest.java

/**
 * Tests default instance URI assignment.
 *
 * @throws Exception in any error occurred during the test.
 *//*  w ww.  jav a 2 s.  c  o m*/
public void testSetInstanceURIDefault() throws Exception {
    this.processor.setXMLContainer(this.form);
    this.processor.setInstanceURI("", "test-uri");

    Element instance = (Element) this.processor.getXMLContainer()
            .getElementsByTagNameNS(NamespaceCtx.XFORMS_NS, "instance").item(0);

    assertTrue(instance.hasAttributeNS(NamespaceCtx.XFORMS_NS, "src"));
    assertTrue(instance.getAttributeNS(NamespaceCtx.XFORMS_NS, "src").equals("test-uri"));
}

From source file:org.chiba.xml.xforms.test.ChibaBeanTest.java

/**
 * Tests submission URI assignment.//from w w w. j av  a  2s  .co  m
 *
 * @throws Exception in any error occurred during the test.
 */
public void testSetSubmissionURI() throws Exception {
    this.processor.setXMLContainer(this.form);
    this.processor.setSubmissionURI("submission-1", "test-uri");

    Element submission = (Element) this.processor.getXMLContainer()
            .getElementsByTagNameNS(NamespaceCtx.XFORMS_NS, "submission").item(1);

    assertTrue(submission.hasAttributeNS(NamespaceCtx.XFORMS_NS, "action"));
    assertTrue(submission.getAttributeNS(NamespaceCtx.XFORMS_NS, "action").equals("test-uri"));
}

From source file:org.chiba.xml.xforms.test.ChibaBeanTest.java

/**
 * Tests submission URI assignment./*from w  ww.  j  a va  2  s  .  c o m*/
 *
 * @throws Exception in any error occurred during the test.
 */
public void testSetSubmissionURIDefault() throws Exception {
    this.processor.setXMLContainer(this.form);
    this.processor.setSubmissionURI("", "test-uri");

    Element submission = (Element) this.processor.getXMLContainer()
            .getElementsByTagNameNS(NamespaceCtx.XFORMS_NS, "submission").item(0);

    assertTrue(submission.hasAttributeNS(NamespaceCtx.XFORMS_NS, "action"));
    assertTrue(submission.getAttributeNS(NamespaceCtx.XFORMS_NS, "action").equals("test-uri"));
}

From source file:org.chiba.xml.xforms.ui.Repeat.java

private void initializePrototype(Node parent, Node prototype) {
    Node copy = prototype.cloneNode(false);
    if (copy.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) copy;
        if (element.getAttributeNS(null, "id").length() == 0) {
            element.setAttributeNS(null, "id", this.container.generateId());
        }/*from ww  w.  j  a va2  s .c  om*/

        NodeList children = prototype.getChildNodes();
        for (int index = 0; index < children.getLength(); index++) {
            initializePrototype(element, children.item(index));
        }
    }

    parent.appendChild(copy);
}

From source file:org.deegree.portal.context.WebMapContextFactory.java

/**
 * creates an instance of an URL described by a <OnlineResource> element
 * //  ww  w.j av  a 2  s . co  m
 * @param element
 *            <OnlineResource>
 * 
 * @return instance of <tt>URL</tt>
 * 
 * @throws XMLParsingException
 */
private static URL createOnlineResource(Element element) throws XMLParsingException {

    URL onlineResource = null;

    if (element != null) {
        String type = element.getAttributeNS(CommonNamespaces.XLNNS.toASCIIString(), "type");
        if ((type != null) && !"".equals(type) && !type.equals("simple")) {
            throw new XMLParsingException("unknown type of online resource: " + type);
        }
        String tmp = element.getAttributeNS(CommonNamespaces.XLNNS.toASCIIString(), "href");
        if (!isImageURL(tmp)) {
            tmp = OWSUtils.validateHTTPGetBaseURL(tmp);
        }

        try {
            onlineResource = new URL(tmp);
        } catch (Exception e) {
            e.printStackTrace();
            throw new XMLParsingException("couldn't create online resource", e);
        }
    }

    return onlineResource;
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Get a boolean attribute from the supplied element.
 * @param element The element.//  w  w  w .j  av  a  2 s  .co m
 * @param namespaceURI Namespace URI of the required attribute.
 * @param attribName The attribute name.
 * @return True if the attribute value is "true" (case insensitive), otherwise false.
 */
public static boolean getBooleanAttrib(Element element, String attribName, String namespaceURI) {
    AssertArgument.isNotNull(element, "element");
    AssertArgument.isNotNullAndNotEmpty(attribName, "attribName");
    AssertArgument.isNotNullAndNotEmpty(namespaceURI, "namespaceURI");

    String attribVal = element.getAttributeNS(namespaceURI, attribName);

    return (attribVal != null ? attribVal.equalsIgnoreCase("true") : false);
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Get attribute value, returning <code>null</code> if unset.
 * <p/>//from   www  .  j a v a2 s  . c  o  m
 * Some DOM implementations return an empty string for an unset
 * attribute.
 * @param element The DOM element.
 * @param attributeName The attribute to get.
 * @param namespaceURI Namespace URI of the required attribute, or null
 * to perform a non-namespaced get.
 * @return The attribute value, or <code>null</code> if unset.
 */
public static String getAttributeValue(Element element, String attributeName, String namespaceURI) {
    AssertArgument.isNotNull(element, "element");
    AssertArgument.isNotNullAndNotEmpty(attributeName, "attributeName");

    String attributeValue;

    if (namespaceURI == null) {
        attributeValue = element.getAttribute(attributeName);
    } else {
        attributeValue = element.getAttributeNS(namespaceURI, attributeName);
    }

    if (attributeValue.length() == 0 && !element.hasAttribute(attributeName)) {
        return null;
    }

    return attributeValue;
}

From source file:org.exist.xquery.modules.oracle.ExecuteFunction.java

private void setParametersOnPreparedStatement(Statement stmt, Element parametersElement)
        throws SQLException, XPathException {

    if (parametersElement.getNamespaceURI().equals(OracleModule.NAMESPACE_URI)
            && parametersElement.getLocalName().equals(PARAMETERS_ELEMENT_NAME)) {
        NodeList paramElements = parametersElement.getElementsByTagNameNS(OracleModule.NAMESPACE_URI,
                PARAM_ELEMENT_NAME);//from  w ww.  j av  a2  s. c om

        for (int i = 0; i < paramElements.getLength(); i++) {
            Element param = ((Element) paramElements.item(i));
            String value = param.getFirstChild().getNodeValue();
            String type = param.getAttributeNS(OracleModule.NAMESPACE_URI, TYPE_ATTRIBUTE_NAME);
            int position = Integer
                    .parseInt(param.getAttributeNS(OracleModule.NAMESPACE_URI, POSITION_ATTRIBUTE_NAME));
            try {
                int sqlType = SQLUtils.sqlTypeFromString(type);
                // What if SQL type is date???
                if (sqlType == Types.DATE) {
                    Date date = xmlDf.parse(value);
                    ((PreparedStatement) stmt).setTimestamp(position, new Timestamp(date.getTime()));
                } else {
                    ((PreparedStatement) stmt).setObject(position, value, sqlType);
                }
            } catch (ParseException pex) {
                throw new XPathException(this, "Unable to parse date from value " + value
                        + ". Expected format is YYYY-MM-DDThh:mm:ss.sss");
            } catch (Exception ex) {
                throw new XPathException(this, "Failed to set stored procedure parameter at position "
                        + position + " as " + type + " with value " + value);
            }
        }
    }
}

From source file:org.exist.xquery.modules.sql.ExecuteFunction.java

/**
 * evaluate the call to the XQuery execute() function, it is really the main entry point of this class.
 *
 * @param   args             arguments from the execute() function call
 * @param   contextSequence  the Context Sequence to operate on (not used here internally!)
 *
 * @return  A node representing the SQL result set
 *
 * @throws  XPathException  DOCUMENT ME!
 *
 * @see     org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 *//*from  www .  j  a  v a2s  . c o m*/
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a connection and SQL statement specified?
    if (args[0].isEmpty() || args[1].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    // get the Connection
    long connectionUID = ((IntegerValue) args[0].itemAt(0)).getLong();
    Connection con = SQLModule.retrieveConnection(context, connectionUID);

    if (con == null) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    boolean preparedStmt = false;

    //setup the SQL statement
    String sql = null;
    Statement stmt = null;
    boolean executeResult = false;
    ResultSet rs = null;

    try {
        boolean makeNodeFromColumnName = false;
        MemTreeBuilder builder = context.getDocumentBuilder();
        int iRow = 0;

        //SQL or PreparedStatement?
        if (args.length == 3) {

            // get the SQL statement
            sql = args[1].getStringValue();
            stmt = con.createStatement();
            makeNodeFromColumnName = ((BooleanValue) args[2].itemAt(0)).effectiveBooleanValue();

            //execute the statement
            executeResult = stmt.execute(sql);

        } else if (args.length == 4) {

            preparedStmt = true;

            //get the prepared statement
            long statementUID = ((IntegerValue) args[1].itemAt(0)).getLong();
            PreparedStatementWithSQL stmtWithSQL = SQLModule.retrievePreparedStatement(context, statementUID);
            sql = stmtWithSQL.getSql();
            stmt = stmtWithSQL.getStmt();
            makeNodeFromColumnName = ((BooleanValue) args[3].itemAt(0)).effectiveBooleanValue();

            if (!args[2].isEmpty()) {
                setParametersOnPreparedStatement(stmt, (Element) args[2].itemAt(0));
            }

            //execute the prepared statement
            executeResult = ((PreparedStatement) stmt).execute();
        } else {
            //TODO throw exception
        }

        // DW: stmt can be null ?

        // execute the query statement
        if (executeResult) {
            /* SQL Query returned results */

            // iterate through the result set building an XML document
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int iColumns = rsmd.getColumnCount();

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("count", null, null), String.valueOf(-1));

            while (rs.next()) {
                builder.startElement(new QName("row", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
                builder.addAttribute(new QName("index", null, null), String.valueOf(rs.getRow()));

                // get each tuple in the row
                for (int i = 0; i < iColumns; i++) {
                    String columnName = rsmd.getColumnLabel(i + 1);

                    if (columnName != null) {

                        String colElement = "field";

                        if (makeNodeFromColumnName && columnName.length() > 0) {
                            // use column names as the XML node

                            /**
                             * Spaces in column names are replaced with
                             * underscore's
                             */
                            colElement = SQLUtils.escapeXmlAttr(columnName.replace(' ', '_'));
                        }

                        builder.startElement(new QName(colElement, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                null);

                        if (!makeNodeFromColumnName || columnName.length() <= 0) {
                            String name;

                            if (columnName.length() > 0) {
                                name = SQLUtils.escapeXmlAttr(columnName);
                            } else {
                                name = "Column: " + String.valueOf(i + 1);
                            }

                            builder.addAttribute(new QName("name", null, null), name);
                        }

                        builder.addAttribute(
                                new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                rsmd.getColumnTypeName(i + 1));
                        builder.addAttribute(new QName(TYPE_ATTRIBUTE_NAME, Namespaces.SCHEMA_NS, "xs"),
                                Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1))));

                        //get the content
                        if (rsmd.getColumnType(i + 1) == Types.SQLXML) {
                            //parse sqlxml value
                            try {
                                final SQLXML sqlXml = rs.getSQLXML(i + 1);

                                if (rs.wasNull()) {
                                    // Add a null indicator attribute if the value was SQL Null
                                    builder.addAttribute(
                                            new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                            "true");
                                } else {

                                    SAXParserFactory factory = SAXParserFactory.newInstance();
                                    factory.setNamespaceAware(true);
                                    InputSource src = new InputSource(sqlXml.getCharacterStream());
                                    SAXParser parser = factory.newSAXParser();
                                    XMLReader xr = parser.getXMLReader();

                                    SAXAdapter adapter = new AppendingSAXAdapter(builder);
                                    xr.setContentHandler(adapter);
                                    xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
                                    xr.parse(src);
                                }
                            } catch (Exception e) {
                                throw new XPathException(
                                        "Could not parse column of type SQLXML: " + e.getMessage(), e);
                            }
                        } else {
                            //otherwise assume string value
                            final String colValue = rs.getString(i + 1);

                            if (rs.wasNull()) {
                                // Add a null indicator attribute if the value was SQL Null
                                builder.addAttribute(
                                        new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), "true");
                            } else {
                                if (colValue != null) {
                                    builder.characters(SQLUtils.escapeXmlText(colValue));
                                }
                            }
                        }

                        builder.endElement();
                    }
                }

                builder.endElement();
                iRow++;
            }

            builder.endElement();
        } else {
            /* SQL Query performed updates */

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("updateCount", null, null), String.valueOf(stmt.getUpdateCount()));
            builder.endElement();
        }

        // Change the root element count attribute to have the correct value
        NodeValue node = (NodeValue) builder.getDocument().getDocumentElement();
        Node count = node.getNode().getAttributes().getNamedItem("count");

        if (count != null) {
            count.setNodeValue(String.valueOf(iRow));
        }

        builder.endDocument();

        // return the XML result set
        return (node);

    } catch (SQLException sqle) {
        LOG.error("sql:execute() Caught SQLException \"" + sqle.getMessage() + "\" for SQL: \"" + sql + "\"",
                sqle);

        //return details about the SQLException
        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("exception", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        boolean recoverable = false;

        if (sqle instanceof SQLRecoverableException) {
            recoverable = true;
        }
        builder.addAttribute(new QName("recoverable", null, null), String.valueOf(recoverable));

        builder.startElement(new QName("state", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(sqle.getSQLState());
        builder.endElement();

        builder.startElement(new QName("message", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        String state = sqle.getMessage();

        if (state != null) {
            builder.characters(state);
        }

        builder.endElement();

        builder.startElement(new QName("stack-trace", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        ByteArrayOutputStream bufStackTrace = new ByteArrayOutputStream();
        sqle.printStackTrace(new PrintStream(bufStackTrace));
        builder.characters(new String(bufStackTrace.toByteArray()));
        builder.endElement();

        builder.startElement(new QName("sql", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(SQLUtils.escapeXmlText(sql));
        builder.endElement();

        if (stmt instanceof PreparedStatement) {
            Element parametersElement = (Element) args[2].itemAt(0);

            if (parametersElement.getNamespaceURI().equals(SQLModule.NAMESPACE_URI)
                    && parametersElement.getLocalName().equals(PARAMETERS_ELEMENT_NAME)) {
                NodeList paramElements = parametersElement.getElementsByTagNameNS(SQLModule.NAMESPACE_URI,
                        PARAM_ELEMENT_NAME);

                builder.startElement(
                        new QName(PARAMETERS_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                for (int i = 0; i < paramElements.getLength(); i++) {
                    Element param = ((Element) paramElements.item(i));
                    String value = param.getFirstChild().getNodeValue();
                    String type = param.getAttributeNS(SQLModule.NAMESPACE_URI, TYPE_ATTRIBUTE_NAME);

                    builder.startElement(
                            new QName(PARAM_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                    builder.addAttribute(
                            new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), type);
                    builder.characters(SQLUtils.escapeXmlText(value));

                    builder.endElement();
                }

                builder.endElement();
            }
        }

        builder.startElement(new QName("xquery", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.addAttribute(new QName("line", null, null), String.valueOf(getLine()));
        builder.addAttribute(new QName("column", null, null), String.valueOf(getColumn()));
        builder.endElement();

        builder.endElement();
        builder.endDocument();

        return ((NodeValue) builder.getDocument().getDocumentElement());
    } finally {

        // close any record set or statement
        if (rs != null) {

            try {
                rs.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            rs = null;
        }

        if (!preparedStmt && stmt != null) {

            try {
                stmt.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            stmt = null;
        }

    }
}