Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import flat storages to the hierarchical storage
 *
 * @param con an open and valid connection to store imported data
 * @param zip zip file containing the data
 * @throws Exception on errors//from   w w  w.ja  v a2  s  .  c  o m
 */
protected void importFlatStoragesHierarchical(Connection con, ZipFile zip) throws Exception {
    //mapping: storage->level->columnname->assignment id
    final Map<String, Map<Integer, Map<String, Long>>> flatAssignmentMapping = new HashMap<String, Map<Integer, Map<String, Long>>>(
            5);
    //mapping: assignment id->position index
    final Map<Long, Integer> assignmentPositions = new HashMap<Long, Integer>(100);
    //mapping: flatstorage->column sizes [string,bigint,double,select,text]
    final Map<String, Integer[]> flatstoragesColumns = new HashMap<String, Integer[]>(5);
    ZipEntry zeMeta = getZipEntry(zip, FILE_FLATSTORAGE_META);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(zip.getInputStream(zeMeta));
    XPath xPath = XPathFactory.newInstance().newXPath();

    //calculate column sizes
    NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document,
            XPathConstants.NODESET);
    Node currNode;
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue());
        int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue());
        int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue());
        int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue());
        int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue());
        String tableName = null;
        if (currNode.hasChildNodes()) {
            for (int j = 0; j < currNode.getChildNodes().getLength(); j++)
                if (currNode.getChildNodes().item(j).getNodeName().equals("name")) {
                    tableName = currNode.getChildNodes().item(j).getTextContent();
                }
        }
        if (tableName != null) {
            flatstoragesColumns.put(tableName, new Integer[] { cstring, cbigInt, cdouble, cselect, ctext });
        }
    }

    //parse mappings
    nodes = (NodeList) xPath.evaluate("/flatstorageMeta/mapping", document, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        long assignment = Long.valueOf(currNode.getAttributes().getNamedItem("assid").getNodeValue());
        int level = Integer.valueOf(currNode.getAttributes().getNamedItem("lvl").getNodeValue());
        String storage = null;
        String columnname = null;
        final NodeList childNodes = currNode.getChildNodes();
        for (int c = 0; c < childNodes.getLength(); c++) {
            Node child = childNodes.item(c);
            if ("tblname".equals(child.getNodeName()))
                storage = child.getTextContent();
            else if ("colname".equals(child.getNodeName()))
                columnname = child.getTextContent();
        }
        if (storage == null || columnname == null)
            throw new Exception("Invalid flatstorage export: could not read storage or column name!");
        if (!flatAssignmentMapping.containsKey(storage))
            flatAssignmentMapping.put(storage, new HashMap<Integer, Map<String, Long>>(20));
        Map<Integer, Map<String, Long>> levelMap = flatAssignmentMapping.get(storage);
        if (!levelMap.containsKey(level))
            levelMap.put(level, new HashMap<String, Long>(30));
        Map<String, Long> columnMap = levelMap.get(level);
        if (!columnMap.containsKey(columnname))
            columnMap.put(columnname, assignment);
        //calculate position
        assignmentPositions.put(assignment,
                getAssignmentPosition(flatstoragesColumns.get(storage), columnname));
    }
    if (flatAssignmentMapping.size() == 0) {
        LOG.warn("No flatstorage assignments found to process!");
        return;
    }
    ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT);

    final String xpathStorage = "flatstorages/storage";
    final String xpathData = "flatstorages/storage/data";

    final PreparedStatement psGetAssInfo = con.prepareStatement(
            "SELECT DISTINCT a.APROPERTY,a.XALIAS,p.DATATYPE FROM " + DatabaseConst.TBL_STRUCT_ASSIGNMENTS
                    + " a, " + DatabaseConst.TBL_STRUCT_PROPERTIES + " p WHERE a.ID=? AND p.ID=a.APROPERTY");
    final Map<Long, Object[]> assignmentPropAlias = new HashMap<Long, Object[]>(assignmentPositions.size());
    final String insert1 = "INSERT INTO " + DatabaseConst.TBL_CONTENT_DATA +
    //1  2   3   4    5     6      =1     =1    =1     =1          7         8          9
            "(ID,VER,POS,LANG,TPROP,ASSIGN,XDEPTH,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISMLDEF,";
    final String insert2 = "(?,?,?,?,1,?,?,1,1,1,?,?,?,";
    final PreparedStatement psString = con
            .prepareStatement(insert1 + "FTEXT1024,UFTEXT1024,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psText = con
            .prepareStatement(insert1 + "FCLOB,UFCLOB,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psDouble = con
            .prepareStatement(insert1 + "FDOUBLE,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psNumber = con
            .prepareStatement(insert1 + "FINT,FSELECT,FBIGINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psLargeNumber = con
            .prepareStatement(insert1 + "FBIGINT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psFloat = con
            .prepareStatement(insert1 + "FFLOAT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psBoolean = con
            .prepareStatement(insert1 + "FBOOL,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psReference = con
            .prepareStatement(insert1 + "FREF,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psSelectOne = con
            .prepareStatement(insert1 + "FSELECT,FINT)VALUES" + insert2 + "?,?)");
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private String currentStorage = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            int insertCount = 0;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
                currentStorage = null;
                insertCount = 0;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                LOG.info("Imported [" + insertCount + "] flatstorage entries into the hierarchical storage");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpathData)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else if (currPath.toString().equals(xpathStorage)) {
                    currentStorage = attributes.getValue("name");
                    LOG.info("Processing storage: " + currentStorage);
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            @SuppressWarnings({ "UnusedDeclaration" })
            private void pushPath(String qName, Attributes att) {
                path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpathData)) {
                    //                        LOG.info("Insert [" + xpathData + "]: [" + data + "]");
                    inTag = false;
                    processData();
                    /*try {
                    if (insertMode) {
                        if (executeInsertPhase) {
                            processColumnSet(insertColumns, psInsert);
                            counter += psInsert.executeUpdate();
                        }
                    } else {
                        if (executeUpdatePhase) {
                            if (processColumnSet(updateSetColumns, psUpdate)) {
                                processColumnSet(updateClauseColumns, psUpdate);
                                counter += psUpdate.executeUpdate();
                            }
                        }
                    }
                    } catch (SQLException e) {
                    throw new SAXException(e);
                    } catch (ParseException e) {
                    throw new SAXException(e);
                    }*/
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            void processData() {
                //                    System.out.println("processing " + currentStorage + " -> " + data);
                final String[] cols = { "string", "bigint", "double", "select", "text" };
                for (String column : data.keySet()) {
                    if (column.endsWith("_mld"))
                        continue;
                    for (String check : cols) {
                        if (column.startsWith(check)) {
                            if ("select".equals(check) && "0".equals(data.get(column)))
                                continue; //dont insert 0-referencing selects
                            try {
                                insertData(column);
                            } catch (SQLException e) {
                                //noinspection ThrowableInstanceNeverThrown
                                throw new FxDbException(e, "ex.db.sqlError", e.getMessage())
                                        .asRuntimeException();
                            }
                        }
                    }
                }
            }

            private void insertData(String column) throws SQLException {
                final int level = Integer.parseInt(data.get("lvl"));
                long assignment = flatAssignmentMapping.get(currentStorage).get(level)
                        .get(column.toUpperCase());
                int pos = FxArrayUtils.getIntElementAt(data.get("positions"), ',',
                        assignmentPositions.get(assignment));
                String _valueData = data.get("valuedata");
                Integer valueData = _valueData == null ? null
                        : FxArrayUtils.getHexIntElementAt(data.get("valuedata"), ',',
                                assignmentPositions.get(assignment));
                Object[] propXP = getPropertyXPathDataType(assignment);
                long prop = (Long) propXP[0];
                String xpath = (String) propXP[1];
                FxDataType dataType;
                try {
                    dataType = FxDataType.getById((Long) propXP[2]);
                } catch (FxNotFoundException e) {
                    throw e.asRuntimeException();
                }
                long id = Long.parseLong(data.get("id"));
                int ver = Integer.parseInt(data.get("ver"));
                long lang = Integer.parseInt(data.get("lang"));
                boolean isMaxVer = "1".equals(data.get("ismax_ver"));
                boolean isLiveVer = "1".equals(data.get("islive_ver"));
                boolean mlDef = "1".equals(data.get(column + "_mld"));
                PreparedStatement ps;
                int vdPos;
                switch (dataType) {
                case String1024:
                    ps = psString;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Text:
                case HTML:
                    ps = psText;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Number:
                    ps = psNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case LargeNumber:
                    ps = psLargeNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Reference:
                    ps = psReference;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Float:
                    ps = psFloat;
                    ps.setFloat(10, Float.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Double:
                    ps = psDouble;
                    ps.setDouble(10, Double.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Boolean:
                    ps = psBoolean;
                    ps.setBoolean(10, "1".equals(data.get(column)));
                    vdPos = 11;
                    break;
                case SelectOne:
                    ps = psSelectOne;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                default:
                    //noinspection ThrowableInstanceNeverThrown
                    throw new FxInvalidParameterException("assignment",
                            "ex.structure.flatstorage.datatype.unsupported", dataType.name())
                                    .asRuntimeException();
                }
                ps.setLong(1, id);
                ps.setInt(2, ver);
                ps.setInt(3, pos);
                ps.setLong(4, lang);
                ps.setLong(5, prop);
                ps.setLong(6, assignment);
                ps.setBoolean(7, isMaxVer);
                ps.setBoolean(8, isLiveVer);
                ps.setBoolean(9, mlDef);
                if (valueData == null)
                    ps.setNull(vdPos, java.sql.Types.NUMERIC);
                else
                    ps.setInt(vdPos, valueData);
                ps.executeUpdate();
                insertCount++;
            }

            /**
             * Get property id, xpath and data type for an assignment
             *
             * @param assignment assignment id
             * @return Object[] {propertyId, xpath, datatype}
             */
            private Object[] getPropertyXPathDataType(long assignment) {
                if (assignmentPropAlias.get(assignment) != null)
                    return assignmentPropAlias.get(assignment);
                try {
                    psGetAssInfo.setLong(1, assignment);
                    ResultSet rs = psGetAssInfo.executeQuery();
                    if (rs != null && rs.next()) {
                        Object[] data = new Object[] { rs.getLong(1), rs.getString(2), rs.getLong(3) };
                        assignmentPropAlias.put(assignment, data);
                        return data;
                    }
                } catch (SQLException e) {
                    throw new IllegalArgumentException(
                            "Could not load data for assignment " + assignment + ": " + e.getMessage());
                }
                throw new IllegalArgumentException("Could not load data for assignment " + assignment + "!");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        parser.parse(zip.getInputStream(zeData), handler);
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psGetAssInfo, psString, psBoolean, psDouble,
                psFloat, psLargeNumber, psNumber, psReference, psSelectOne, psText);
    }
}

From source file:org.dasein.cloud.aws.platform.RDS.java

private ConfigurationParameter toParameter(Node pNode) throws CloudException {
    ConfigurationParameter param = new ConfigurationParameter();
    NodeList attrs = pNode.getChildNodes();

    param.setModifiable(false);//from   ww w. j a  v a 2 s.  com
    param.setApplyImmediately(false);
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);
        String name;

        name = attr.getNodeName();
        if (name.equalsIgnoreCase("ParameterValue")) {
            param.setParameter(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("DataType")) {
            param.setDataType(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("IsModifiable") && attr.hasChildNodes()) {
            param.setModifiable(attr.getFirstChild().getNodeValue().trim().equalsIgnoreCase("true"));
        } else if (name.equalsIgnoreCase("Description")) {
            param.setDescription(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("AllowedValues") && attr.hasChildNodes()) {
            param.setValidation(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("ParameterName")) {
            param.setKey(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("ApplyType") && attr.hasChildNodes()) {
            param.setApplyImmediately(attr.getFirstChild().getNodeValue().trim().equalsIgnoreCase("static"));
        }
    }
    return param;
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * replace elements in originalDom with modifiedDom according to listed
 * xPaths, if the originalDom has elements not listed in the xPath, it will
 * be kept untouched. in the HashMap<String, String> xPathPairs, the key is
 * the path in the source xml, and the value is the xpath for the final
 * note*: the if the xpath has attributes, it's not going to work... need to
 * do a custom implementation when that use case happened...
 * //w  w  w .  jav a 2 s  .  c  o  m
 * @param originalDom
 * @param modifiedDom
 * @param xPaths
 * @return
 * @throws XPathExpressionException
 */
private Document replaceByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

    Document finalDom = originalDom;
    Element finalDomRoot = (Element) finalDom.getFirstChild();

    Element lastChild = null;

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);
            // remove this node from its parent...
            c.getParentNode().removeChild(c);
        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private Document replaceIfExistingByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

    Document finalDom = originalDom;
    Element finalDomRoot = (Element) finalDom.getFirstChild();

    //Element modifiedDomRoot = (Element) modifiedDom.getFirstChild();

    Element lastChild = null;//www.ja va  2s.  c om

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);

            //xPathExpression = xPath.compile(srcXPath);
            //NodeList srcNodeLst = (NodeList) (xPathExpression.evaluate(
            //modifiedDom, XPathConstants.NODESET));
            //NodeList srcNodeLst = modifiedDomRoot.getElementsByTagName(c.getNodeName());

            if (l > 0) {
                // remove this node from its parent...

                c.getParentNode().removeChild(c);
                logger.debug("Node:" + c.getNodeName() + " is removed!");
            }

        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:com.joliciel.frenchTreebank.search.XmlPatternSearchImpl.java

private PhraseMemberNode traverse(Node node, int depth) {
    {// w  ww  . j a va2 s.com
        LOG.debug(depth + " " + node.getNodeName());
        PhraseMemberNode xmlPatternNode = null;
        Element element = (Element) node;
        String tag = node.getNodeName();
        if (tag == "phrase") {
            String phraseTypes = element.getAttribute("type");
            String functionCodes = element.getAttribute("fct");
            String existsString = element.getAttribute("exists");
            boolean exists = existsString == null || !(existsString.equals("no"));
            LOG.debug(
                    "Phrase type: " + phraseTypes + ", fct = " + functionCodes + ", exists = " + existsString);
            xmlPatternNode = new PhraseNode(phraseTypes, functionCodes, exists, phraseCounter++);
        } else if (tag == "w") {
            String categoryCode = element.getAttribute("cat");
            String subCategoryCode = element.getAttribute("subcat");
            String lemma = element.getAttribute("lemma");
            String word = element.getTextContent();
            String existsString = element.getAttribute("exists");
            boolean exists = existsString == null || !(existsString.equals("no"));
            LOG.debug("w: cat=" + categoryCode + ", subcat = " + subCategoryCode + ", lemma=" + lemma
                    + ", word=" + word + ", exists = " + existsString);
            xmlPatternNode = new WordNode(categoryCode, subCategoryCode, lemma, word, exists,
                    phraseUnitCounter++);
        } else {
            String phraseTypes = node.getNodeName();
            String functionCodes = element.getAttribute("fct");
            String existsString = element.getAttribute("exists");
            boolean exists = existsString == null || !(existsString.equals("no"));
            LOG.debug(
                    "Phrase type: " + phraseTypes + ", fct = " + functionCodes + ", exists = " + existsString);
            xmlPatternNode = new PhraseNode(phraseTypes, functionCodes, exists, phraseCounter++);
        }

        if (xmlPatternNode instanceof PhraseNode) {
            if (node.hasChildNodes()) {
                Node child = node.getFirstChild();
                while (child != null) {
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        PhraseNode phraseNode = (PhraseNode) xmlPatternNode;
                        PhraseMemberNode childNode = this.traverse(child, depth + 1);
                        phraseNode.addNode(childNode);
                        childNode.setParent(phraseNode);
                    }
                    child = child.getNextSibling();
                }
            }
        } else if (xmlPatternNode instanceof WordNode) {
            if (node.hasChildNodes()) {
                Node child = node.getFirstChild();
                while (child != null) {
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        WordNode wordNode = (WordNode) xmlPatternNode;
                        ComponentWordNode childNode = this.getComponentWordNode(child);
                        wordNode.addNode(childNode);
                        childNode.setParent(wordNode);
                    }
                    child = child.getNextSibling();
                }
            }
        }
        return xmlPatternNode;
    }
}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

private void loadVDC(@Nonnull VDC vdc, @Nonnull String id) throws CloudException, InternalException {
    String xml = get("vdc", id);

    if (xml != null) {
        Document doc = parseXML(xml);
        String docElementTagName = doc.getDocumentElement().getTagName();
        String nsString = "";
        if (docElementTagName.contains(":"))
            nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
        NodeList vdcs = doc.getElementsByTagName(nsString + "Vdc");

        if (vdcs.getLength() < 1) {
            return;
        }/* w  w  w  . ja va 2 s  .com*/
        NodeList attributes = vdcs.item(0).getChildNodes();

        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (attribute.getNodeName().contains(":"))
                nsString = attribute.getNodeName().substring(0, attribute.getNodeName().indexOf(":") + 1);
            else
                nsString = "";

            if (attribute.getNodeName().equalsIgnoreCase(nsString + "Link") && attribute.hasAttributes()) {
                Node rel = attribute.getAttributes().getNamedItem("rel");

                if (rel.getNodeValue().trim().equalsIgnoreCase("add")) {
                    Node type = attribute.getAttributes().getNamedItem("type");
                    Node href = attribute.getAttributes().getNamedItem("href");

                    if (type != null && href != null) {
                        vdc.actions.put(type.getNodeValue().trim(), href.getNodeValue().trim());
                    }
                }
            } else if (attribute.getNodeName().equalsIgnoreCase(nsString + "VmQuota")
                    && attribute.hasChildNodes()) {
                try {
                    vdc.vmQuota = Integer.parseInt(attribute.getFirstChild().getNodeValue().trim());
                } catch (NumberFormatException ignore) {
                    // ignore
                }
            } else if (attribute.getNodeName().equalsIgnoreCase(nsString + "NetworkQuota")
                    && attribute.hasChildNodes()) {
                try {
                    vdc.networkQuota = Integer.parseInt(attribute.getFirstChild().getNodeValue().trim());
                } catch (NumberFormatException ignore) {
                    // ignore
                }
            } else if (attribute.getNodeName().equalsIgnoreCase(nsString + "IsEnabled")
                    && attribute.hasChildNodes()) {
                boolean enabled = attribute.getFirstChild().getNodeValue().trim().equalsIgnoreCase("true");

                if (!enabled) {
                    vdc.dataCenter.setActive(false);
                    vdc.dataCenter.setAvailable(false);
                }
            }
        }
    }
}

From source file:com.nortal.jroad.typegen.xmlbeans.XteeSchemaCodePrinter.java

private Node findFirstNode(final NodeList nodeList, final String elementName, final String name,
        boolean processChildElements) {

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node nNode = nodeList.item(i).cloneNode(true);
        String localName = nNode.getLocalName();
        if (localName != null && nNode.getLocalName().equals(elementName)) {
            if (name == null) {
                return nNode;
            } else {
                if (nNode.hasAttributes()) {
                    Node attrbute = nNode.getAttributes().getNamedItem("name");
                    if (attrbute != null && StringUtils.equals(attrbute.getNodeValue(), name)) {
                        return nNode;
                    }/*  ww  w  .  java  2s.  co m*/
                }
            }
        }
        if (!processChildElements && "element".equals(localName)) {
            continue;
        }
        if (nNode.hasChildNodes()) {
            nNode = findFirstNode(nNode.getChildNodes(), elementName, name, processChildElements);
            if (nNode != null) {
                return nNode;
            }
        }
    }

    return null;
}

From source file:org.dasein.cloud.aws.platform.RDS.java

private Database toDatabase(Node dbNode) throws CloudException {
    NodeList attrs = dbNode.getChildNodes();
    Database db = new Database();
    String engineVersion = null;/*from  w ww  .j  a v  a2 s .  co  m*/

    db.setCreationTimestamp(0L);
    db.setProviderRegionId(getProvider().getContext().getRegionId());
    db.setProviderOwnerId(getProvider().getContext().getAccountNumber());
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);
        String name;

        name = attr.getNodeName();
        if (name.equalsIgnoreCase("EngineVersion")) {
            String val = attr.getFirstChild().getNodeValue().trim();

            if (val != null) {
                db.setEngineVersion(val.toLowerCase().trim());
            }
        } else if (name.equalsIgnoreCase("Engine")) {
            String val = attr.getFirstChild().getNodeValue().trim();
            DatabaseEngine engine = toDatabaseEngine(val);
            db.setEngine(engine);
        } else if (name.equalsIgnoreCase("DBInstanceIdentifier")) {
            db.setProviderDatabaseId(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("DBName")) {
            db.setName(AWSCloud.getTextValue(attr));
        } else if (name.equalsIgnoreCase("MultiAZ")) {
            db.setHighAvailability(attr.getFirstChild().getNodeValue().equalsIgnoreCase("true"));
        } else if (name.equalsIgnoreCase("DBInstanceClass")) {
            db.setProductSize(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("DBInstanceStatus")) {
            db.setCurrentState(toDatabaseState(attr.getFirstChild().getNodeValue().trim()));
        } else if (name.equalsIgnoreCase("Endpoint")) {
            if (attr.hasChildNodes()) {
                NodeList nodes = attr.getChildNodes();

                for (int j = 0; j < nodes.getLength(); j++) {
                    Node child = nodes.item(j);

                    if (child != null) {
                        if (child.getNodeName().equalsIgnoreCase("Port")) {
                            try {
                                db.setHostPort(Integer.parseInt(child.getFirstChild().getNodeValue().trim()));
                            } catch (NumberFormatException e) {
                                throw new CloudException(
                                        "Invalid storage value: " + child.getFirstChild().getNodeValue()); // ignore this
                            }
                        } else if (child.getNodeName().equalsIgnoreCase("Address")) {
                            db.setHostName(child.getFirstChild().getNodeValue().trim());
                        }
                    }
                }
            }
        } else if (name.equalsIgnoreCase("AllocatedStorage")) {
            try {
                db.setAllocatedStorageInGb(Integer.parseInt(attr.getFirstChild().getNodeValue().trim()));
            } catch (NumberFormatException e) {
                throw new CloudException("Invalid storage value: " + attr.getFirstChild().getNodeValue());
            }
        } else if (name.equalsIgnoreCase("MasterUsername")) {
            db.setAdminUser(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("PreferredMaintenanceWindow")) {
            if (attr.hasChildNodes()) {
                String val = attr.getFirstChild().getNodeValue();

                if (val != null) {
                    String[] parts = val.split("-");

                    if (parts.length == 2) {
                        TimeWindow window = getTimeWindow(parts[0], parts[1]);

                        db.setMaintenanceWindow(window);
                    }
                }
            }
        } else if (name.equalsIgnoreCase("PreferredBackupWindow")) {
            if (attr.hasChildNodes()) {
                String val = attr.getFirstChild().getNodeValue();

                if (val != null) {
                    String[] parts = val.split("-");

                    if (parts.length == 2) {
                        TimeWindow window = getTimeWindow(parts[0], parts[1]);

                        db.setBackupWindow(window);
                    }
                }
            }
        } else if (name.equalsIgnoreCase("AvailabilityZone")) {
            db.setProviderDataCenterId(attr.getFirstChild().getNodeValue().trim());
        } else if (name.equalsIgnoreCase("InstanceCreateTime")) {
            String tstr = attr.getFirstChild().getNodeValue().trim();

            db.setCreationTimestamp(getProvider().parseTime(tstr));
        } else if (name.equalsIgnoreCase("LatestRestorableTime")) {
            db.setRecoveryPointTimestamp(getProvider().parseTime(attr.getFirstChild().getNodeValue().trim()));
        } else if (name.equalsIgnoreCase("BackupRetentionPeriod")) {
            try {
                db.setSnapshotRetentionInDays(Integer.parseInt(attr.getFirstChild().getNodeValue().trim()));
            } catch (NumberFormatException e) {
                throw new CloudException(
                        "Invalid backup retention period: " + attr.getFirstChild().getNodeValue());
            }
        } else if (name.equalsIgnoreCase("DBParameterGroups")) {
            NodeList groups = attr.getChildNodes();

            for (int j = 0; j < groups.getLength(); j++) {
                Node group = groups.item(j);

                if (group.getNodeName().equalsIgnoreCase("DBParameterGroup") && group.hasChildNodes()) {
                    NodeList nodes = group.getChildNodes();

                    for (int k = 0; k < nodes.getLength(); k++) {
                        Node child = nodes.item(k);

                        if (child != null) {
                            if (child.getNodeName().equalsIgnoreCase("DBParameterGroupName")) {
                                db.setConfiguration(child.getFirstChild().getNodeValue().trim());
                            }
                        }
                    }
                }
            }
        }
    }
    if (db.getHostName() == null) {
        if (db.getCurrentState().equals(DatabaseState.PENDING)
                || db.getCurrentState().equals(DatabaseState.MODIFYING)
                || db.getCurrentState().equals(DatabaseState.RESTARTING)) {
            db.setHostName("");
        } else {
            System.out.println("DEBUG: null database for " + db.getCurrentState());
            return null;
        }
    }
    if (db.getName() == null) {
        db.setName(db.getProviderDatabaseId());
    }
    return db;
}