Example usage for org.w3c.dom Element getTagName

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

Introduction

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

Prototype

public String getTagName();

Source Link

Document

The name of the element.

Usage

From source file:it.imtech.metadata.MetaUtility.java

private void classifications_reader_taxons(Element iTaxons, TreeMap<Object, Taxon> taxons) throws Exception {
    String TAXON_DE = null;/*from  w  w w . ja  v  a  2s.co m*/
    String sLang = Globals.CURRENT_LOCALE.getLanguage();

    NodeList tList = iTaxons.getChildNodes();
    for (int z = 0; z < tList.getLength(); z++) {
        if (tList.item(z).getNodeType() == Node.ELEMENT_NODE) {
            Element taxon = (Element) tList.item(z);

            if (taxon.getTagName().equals("taxon")) {
                String TID = taxon.getAttribute("ID");

                String upstream_identifier = taxon.getAttribute("upstream_identifier");
                String description = null;

                TreeMap<Object, Taxon> subtaxons = new TreeMap<Object, Taxon>();

                NodeList dList = taxon.getChildNodes();
                for (int d = 0; d < dList.getLength(); d++) {
                    if (dList.item(d).getNodeType() == Node.ELEMENT_NODE) {
                        Element iTaxon = (Element) dList.item(d);
                        if (iTaxon.getTagName().equals("description")) {
                            if (iTaxon.getAttribute("isocode").equals(sLang)) {
                                description = iTaxon.getTextContent();
                            } else if (iTaxon.getAttribute("isocode").equals("de")) {
                                TAXON_DE = iTaxon.getTextContent();
                            }
                        } else if (iTaxon.getTagName().equals("taxons")) {
                            classifications_reader_taxons(iTaxon, subtaxons);
                        }
                    }
                }
                //Fallback DE
                if (description == null) {
                    description = TAXON_DE;
                }
                if (description == null) {
                    throw new Exception("Can't find description for taxon (2)");
                }

                // In die Liste einfuegen
                Taxon t = new Taxon(Integer.parseInt(TID), upstream_identifier, description);
                t.subtaxons = subtaxons;
                taxons.put(Integer.parseInt(TID), t);
            }
        }
    }
}

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Metodo adibito alla lettura ricorsiva dei file delle classificazioni
 *
 * @return TreeMap<Object, Taxon>//from  w  ww  .  j av a2 s. c o m
 * @throws Exception
 */
public void classifications_reader(String sequence, String panelname) throws Exception {
    ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE, Globals.loader);
    String currentlink = "";

    try {
        boolean defaultclassification = true;
        boolean alreadyread = false;

        if (!sequence.isEmpty()) {
            defaultclassification = false;
            currentlink = selectedClassificationList.get(panelname + "---" + sequence);

            if (!currentlink.isEmpty()) {
                if (oefos.containsKey(currentlink))
                    alreadyread = true;
            }
        }

        for (String classificationLink : this.availableClassifications.keySet()) {
            if (!alreadyread && (defaultclassification
                    || (!currentlink.isEmpty() && classificationLink.equals(currentlink)))) {
                defaultclassification = false;

                TreeMap<Object, Taxon> rval = new TreeMap<Object, Taxon>();
                Document doc = Utility.getDocument(classificationLink, true);
                XPath taxonpath = XPathFactory.newInstance().newXPath();
                String expression = "//*[local-name()='classification']";

                NodeList nList = (NodeList) taxonpath.evaluate(expression, doc, XPathConstants.NODESET);

                for (int s = 0; s < nList.getLength(); s++) {
                    Element classification = (Element) nList.item(s);

                    if (classification == null) {
                        throw new Exception("Classification 1 not found");
                    } else {
                        classificationIDS.put(classificationLink, classification.getAttribute("ID"));

                        NodeList tList = classification.getChildNodes();
                        for (int z = 0; z < tList.getLength(); z++) {
                            if (tList.item(z).getNodeType() == Node.ELEMENT_NODE) {
                                Element taxons = (Element) tList.item(z);

                                if (taxons.getTagName().equals("taxons")) {
                                    classifications_reader_taxons(taxons, rval);
                                }
                            }
                        }

                        oefos.put(classificationLink, rval);
                    }
                }
            }
        }

    } catch (Exception ex) {
        throw new Exception(Utility.getBundleString("error4", bundle) + ": " + ex.getMessage());
    }
}

From source file:com.bluexml.side.Integration.alfresco.xforms.webscript.XFormsWork.java

private void replaceIds(Element element, Map<String, String> created) {
    if (StringUtils.equals(element.getTagName(), "target")
            || StringUtils.equals(element.getTagName(), "associationClass")) {
        String newId = created.get(element.getTextContent());
        if (newId != null) {
            element.setTextContent(newId);
        }//from  w  ww.j av a 2s.co  m
    }
    String elementId = element.getAttribute("id");
    String newId = created.get(elementId);
    if (newId != null) {
        element.setAttribute("id", newId);
    }
    List<Element> children = DOMUtil.getAllChildren(element);
    for (Element child : children) {
        replaceIds(child, created);
    }
}

From source file:com.bluexml.side.Integration.alfresco.xforms.webscript.XFormsWork.java

protected String batch() throws Exception {
    String datas = parameters.get("datas");
    // build the DOM tree
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    InputSource source = new InputSource(new StringReader(datas));
    Document document = factory.newDocumentBuilder().parse(source);
    Element batchElement = document.getDocumentElement();

    List<Element> children = DOMUtil.getAllChildren(batchElement);
    Map<String, String> created = new HashMap<String, String>();
    String saveToPath = null;/*from   w  ww  .j  a  v  a  2 s  . com*/
    // ** #1544
    String saveToAttribute = batchElement.getAttribute("saveTo");
    if (StringUtils.trimToNull(saveToAttribute) != null) {
        parameters.put("path", saveToAttribute);
        String createdPath = createPath();
        if (StringUtils.trimToNull(createdPath) != null) {
            saveToPath = saveToAttribute;
        } else {
            logger.error("The target space '" + saveToAttribute
                    + "' does not exist and could not be created. Reverting to the default path.");
        }
    }
    // ** #1544
    String currentId = null;
    try {
        for (Element element : children) {
            replaceIds(element, created);
            if (StringUtils.equals(element.getTagName(), "create")) {
                Element toCreate = DOMUtil.getChild(element, "class");
                String transactionId = toCreate.getAttribute("id");
                currentId = transactionId; // for faulty id management
                NodeRef result = dataLayer.create(saveToPath, toCreate, null);
                created.put(transactionId, result.toString());
            } else if (StringUtils.equals(element.getTagName(), "update")) {
                Element toUpdate = DOMUtil.getChild(element, "class");
                String nodeId = toUpdate.getAttribute("id");
                currentId = nodeId; // for faulty id management
                // ** #1421
                String massAttr = toUpdate.getAttribute("massTagging");
                boolean isMassTagging = StringUtils.equals(massAttr, "true");
                if (isMassTagging) {
                    String result = dataLayer.updateMassTagging(nodeId, toUpdate);
                    created.put("massTagging", result.toString());
                    // ** #1421
                } else {
                    NodeRef result = dataLayer.update(nodeId, toUpdate);
                    created.put(nodeId, result.toString());
                }
            } else if (StringUtils.equals(element.getTagName(), "delete")) {
                dataLayer.delete(element.getTextContent());
            } else if (StringUtils.equals(element.getTagName(), "requester")) {
                if (StringUtils.equals(element.getTextContent(), "XFormsController") == true) {
                    // NOTHING YET
                }
            } else if (StringUtils.equals(element.getTagName(), "attach")) {
                String target = DOMUtil.getChild(element, "targetNode").getTextContent();
                String filename = DOMUtil.getChild(element, "fileName").getTextContent();
                String filepath = DOMUtil.getChild(element, "filePath").getTextContent();
                String mimetype = DOMUtil.getChild(element, "mimeType").getTextContent();
                String contentType = DOMUtil.getChild(element, "contentType").getTextContent();
                String appendStr = DOMUtil.getChild(element, "appendSuffix").getTextContent();
                boolean shouldAppendSuffix = !(StringUtils.equals(appendStr, "false"));

                // we must ensure the receiver is a valid id
                String receiver = target;
                try {
                    @SuppressWarnings("unused")
                    NodeRef nodeRef = new NodeRef(target);
                } catch (Exception e) {
                    receiver = created.get(target);
                }
                dataLayer.attachContent(receiver, filename, filepath, mimetype, contentType,
                        shouldAppendSuffix);
            }
        }
    } catch (RuntimeException e) {
        /*
         * this exception catching enables to retrieve the faulty id which
         * will be an additional
         * information that will be given to user
         */
        this.faultyId = currentId;
        throw e;
    }
    StringBuffer sb = new StringBuffer();
    createdToXML(sb, created);
    return sb.toString();
}

From source file:it.imtech.metadata.MetaUtility.java

private void metadata_reader_metadatas(Element iENode, TreeMap<Object, Metadata> metadatas, boolean forceAdd,
        TreeMap forceAddMID, String sLang) {
    try {/*w  w w.j av  a  2 s . c  o m*/
        if (iENode.getTagName().equals("metadatas")) {
            NodeList nList = iENode.getChildNodes();

            for (int s = 0; s < nList.getLength(); s++) {

                if (nList.item(s).getNodeType() == Node.ELEMENT_NODE) {
                    Element iInnerNode = (Element) nList.item(s);

                    if (iInnerNode.getTagName().equals("metadata")) {
                        String MID = iInnerNode.getAttribute("ID");

                        //Se  hidden rimuovo l'elemento dai forzati
                        String hidden = "0";

                        if (iInnerNode.hasAttribute("hidden")) {
                            hidden = iInnerNode.getAttribute("hidden");
                            forceAddMID.remove(iInnerNode.getAttribute("ID"));
                        }

                        if (forceAddMID.containsKey(MID)) {
                            forceAdd = true;
                        }

                        String MID_parent = iInnerNode.getAttribute("mid_parent");
                        String mandatory = iInnerNode.getAttribute("mandatory");
                        String datatype = iInnerNode.getAttribute("datatype");
                        String editable = iInnerNode.getAttribute("editable");
                        String foxmlname = iInnerNode.getAttribute("forxmlname");
                        String sequence = iInnerNode.getAttribute("sequence");

                        String sequencemulti = "";

                        if (MID_parent.equals("22") || MID_parent.equals("45")) {
                            Node searchparent = iInnerNode;
                            boolean found = false;

                            while (!found) {
                                Element x = (Element) searchparent.getParentNode();
                                if (x.getAttribute("ID").equals("22")) {
                                    sequencemulti = x.getAttribute("sequence");
                                    found = true;
                                } else {
                                    searchparent = searchparent.getParentNode();
                                }
                            }
                        }

                        //Add contributors management
                        if (MID_parent.equals("11") || MID_parent.equals("13")) {
                            Node searchparent = iInnerNode;
                            boolean found = false;

                            while (!found) {
                                Element x = (Element) searchparent.getParentNode();
                                if (x.getAttribute("ID").equals("11")) {
                                    sequencemulti = x.getAttribute("sequence");
                                    found = true;
                                } else {
                                    searchparent = searchparent.getParentNode();
                                }
                            }
                        }

                        if (MID.equals("11")) {
                            Element x = (Element) iInnerNode;
                            sequencemulti = x.getAttribute("sequence");
                        }

                        String foxmlnamespace = iInnerNode.getAttribute("fornamespace");

                        if (!metadata_namespaces.containsValue(foxmlnamespace)) {
                            int count = metadata_namespaces.size();
                            count++;
                            metadata_namespaces.put("ns" + count, foxmlnamespace);
                        }

                        String description = null;
                        String DESCRIPTION_DE = null;

                        TreeMap<Object, Metadata> submetadatas = new TreeMap<Object, Metadata>();

                        NodeList innerList = iInnerNode.getChildNodes();
                        for (int z = 0; z < innerList.getLength(); z++) {
                            if (innerList.item(z).getNodeType() == Node.ELEMENT_NODE) {
                                Element iDescrNode = (Element) innerList.item(z);

                                if (iDescrNode.getAttribute("isocode").equals(sLang)) {
                                    description = iDescrNode.getTextContent();
                                } else if (iDescrNode.getAttribute("isocode").equals("de")) {
                                    DESCRIPTION_DE = iDescrNode.getTextContent();
                                }

                                if (iDescrNode.getTagName().equals("metadatas")) {
                                    if (MID.equals("98")) {
                                        metadata_reader_metadatas(iDescrNode, submetadatas, true, forceAddMID,
                                                sLang);
                                    } else {
                                        metadata_reader_metadatas(iDescrNode, submetadatas, false, forceAddMID,
                                                sLang);
                                    }
                                }
                            }
                        }

                        //Fallback DE
                        if (description == null) {
                            description = DESCRIPTION_DE;
                        }
                        if (description == null && !iInnerNode.getTagName().equals("metadata")) {
                            throw new Exception(
                                    "Can't find description for metadata " + iInnerNode.getTagName());
                        }

                        if ((mandatory.equals("Y") || forceAdd == true)) {
                            int mid_parent = 0;
                            if (!MID_parent.equals("")) {
                                mid_parent = Integer.parseInt(MID_parent);
                            }

                            Metadata t = new Metadata(Integer.parseInt(MID), mid_parent, description, datatype,
                                    editable, foxmlname, null, foxmlnamespace, mandatory, hidden,
                                    sequencemulti);
                            t.submetadatas = submetadatas;

                            String index = sequence;

                            if (index == null || index.equals("")) {
                                index = MID;
                            }
                            int param = Integer.parseInt(index);
                            metadatas.put(param, t);
                        }

                        if (forceAddMID.containsKey(MID.toString())) {
                            forceAdd = false;
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
}

From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java

private boolean makePage(Element element, String oldServer, String siteId, String fromSiteId,
        Map<Long, Long> pageMap, Map<Long, Long> itemMap, Map<String, String> entityMap) {

    String oldSiteId = element.getAttribute("siteid");
    String oldPageIdString = element.getAttribute("pageid");
    Long oldPageId = Long.valueOf(oldPageIdString);
    Long pageId = pageMap.get(oldPageId);
    Site site = null;/*from  w  w  w.  j  av  a2 s.  c o  m*/
    Collection<Group> siteGroups = null;
    boolean needFix = false;

    // not currently doing this
    if (RESTORE_GROUPS) {
        try {
            site = siteService.getSite(siteId);
            siteGroups = site.getGroups();
        } catch (Exception impossible) {
        }
        ;
    }

    NodeList allChildrenNodes = element.getChildNodes();
    int length = allChildrenNodes.getLength();
    for (int i = 0; i < length; i++) {

        Node node = allChildrenNodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {

            Element itemElement = (Element) node;
            if (itemElement.getTagName().equals("item")) {
                String s = itemElement.getAttribute("sequence");
                int sequence = new Integer(s);
                s = itemElement.getAttribute("type");
                int type = new Integer(s);
                String sakaiId = itemElement.getAttribute("sakaiid");
                String name = itemElement.getAttribute("name");
                String explanation = null;
                String sakaiTitle = itemElement.getAttribute("sakaititle");
                String id = itemElement.getAttribute("id");
                Long itemId = new Long(id);

                // URL is probably no longer used, but if it is, it probably doesn't need mapping
                if (type == SimplePageItem.RESOURCE || type == SimplePageItem.MULTIMEDIA) {
                    String prefix = "/group/" + oldSiteId + "/";
                    if (sakaiId.startsWith(prefix))
                        sakaiId = "/group/" + siteId + "/" + sakaiId.substring(prefix.length());
                    else
                        logger.error("sakaiId not recognized " + sakaiId);
                } else if (type == SimplePageItem.PAGE) {
                    // sakaiId should be the new page ID
                    Long newPageId = pageMap.get(Long.valueOf(sakaiId));
                    // we've seen a few cases where sakaiId of a subpage is 0. It won't be
                    // in the map, so this leaves it zero.
                    if (newPageId != null)
                        sakaiId = newPageId.toString();
                }

                if (type == SimplePageItem.ASSIGNMENT || type == SimplePageItem.ASSESSMENT
                        || type == SimplePageItem.FORUM) {
                    sakaiId = SimplePageItem.DUMMY;
                    needFix = true;
                }

                SimplePageItem item = simplePageToolDao.makeItem(pageId, sequence, type, sakaiId, name);

                if (explanation != null) {
                    item.setHtml(explanation);
                } else {
                    item.setHtml(itemElement.getAttribute("html"));
                }
                s = itemElement.getAttribute("description");
                if (s != null)
                    item.setDescription(s);
                s = itemElement.getAttribute("height");
                if (s != null)
                    item.setHeight(s);
                s = itemElement.getAttribute("width");
                if (s != null)
                    item.setWidth(s);
                s = itemElement.getAttribute("alt");
                if (s != null)
                    item.setAlt(s);
                s = itemElement.getAttribute("required");
                if (s != null)
                    item.setRequired(s.equals("true"));
                s = itemElement.getAttribute("prerequisite");
                if (s != null)
                    item.setPrerequisite(s.equals("true"));
                s = itemElement.getAttribute("subrequirement");
                if (s != null)
                    item.setSubrequirement(s.equals("true"));
                s = itemElement.getAttribute("requirementtext");
                if (s != null)
                    item.setRequirementText(s);
                s = itemElement.getAttribute("nextpage");
                if (s != null)
                    item.setNextPage(s.equals("true"));
                s = itemElement.getAttribute("format");
                if (s != null)
                    item.setFormat(s);
                s = itemElement.getAttribute("samewindow");
                if (s != null)
                    item.setSameWindow(s.equals("true"));
                s = itemElement.getAttribute("anonymous");
                if (s != null)
                    item.setAnonymous(s.equals("true"));
                s = itemElement.getAttribute("showComments");
                if (s != null)
                    item.setShowComments(s.equals("true"));
                s = itemElement.getAttribute("forcedCommentsAnonymous");
                if (s != null)
                    item.setForcedCommentsAnonymous(s.equals("true"));

                s = itemElement.getAttribute("gradebookTitle");
                if (s != null)
                    item.setGradebookTitle(s);
                s = itemElement.getAttribute("altGradebookTitle");
                if (s != null)
                    item.setAltGradebookTitle(s);

                s = itemElement.getAttribute("gradebookPoints");
                if (s != null && !s.equals("null"))
                    item.setGradebookPoints(Integer.valueOf(s));
                s = itemElement.getAttribute("altPoints");
                if (s != null && !s.equals("null"))
                    item.setAltPoints(Integer.valueOf(s));

                s = itemElement.getAttribute("groupOwned");
                if (s != null)
                    item.setGroupOwned(s.equals("true"));

                if (RESTORE_GROUPS) {
                    String groupString = mergeGroups(itemElement, "ownerGroup", siteGroups);
                    if (groupString != null)
                        item.setOwnerGroups(groupString);
                }

                // save objectid for dummy items so we can do mapping; alt isn't otherwise used for these items
                if (type == SimplePageItem.ASSIGNMENT || type == SimplePageItem.ASSESSMENT
                        || type == SimplePageItem.FORUM) {
                    item.setAlt(itemElement.getAttribute("objectid"));
                }

                // not currently doing this, although the code has been tested.
                // The problem is that other tools don't do it. Since much of our group
                // awareness comes from the other tools, enabling this produces
                // inconsistent results
                if (RESTORE_GROUPS) {
                    String groupString = mergeGroups(itemElement, "group", siteGroups);
                    if (groupString != null)
                        item.setGroups(groupString);
                }

                NodeList attributes = itemElement.getElementsByTagName("attributes");
                if (attributes != null && attributes.getLength() > 0) {
                    Node attributesNode = attributes.item(0); // only one
                    String attributeString = attributesNode.getTextContent();
                    item.setAttributeString(attributeString);
                }

                simplePageToolDao.quickSaveItem(item);
                itemMap.put(itemId, item.getId());

                boolean needupdate = false;

                // these need the item number, so do after save
                s = itemElement.getAttribute("gradebookId");
                if (s != null && !s.equals("null") && !s.equals("")) {
                    // update item number in both gradebook id and title
                    String title = item.getGradebookTitle();
                    if (title == null || title.equals("null") || title.equals("")) {
                        title = s;
                    }
                    // update gb id
                    int ii = s.lastIndexOf(":");
                    s = s.substring(0, ii + 1) + item.getId();
                    // update title
                    // can't do this, because Gradebook 2 will create items with the original name.
                    // the plan is to use user-defined names so we avoid this whole problem.
                    if (false) {
                        ii = title.lastIndexOf(":");
                        title = title.substring(0, ii + 1) + item.getId() + ")";
                    }

                    gradebookIfc.addExternalAssessment(siteId, s, null, title,
                            Double.valueOf(itemElement.getAttribute("gradebookPoints")), null,
                            "Lesson Builder");
                    needupdate = true;
                    item.setGradebookId(s);
                }

                s = itemElement.getAttribute("altGradebook");
                if (s != null && !s.equals("null") && !s.equals("")) {
                    // update item number in both gradebook id and title
                    String title = item.getAltGradebookTitle();
                    if (title == null || title.equals("null") || title.equals("")) {
                        title = s;
                    }
                    // update gb id
                    int ii = s.lastIndexOf(":");
                    s = s.substring(0, ii + 1) + item.getId();
                    // update title
                    // can't do this, because Gradebook 2 will create items with the original name.
                    // the plan is to use user-defined names so we avoid this whole problem.
                    if (false) {
                        ii = title.lastIndexOf(":");
                        title = title.substring(0, ii + 1) + item.getId() + ")";
                    }
                    gradebookIfc.addExternalAssessment(siteId, s, null, title,
                            Double.valueOf(itemElement.getAttribute("altPoints")), null, "Lesson Builder");
                    needupdate = true;
                    item.setAltGradebook(s);
                }

                // have to save again, I believe
                if (needupdate)
                    simplePageToolDao.quickUpdate(item);

                // these needs item id, so it has to be done here
                // save item ID to object id. This will allow references to be fixed up.
                // object id identifies the Sakai object in the old site. The fixup will
                // find the object in the new site and fix up the item. Hence we need
                // a mapping of item ID to object id.

                simplePageToolDao.syncQRTotals(item);

                if (type == SimplePageItem.ASSIGNMENT || type == SimplePageItem.ASSESSMENT
                        || type == SimplePageItem.FORUM) {
                    String objectid = itemElement.getAttribute("objectid");
                    if (objectid != null) {
                        String entityid = null;
                        if (type == SimplePageItem.ASSIGNMENT)
                            entityid = REF_LB_ASSIGNMENT + item.getId();
                        else if (type == SimplePageItem.ASSESSMENT)
                            entityid = REF_LB_ASSESSMENT + item.getId();
                        else
                            entityid = REF_LB_FORUM + item.getId();
                        if (entityMap != null)
                            entityMap.put(entityid, objectid);
                    }
                }

            }
        }
    }
    return needFix;
}

From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java

private int findParentPagetemplateKey(Document doc, int parentKey) throws TransformerException {
    int pagetemplatekey = -1;

    if (parentKey != -1) {
        Element rootNode = doc.getDocumentElement();
        Element currentElement = (Element) XMLTool.selectNode(rootNode, "//menuitem[@key = " + parentKey + "]");

        while (currentElement != null && currentElement.getTagName().equals("menuitem")) {
            String tmp = XMLTool.getElementText(currentElement, "page/@pagetemplatekey");
            if (tmp != null) {
                pagetemplatekey = Integer.parseInt(tmp);
                break;
            }/*from w w  w  . j  av  a 2  s.  com*/

            currentElement = (Element) XMLTool.selectNode(currentElement, "../../menuitem");
        }

        if (pagetemplatekey == -1) {
            String tmp = XMLTool.getElementText(doc, "/menus/menu/defaultpagetemplate/@pagetemplatekey");
            if (tmp != null) {
                pagetemplatekey = Integer.parseInt(tmp);
            }
        }
    }

    // attempt to set it to default pagetemplate
    if (pagetemplatekey == -1) {
        String tmp = XMLTool.getElementText(doc, "/menus/menu/defaultpagetemplate/@pagetemplatekey");
        if (tmp != null) {
            pagetemplatekey = Integer.parseInt(tmp);
        }
    }

    return pagetemplatekey;
}

From source file:com.aliyun.odps.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {//from w  w  w. j av  a 2 s .c o m
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        // ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        // allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        if (name instanceof URL) { // an URL resource
            URL url = (URL) name;
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) name);
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof InputStream) {
            try {
                doc = builder.parse((InputStream) name);
            } finally {
                ((InputStream) name).close();
            }
        } else if (name instanceof Element) {
            root = (Element) name;
        }

        if (doc == null && root == null) {
            if (quiet) {
                return;
            }
            throw new RuntimeException(name + " not found");
        }

        if (root == null) {
            root = doc.getDocumentElement();
        }
        if (!"configuration".equals(root.getTagName())) {
            LOG.fatal("bad conf file: top-level element not <configuration>");
        }
        NodeList props = root.getChildNodes();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element)) {
                continue;
            }
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(properties, prop, quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName())) {
                LOG.warn("bad conf file: element not <property>");
            }
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element)) {
                    continue;
                }
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes()) {
                    attr = ((Text) field.getFirstChild()).getData().trim();
                }
                if ("value".equals(field.getTagName()) && field.hasChildNodes()) {
                    value = ((Text) field.getFirstChild()).getData();
                }
                if ("final".equals(field.getTagName()) && field.hasChildNodes()) {
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
                }
            }

            // Ignore this parameter if it has already been marked as
            // 'final'
            if (attr != null && value != null) {
                if (!finalParameters.contains(attr)) {
                    properties.setProperty(attr, value);
                    if (finalParameter) {
                        finalParameters.add(attr);
                    }
                } else {
                    LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                }
            }
        }

    } catch (IOException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf file: " + e);
        throw new RuntimeException(e);
    }
}

From source file:com.netspective.sparx.util.xml.XmlSource.java

public void inheritNodes(Element element, Map sourcePool, String attrName, Set excludeElems) {
    String inheritAttr = element.getAttribute(attrName);
    while (inheritAttr != null && inheritAttr.length() > 0) {
        Element inheritFromElem = null;
        StringTokenizer inheritST = new StringTokenizer(inheritAttr, ",");
        String[] inherits = new String[15];
        int inheritsCount = 0;
        while (inheritST.hasMoreTokens()) {
            inherits[inheritsCount] = inheritST.nextToken();
            inheritsCount++;//from  w  w  w  . java 2s . co m
        }

        /** we're going to work backwards because we want to make sure the
         *  elements are added in the appropriate order (same order as the
         *  inheritance list)
         */

        for (int j = (inheritsCount - 1); j >= 0; j--) {
            String inheritType = inherits[j];
            inheritFromElem = (Element) sourcePool.get(inheritType);
            if (inheritFromElem == null) {
                errors.add("can not extend '" + element.getAttribute("name") + "' from '" + inheritType
                        + "': source not found");
                continue;
            }

            /* don't inherit the same objects more than once */
            String inheritanceId = Integer.toString(element.hashCode()) + '.'
                    + Integer.toString(inheritFromElem.hashCode());
            if (inheritanceHistorySet.contains(inheritanceId)) {
                errors.add("Attempting to copy duplicate node: " + inheritanceId + ", " + element.getTagName()
                        + ", " + element.getAttribute("name") + ", " + inheritFromElem.getTagName());
                //continue;
            }
            inheritanceHistorySet.add(inheritanceId);

            Element extendsElem = xmlDoc.createElement("extends");
            extendsElem.appendChild(xmlDoc.createTextNode(inheritType));
            element.appendChild(extendsElem);

            inheritElement(inheritFromElem, element, excludeElems, inheritType);
        }

        // find the next one if we have more parents
        if (inheritFromElem != null)
            inheritAttr = inheritFromElem.getAttribute(attrName);
        else
            inheritAttr = null;
    }
}

From source file:org.canova.api.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {// ww  w . j av a 2 s  .co  m
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        //ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        //allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        if (name instanceof URL) { // an URL resource
            URL url = (URL) name;
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) name);
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof InputStream) {
            try {
                doc = builder.parse((InputStream) name);
            } finally {
                ((InputStream) name).close();
            }
        } else if (name instanceof Element) {
            root = (Element) name;
        }

        if (doc == null && root == null) {
            if (quiet)
                return;
            throw new RuntimeException(name + " not found");
        }

        if (root == null) {
            root = doc.getDocumentElement();
        }
        if (!"configuration".equals(root.getTagName()))
            LOG.error("bad conf file: top-level element not <configuration>");
        NodeList props = root.getChildNodes();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element))
                continue;
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(properties, prop, quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes())
                    attr = ((Text) field.getFirstChild()).getData().trim();
                if ("value".equals(field.getTagName()) && field.hasChildNodes())
                    value = ((Text) field.getFirstChild()).getData();
                if ("final".equals(field.getTagName()) && field.hasChildNodes())
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
            }

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null && value != null) {
                if (!finalParameters.contains(attr)) {
                    properties.setProperty(attr, value);
                    if (storeResource) {
                        updatingResource.put(attr, name.toString());
                    }
                    if (finalParameter)
                        finalParameters.add(attr);
                } else {
                    LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                }
            }
        }

    } catch (IOException | ParserConfigurationException | SAXException | DOMException e) {
        LOG.error("error parsing conf file: " + e);
        throw new RuntimeException(e);
    }
}