Example usage for org.w3c.dom Node setNodeValue

List of usage examples for org.w3c.dom Node setNodeValue

Introduction

In this page you can find the example usage for org.w3c.dom Node setNodeValue.

Prototype

public void setNodeValue(String nodeValue) throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:org.ebayopensource.turmeric.eclipse.resources.util.SOAIntfUtil.java

/**
 * The format should be the following/*from ww w. j a  va 2  s. co m*/
 * <wsdl:service name="CreativeService">
 * <wsdl:documentation>
 *    <version>1.0</version>
 * </wsdl:documentation>
 * ...
 *
 * @param project the project
 * @param newVersion the new version
 * @param monitor the monitor
 * @throws Exception the exception
 */
public static void modifyWsdlAppInfoVersion(final IProject project, final String newVersion,
        IProgressMonitor monitor) throws Exception {
    monitor.setTaskName("Modifying service WSDL...");
    final String serviceName = project.getName();
    final IFile wsdlFile = SOAServiceUtil.getWsdlFile(project, serviceName);
    InputStream ins = null;
    Definition wsdl = null;
    try {
        ins = wsdlFile.getContents();
        wsdl = WSDLUtil.readWSDL(ins);
    } finally {
        IOUtils.closeQuietly(ins);
    }
    monitor.worked(10);
    if (wsdl == null)
        return;

    DOMParser domParser = new DOMParser();
    Document doc = null;
    try {
        ins = wsdlFile.getContents();
        domParser.parse(new InputSource(ins));
        doc = domParser.getDocument();
    } finally {
        IOUtils.closeQuietly(ins);
    }
    monitor.worked(10);
    if (doc == null)
        return;

    Node wsdlNode = doc.getFirstChild();
    Node serviceNode = null;
    for (int i = wsdlNode.getChildNodes().getLength() - 1; i >= 0; i--) {
        Node node = wsdlNode.getChildNodes().item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE && ELEM_NAME_SERVICE.equals(node.getLocalName())) {
            serviceNode = node;
            break;
        }
    }
    monitor.worked(10);
    if (serviceNode == null)
        return;

    Node documentationNode = null;
    for (int i = 0; i < serviceNode.getChildNodes().getLength(); i++) {
        Node node = serviceNode.getChildNodes().item(i);
        if (ELEM_NAME_DOCUMENTATION.equals(node.getLocalName())) {
            documentationNode = node;
        }
    }
    monitor.worked(10);

    boolean needUpdateWsdl = false;

    if (documentationNode != null) {
        //we found the documentation node
        Node verNode = null;
        for (int i = 0; i < documentationNode.getChildNodes().getLength(); i++) {
            Node node = documentationNode.getChildNodes().item(i);
            if (ELEM_NAME_VERSION_V2_CAMEL_CASE.equals(node.getLocalName())
                    || ELEM_NAME_VERSION_V3_CAMEL_CASE.equals(node.getLocalName())) {
                verNode = node;
                break;
            }
        }

        if (verNode == null) {
            // add version node to document node if there is no version
            // node.
            Element v3Version = doc.createElement("version");
            Text versionText = doc.createTextNode(newVersion);
            v3Version.appendChild(versionText);
            documentationNode.appendChild(v3Version);
            needUpdateWsdl = true;
        } else {
            if (ELEM_NAME_VERSION_V2_CAMEL_CASE.equals(verNode.getLocalName())) {
                // if current version node is V2 format, replace it with V3
                // format
                Element v3Version = doc.createElement("version");
                Text versionText = doc.createTextNode(newVersion);
                v3Version.appendChild(versionText);
                documentationNode.replaceChild(v3Version, verNode);
                needUpdateWsdl = true;
            } else {
                // current version format is V3, update version value.
                for (int i = 0; i < verNode.getChildNodes().getLength(); i++) {
                    Node node = verNode.getChildNodes().item(i);
                    if (node.getNodeType() == Node.TEXT_NODE
                            && newVersion.equals(node.getNodeValue()) == false) {
                        logger.warning("Version defined in WSDL's service section->", node.getNodeValue(),
                                " is older than the new version->", newVersion);
                        node.setNodeValue(newVersion);
                        needUpdateWsdl = true;
                        break;
                    }
                }
            }
        }
    }

    monitor.worked(10);
    if (needUpdateWsdl == true) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(wsdlFile.getLocation().toFile());
            XMLUtil.writeXML(wsdlNode, writer);
        } finally {
            IOUtils.closeQuietly(writer);
            wsdlFile.refreshLocal(IResource.DEPTH_ONE, monitor);
        }
    } else {
        logger.info("WSDL already have the correct version '", newVersion,
                "', skip the modification for WSDL->", wsdlFile.getLocation());
    }
    monitor.worked(10);
}

From source file:org.eclipse.swordfish.p2.internal.deploy.server.MetadataProcessor.java

/**
 * Add an instruction to the bundle IU metadata
 * This creates all possibly missing nodes and appends the instruction to the
 * node designated for the phase./*from   w  w w  . ja v  a2  s  .  c  om*/
 *  
 * @param bundle - the bundle node
 * @param phase - the phase where the instruction should be added.
 * @param instructionCode - the instruction to be added
 * @return the modified bundle node
 */
private final Node addInstruction(Node bundle, String phase, String instructionCode) {
    Element touchPointDataElem = getOrCreateChild(bundle, TOUCHPOINT_DATA);
    Element instructionsElem = getOrCreateChild(touchPointDataElem, INSTRUCTIONS);

    String instructionQuery = INSTRUCTION + "[@" + KEY + " = '" + phase + "']";
    NodeList instrucList = query(instructionsElem, instructionQuery);

    Element instruction;

    if (instrucList.getLength() == 0) {
        instruction = appendChild(instructionsElem, INSTRUCTION);
        instruction.setAttribute(KEY, phase);
        instruction.appendChild(instruction.getOwnerDocument().createTextNode(""));
    } else {
        instruction = (Element) instrucList.item(0);
    }

    Node instructionTextNode = getTextNode(instruction);

    if (instructionTextNode == null) {
        instructionTextNode = instruction.appendChild(instruction.getOwnerDocument().createTextNode(""));
    }

    String val = instructionTextNode.getNodeValue();

    if ("".equals(val) || val == null) {
        instructionTextNode.setNodeValue(instructionCode);
    } else {
        String delimiter = val.replaceAll(" ", "").replaceAll(CR, "").endsWith(";") ? "" : ";";
        instructionTextNode.setNodeValue(val + delimiter + instructionCode);
    }

    int iCounter = query(instructionsElem, INSTRUCTION).getLength();
    instructionsElem.setAttribute(SIZE, "" + iCounter);

    int tdCounter = query(touchPointDataElem, INSTRUCTIONS).getLength();
    touchPointDataElem.setAttribute(SIZE, "" + tdCounter);
    return bundle;
}

From source file:org.ecoinformatics.seek.ecogrid.EcogridWriter.java

/**
 * This method will set up new value for the list. We only replace the first
 * one./*w w w .j  a va2 s . c o  m*/
 * 
 * @param list
 * @param newValue
 */
private void setNewValueForNode(NodeList list, String newValue) {
    Node cn = list.item(0).getFirstChild();
    if ((cn != null) && (cn.getNodeType() == Node.TEXT_NODE)) {
        log.debug("set new value " + newValue + " for distribution url");
        cn.setNodeValue(newValue);
    }
}

From source file:org.ecoinformatics.seek.ecogrid.EcogridWriter.java

/**
 * Set a new value for an attribute node.
 * /*  w  ww .  j a v a  2 s . com*/
 * @param list
 * @param newValue
 */
private void setNewValueForAttribute(NodeList list, String newValue) {
    if (list != null && list.getLength() > 0) {
        Node cn = list.item(0);
        if (cn != null && cn.getNodeType() == Node.ATTRIBUTE_NODE) {
            //System.out.println("Set new value "+newValue +" for attribute"+cn.getNodeName());
            cn.setNodeValue(newValue);
        }
    }
}

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

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    if (args.length == 5 || args.length == 6) {
        // was a connection and PL/SQL statement specified?
        if (args[0].isEmpty() || args[1].isEmpty()) {
            return (Sequence.EMPTY_SEQUENCE);
        }//  w w w .  j a  va 2  s . c o m

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

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

        // get the PL/SQL statement
        String plSql = args[1].getStringValue();

        // get the input parameters (if any)
        Element parameters = null;
        if (!args[2].isEmpty()) {
            parameters = (Element) args[2].itemAt(0);
        }

        // was a result set position specified?
        int resultSetPos = 0;
        if (!args[3].isEmpty()) {
            resultSetPos = ((IntegerValue) args[3].itemAt(0)).getInt();
        }

        boolean haveReturnCode = false;
        int plSqlSuccess = 1; // default value of 1 for success
        if (args.length == 6) {
            // a return code is expected so what is the value indicating success?
            plSqlSuccess = ((IntegerValue) args[5].itemAt(0)).getInt();
            haveReturnCode = true;
        }

        CallableStatement statement = null;
        ResultSet resultSet = null;

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

            statement = connection.prepareCall(plSql);
            if (haveReturnCode) {
                statement.registerOutParameter(1, Types.NUMERIC);
            }
            if (resultSetPos != 0) {
                statement.registerOutParameter(resultSetPos, OracleTypes.CURSOR);
            }
            if (!args[2].isEmpty()) {
                setParametersOnPreparedStatement(statement, parameters);
            }

            statement.execute();

            if (haveReturnCode) {
                int returnCode = statement.getInt(1);
                if (returnCode != plSqlSuccess) {
                    LOG.error(plSql + " failed [" + returnCode + "]");
                    return (Sequence.EMPTY_SEQUENCE);
                }
            }

            if (resultSetPos != 0) {
                // iterate through the result set building an XML document
                builder.startDocument();

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

                resultSet = (ResultSet) statement.getObject(resultSetPos);

                ResultSetMetaData rsmd = resultSet.getMetaData();
                int iColumns = rsmd.getColumnCount();

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

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

                            String colElement = "field";

                            if (((BooleanValue) args[4].itemAt(0)).effectiveBooleanValue()
                                    && 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, OracleModule.NAMESPACE_URI, OracleModule.PREFIX),
                                    null);

                            if (!((BooleanValue) args[4].itemAt(0)).effectiveBooleanValue()
                                    || 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", OracleModule.NAMESPACE_URI, OracleModule.PREFIX),
                                    rsmd.getColumnTypeName(i + 1));
                            builder.addAttribute(new QName("type", Namespaces.SCHEMA_NS, "xs"),
                                    Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1))));

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

                            if (colValue != null) {
                                builder.characters(SQLUtils.escapeXmlText(colValue));
                            }

                            builder.endElement();
                        }
                    }

                    builder.endElement();

                    iRow++;
                }
                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);
            } else {
                // there was no result set so just return an empty sequence
                return (Sequence.EMPTY_SEQUENCE);
            }
        } catch (SQLException sqle) {

            LOG.error("oracle:execute() Caught SQLException \"" + sqle.getMessage() + "\" for PL/SQL: \""
                    + plSql + "\"", sqle);

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

            builder.startDocument();
            builder.startElement(new QName("exception", OracleModule.NAMESPACE_URI, OracleModule.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", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            String sqlState = sqle.getSQLState();
            if (sqlState != null) {
                builder.characters(sqle.getSQLState());
            } else {
                builder.characters("null");
            }

            builder.endElement();

            builder.startElement(new QName("message", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            builder.characters(sqle.getMessage());
            builder.endElement();

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

            builder.startElement(new QName("oracle", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null);
            builder.characters(SQLUtils.escapeXmlText(plSql));
            builder.endElement();

            int line = getLine();
            int column = getColumn();

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

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

            return (NodeValue) builder.getDocument().getDocumentElement();
        } finally {
            release(connection, statement, resultSet);
        }
    } else {
        throw new XPathException("Invalid number of arguments [" + args.length + "]");
    }
}

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)
 *///w  ww.j av a 2  s  .  c  om
@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;
        }

    }
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected Element getStructure(Document doc, LayoutStructure ls) {
    Element structure = null;//from  w  ww.j av a 2s . com

    // handle migration of legacy namespace
    String type = ls.getType();
    if (type != null && type.startsWith(Constants.LEGACY_NS)) {
        type = Constants.NS + type.substring(Constants.LEGACY_NS.length());
    }

    if (ls.isChannel()) {
        final IPortletDefinition channelDef = this.portletDefinitionRegistry
                .getPortletDefinition(String.valueOf(ls.getChanId()));
        if (channelDef != null && channelApproved(channelDef.getApprovalDate())) {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(), channelDef,
                    ls.getLocale());
        } else {
            // Create an error channel if channel is missing or not approved
            String missingChannel = "Unknown";
            if (channelDef != null) {
                missingChannel = channelDef.getName();
            }
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(),
                    MissingPortletDefinition.INSTANCE, null);
            //        structure = MissingPortletDefinition.INSTANCE.getDocument(doc, channelPrefix + ls.getStructId());
            //        structure = MissingPortletDefinition.INSTANCE.getDocument(doc, channelPrefix + ls.getStructId(),
            //                "The '" + missingChannel + "' channel is no longer available. " +
            //                "Please remove it from your layout.",
            //                -1);
        }
    } else {
        // create folder objects including dlm new types in cp namespace
        if (type != null && type.startsWith(Constants.NS)) {
            structure = doc.createElementNS(Constants.NS_URI, type);
        } else {
            structure = doc.createElement("folder");
        }
        structure.setAttribute("name", ls.getName());
        structure.setAttribute("type", (type != null ? type : "regular"));
    }

    structure.setAttribute("hidden", (ls.isHidden() ? "true" : "false"));
    structure.setAttribute("immutable", (ls.isImmutable() ? "true" : "false"));
    structure.setAttribute("unremovable", (ls.isUnremovable() ? "true" : "false"));
    if (localeAware) {
        structure.setAttribute("locale", ls.getLocale()); // for i18n by Shoji
    }

    /*
     * Parameters from up_layout_param are loaded slightly differently for
     * folders and channels. For folders all parameters are added as attributes
     * of the Element. For channels only those parameters with names starting
     * with the dlm namespace Constants.NS are added as attributes to the Element.
     * Others are added as child parameter Elements.
     */
    if (ls.getParameters() != null) {
        for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
            final StructureParameter sp = (StructureParameter) itr.next();
            String pName = sp.getName();

            // handle migration of legacy namespace
            if (pName.startsWith(Constants.LEGACY_NS)) {
                pName = Constants.NS + sp.getName().substring(Constants.LEGACY_NS.length());
            }

            if (!ls.isChannel()) { // Folder
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                } else {
                    structure.setAttribute(pName, sp.getValue());
                }
            } else // Channel
            {
                // if dealing with a dlm namespace param add as attribute
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                    itr.remove();
                } else {
                    /*
                     * do traditional override processing. some explanation is in
                     * order. The structure element was created by the
                     * ChannelDefinition and only contains parameter children if the
                     * definition had defined parameters. These are checked for each
                     * layout loaded parameter as found in LayoutStructure.parameters.
                     * If a name match is found then we need to see if overriding is
                     * allowed and if so we set the value on the child parameter
                     * element. At that point we are done with that version loaded
                     * from the layout so we remove it from the in-memory set of
                     * parameters that are being merged-in. Then, after all such have
                     * been checked against those added by the channel definition we
                     * add in any remaining as adhoc, unregulated parameters.
                     */
                    final NodeList nodeListParameters = structure.getElementsByTagName("parameter");
                    for (int j = 0; j < nodeListParameters.getLength(); j++) {
                        final Element parmElement = (Element) nodeListParameters.item(j);
                        final NamedNodeMap nm = parmElement.getAttributes();

                        final String nodeName = nm.getNamedItem("name").getNodeValue();
                        if (nodeName.equals(pName)) {
                            final Node override = nm.getNamedItem("override");
                            if (override != null && override.getNodeValue().equals("yes")) {
                                final Node valueNode = nm.getNamedItem("value");
                                valueNode.setNodeValue(sp.getValue());
                            }
                            itr.remove();
                            break; // found the corresponding one so skip the rest
                        }
                    }
                }
            }
        }
        // For channels, add any remaining parameter elements loaded with the
        // layout as adhoc, unregulated, parameter children that can be overridden.
        if (ls.isChannel()) {
            for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
                final StructureParameter sp = (StructureParameter) itr.next();
                final Element parameter = doc.createElement("parameter");
                parameter.setAttribute("name", sp.getName());
                parameter.setAttribute("value", sp.getValue());
                parameter.setAttribute("override", "yes");
                structure.appendChild(parameter);
            }
        }
    }
    // finish setting up elements based on loaded params
    final String origin = structure.getAttribute(Constants.ATT_ORIGIN);
    final String prefix = ls.isChannel() ? channelPrefix : folderPrefix;

    // if not null we are dealing with a node incorporated from another
    // layout and this node contains changes made by the user so handle
    // id swapping.
    if (!origin.equals("")) {
        structure.setAttributeNS(Constants.NS_URI, Constants.ATT_PLF_ID, prefix + ls.getStructId());
        structure.setAttribute("ID", origin);
    } else if (!ls.isChannel())
    // regular folder owned by this user, need to check if this is a
    // directive or ui element. If the latter then use traditional id
    // structure
    {
        if (type != null && type.startsWith(Constants.NS)) {
            structure.setAttribute("ID", Constants.DIRECTIVE_PREFIX + ls.getStructId());
        } else {
            structure.setAttribute("ID", folderPrefix + ls.getStructId());
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding identifier " + folderPrefix + ls.getStructId());
        }
        structure.setAttribute("ID", channelPrefix + ls.getStructId());
    }
    structure.setIdAttribute(Constants.ATT_ID, true);
    return structure;
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Processes the Topics in the BuildDatabase and builds up the images found within the topics XML. If the image reference is
 * blank or invalid it is replaced by the fail penguin image.
 *
 * @param buildData Information and data structures for the build.
 *///from   w  ww . j a v a  2  s . c  o  m
@SuppressWarnings("unchecked")
private void processImageLocations(final BuildData buildData) {
    final List<Integer> topicIds = buildData.getBuildDatabase().getTopicIds();
    for (final Integer topicId : topicIds) {
        final ITopicNode topicNode = buildData.getBuildDatabase().getTopicNodesForTopicID(topicId).get(0);
        final BaseTopicWrapper<?> topic = topicNode.getTopic();

        if (log.isDebugEnabled())
            log.debug("\tProcessing SpecTopic " + topicNode.getId()
                    + (topicNode.getRevision() != null ? (", " + "Revision " + topicNode.getRevision()) : ""));

        /*
         * Images have to be in the image folder in Publican. Here we loop through all the imagedata elements and fix up any
         * reference to an image that is not in the images folder.
         */
        final List<Node> images = XMLUtilities.getChildNodes(topicNode.getXMLDocument(), "imagedata",
                "inlinegraphic");

        for (final Node imageNode : images) {
            final NamedNodeMap attributes = imageNode.getAttributes();
            if (attributes != null) {
                final Node fileRefAttribute = attributes.getNamedItem("fileref");

                if (fileRefAttribute != null && (fileRefAttribute.getNodeValue() == null
                        || fileRefAttribute.getNodeValue().isEmpty())) {
                    fileRefAttribute.setNodeValue("images/" + BuilderConstants.FAILPENGUIN_PNG_NAME + ".jpg");
                    buildData.getImageLocations()
                            .add(new TopicImageData(topic, fileRefAttribute.getNodeValue()));
                } else if (fileRefAttribute != null && fileRefAttribute.getNodeValue() != null) {
                    final String fileRefValue = fileRefAttribute.getNodeValue();
                    if (BuilderConstants.IMAGE_FILE_REF_PATTERN.matcher(fileRefValue).matches()) {
                        if (fileRefValue.startsWith("./images/")) {
                            fileRefAttribute.setNodeValue(fileRefValue.substring(2));
                        } else if (!fileRefValue.startsWith("images/")) {
                            fileRefAttribute.setNodeValue("images/" + fileRefValue);
                        }

                        buildData.getImageLocations()
                                .add(new TopicImageData(topic, fileRefAttribute.getNodeValue()));
                    } else if (!BuilderConstants.COMMON_CONTENT_FILE_REF_PATTERN.matcher(fileRefValue)
                            .matches()) {
                        // The file isn't common content or a pressgang image so mark it as a missing image.
                        fileRefAttribute
                                .setNodeValue("images/" + BuilderConstants.FAILPENGUIN_PNG_NAME + ".jpg");
                        buildData.getImageLocations()
                                .add(new TopicImageData(topic, fileRefAttribute.getNodeValue()));
                    }
                }
            }
        }
    }
}

From source file:org.jbpm.bpel.xml.util.XmlUtil.java

public static void setObjectValue(Node node, Object value) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        setObjectValue((Element) node, value);
        break;//from   w  ww  .  j  a  v a 2 s  .  c  o  m
    case Node.DOCUMENT_NODE:
        setObjectValue(((Document) node).getDocumentElement(), value);
        break;
    default:
        // BPEL-243 throw selectionFailure if the source is an EII with xsi:nil=true
        if (value instanceof Element) {
            String nil = ((Element) value).getAttributeNS(BpelConstants.NS_XML_SCHEMA_INSTANCE,
                    BpelConstants.ATTR_NIL);
            if (DatatypeUtil.parseBoolean(nil) == Boolean.TRUE)
                throw new BpelFaultException(BpelConstants.FAULT_SELECTION_FAILURE);
        }
        // replace content
        node.setNodeValue(DatatypeUtil.toString(value));
    }
}

From source file:org.jbpm.bpel.xml.util.XmlUtil.java

public static void setStringValue(Element elem, String value) {
    // remove jbpm:initialized
    elem.removeAttributeNS(BpelConstants.NS_VENDOR, BpelConstants.ATTR_INITIALIZED);

    Node firstChild = elem.getFirstChild();
    // if first child is a text node, reuse it
    if (firstChild instanceof org.w3c.dom.Text)
        firstChild.setNodeValue(value);
    // otherwise, just create a new text node
    else/*  w w w . j a v a2 s  . c om*/
        firstChild = elem.getOwnerDocument().createTextNode(value);

    // remove all children
    removeChildNodes(elem);
    // append text
    elem.appendChild(firstChild);
}