Example usage for org.w3c.dom Document normalize

List of usage examples for org.w3c.dom Document normalize

Introduction

In this page you can find the example usage for org.w3c.dom Document normalize.

Prototype

public void normalize();

Source Link

Document

Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

Usage

From source file:org.chiba.xml.xforms.constraints.RelevanceSelectorTest.java

/**
 * Test case 1 for relevance selection of submitted instance data.
 *
 * @throws Exception if any error occurred during the test.
 *//*from w w  w  .  java2  s  . co  m*/
public void testSelectRelevant1() throws Exception {
    Instance instance = this.chibaBean.getContainer().getDefaultModel().getDefaultInstance();
    Document document = RelevanceSelector.selectRelevant(instance);
    document.normalize();
    JXPathContext context = JXPathContext.newContext(document);

    assertTrue("name(/*[1]) = 'root'", context.getValue("name(/*[1])").toString().equals("root"));
    assertTrue("/root/@xmlns = ''", context.getValue("/root/@xmlns").toString().equals(""));
    assertTrue("/root/@xmlns:test = 'http://test.org/ns'",
            context.getValue("/root/@xmlns:test").toString().equals("http://test.org/ns"));
    assertTrue("count(/root/*) = 3", context.getValue("count(/root/*)", Integer.class).toString().equals("3"));

    assertTrue("name(/root/*[1]) = 'name'", context.getValue("name(/root/*[1])").toString().equals("name"));
    assertTrue("/root/name/@id = 'n-1'", context.getValue("/root/name/@id").toString().equals("n-1"));
    assertTrue("count(/root/name/*) = 0",
            context.getValue("count(/root/name/*)", Integer.class).toString().equals("0"));

    assertTrue("name(/root/*[2]) = 'paragraph'",
            context.getValue("name(/root/*[2])").toString().equals("paragraph"));
    assertTrue("/root/paragraph[1]/@id = 'p-1'",
            context.getValue("/root/paragraph[1]/@id").toString().equals("p-1"));
    assertTrue("count(/root/paragraph[1]/*) = 1",
            context.getValue("count(/root/paragraph[1]/*)", Integer.class).toString().equals("1"));

    assertTrue("name(/root/paragraph[1]/*[1]) = 'content'",
            context.getValue("name(/root/paragraph[1]/*[1])").toString().equals("content"));
    assertTrue("/root/paragraph[1]/content/@id = 'c-1'",
            context.getValue("/root/paragraph[1]/content/@id").toString().equals("c-1"));
    assertTrue("/root/paragraph[1]/content/text()[1] = 'some mixed content 1'",
            context.getValue("/root/paragraph[1]/content/text()[1]").toString().equals("some mixed content 1"));
    assertTrue("/root/paragraph[1]/content/text()[2] = 'some more mixed content 1'", context
            .getValue("/root/paragraph[1]/content/text()[2]").toString().equals("some more mixed content 1"));
    assertTrue("count(/root/paragraph[1]/content/*) = 1",
            context.getValue("count(/root/paragraph[1]/content/*)", Integer.class).toString().equals("1"));

    assertTrue("name(/root/paragraph[1]/content/*[1]) = 'input'",
            context.getValue("name(/root/paragraph[1]/content/*[1])").toString().equals("input"));
    assertTrue("/root/paragraph[1]/content/input/@id = 'i-1'",
            context.getValue("/root/paragraph[1]/content/input/@id").toString().equals("i-1"));
    assertTrue("/root/paragraph[1]/content/input/text()[1] = 'input 1'",
            context.getValue("/root/paragraph[1]/content/input/text()[1]").toString().equals("input 1"));
    assertTrue("count(/root/paragraph[1]/content/input/*) = 0", context
            .getValue("count(/root/paragraph[1]/content/input/*)", Integer.class).toString().equals("0"));

    assertTrue("name(/root/*[3]) = 'paragraph'",
            context.getValue("name(/root/*[3])").toString().equals("paragraph"));
    assertTrue("/root/paragraph[2]/@id = 'p-2'",
            context.getValue("/root/paragraph[2]/@id").toString().equals("p-2"));
    assertTrue("count(/root/paragraph[2]/*) = 1",
            context.getValue("count(/root/paragraph[2]/*)", Integer.class).toString().equals("1"));

    assertTrue("name(/root/paragraph[2]/*[1]) = 'content'",
            context.getValue("name(/root/paragraph[2]/*[1])").toString().equals("content"));
    assertTrue("/root/paragraph[2]/content/@id = 'c-2'",
            context.getValue("/root/paragraph[2]/content/@id").toString().equals("c-2"));
    assertTrue("/root/paragraph[2]/content/text()[1] = 'some mixed content 2'",
            context.getValue("/root/paragraph[2]/content/text()[1]").toString().equals("some mixed content 2"));
    assertTrue("/root/paragraph[2]/content/text()[2] = 'some more mixed content 2'", context
            .getValue("/root/paragraph[2]/content/text()[2]").toString().equals("some more mixed content 2"));
    assertTrue("count(/root/paragraph[2]/content/*) = 1",
            context.getValue("count(/root/paragraph[2]/content/*)", Integer.class).toString().equals("1"));

    assertTrue("name(/root/paragraph[2]/content/*[1]) = 'input'",
            context.getValue("name(/root/paragraph[2]/content/*[1])").toString().equals("input"));
    assertTrue("/root/paragraph[2]/content/input/@id = 'i-2'",
            context.getValue("/root/paragraph[2]/content/input/@id").toString().equals("i-2"));
    assertTrue("/root/paragraph[2]/content/input/text()[1] = 'input 2'",
            context.getValue("/root/paragraph[2]/content/input/text()[1]").toString().equals("input 2"));
    assertTrue("count(/root/paragraph[2]/content/input/*) = 0", context
            .getValue("count(/root/paragraph[2]/content/input/*)", Integer.class).toString().equals("0"));
}

From source file:org.chiba.xml.xforms.constraints.RelevanceSelectorTest.java

/**
 * Test case 2 for relevance selection of submitted instance data.
 *
 * @throws Exception if any error occurred during the test.
 *///  w w  w . j a  v  a 2 s . c om
public void testSelectRelevant2() throws Exception {
    Instance instance = this.chibaBean.getContainer().getDefaultModel().getDefaultInstance();
    Document document = RelevanceSelector.selectRelevant(instance, "/root/paragraph");
    document.normalize();
    JXPathContext context = JXPathContext.newContext(document);

    assertTrue("name(/*[1]) = 'paragraph'", context.getValue("name(/*[1])").toString().equals("paragraph"));
    assertTrue("/paragraph/@xmlns = ''", context.getValue("/paragraph/@xmlns").toString().equals(""));
    assertTrue("/paragraph/@xmlns:test = 'http://test.org/ns'",
            context.getValue("/paragraph/@xmlns:test").toString().equals("http://test.org/ns"));
    assertTrue("/paragraph/@id = 'p-1'", context.getValue("/paragraph/@id").toString().equals("p-1"));
    assertTrue("count(/paragraph/*) = 1",
            context.getValue("count(/paragraph/*)", Integer.class).toString().equals("1"));

    assertTrue("name(/paragraph/*[1]) = 'content'",
            context.getValue("name(/paragraph/*[1])").toString().equals("content"));
    assertTrue("/paragraph/content/@id = 'c-1'",
            context.getValue("/paragraph/content/@id").toString().equals("c-1"));
    assertTrue("/paragraph/content/text()[1] = 'some mixed content 1'",
            context.getValue("/paragraph/content/text()[1]").toString().equals("some mixed content 1"));
    assertTrue("/paragraph/content/text()[2] = 'some more mixed content 1'",
            context.getValue("/paragraph/content/text()[2]").toString().equals("some more mixed content 1"));
    assertTrue("count(/paragraph/content/*) = 1",
            context.getValue("count(/paragraph/content/*)", Integer.class).toString().equals("1"));

    assertTrue("name(/paragraph/content/*[1]) = 'input'",
            context.getValue("name(/paragraph/content/*[1])").toString().equals("input"));
    assertTrue("/paragraph/content/input/@id = 'i-1'",
            context.getValue("/paragraph/content/input/@id").toString().equals("i-1"));
    assertTrue("/paragraph/content/input/text()[1] = 'input 1'",
            context.getValue("/paragraph/content/input/text()[1]").toString().equals("input 1"));
    assertTrue("count(/paragraph/content/input/*) = 0",
            context.getValue("count(/paragraph/content/input/*)", Integer.class).toString().equals("0"));
}

From source file:org.dita.dost.module.AbstractModuleTest.java

private Document getDocument(final File file) {
    try {//from w  w w . j  a  v  a 2s .c o  m
        final Document doc = builder.parse(file);
        doc.normalize();
        normalizeSpace(doc.getDocumentElement());
        return doc;
    } catch (SAXException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.recommenders.jayes.io.XDSLReader.java

private Document obtainDocument(InputStream xdslStream) throws IOException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    try {//w  w w  .  ja v a2  s . c  o  m
        DocumentBuilder docBldr = docBuilderFactory.newDocumentBuilder();
        Document doc = docBldr.parse(xdslStream);

        doc.normalize();
        return doc;
    } catch (ParserConfigurationException e) {
        throw new IOException("Bad parser configuration, probably missing dependency", e);
    } catch (SAXException e) {
        throw new IOException("Parse failed", e);
    }

}

From source file:org.eclipse.recommenders.jayes.io.XMLBIFReader.java

private Document obtainDocument(InputStream biffile)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setValidating(true);
    DocumentBuilder docBldr = docBuilderFactory.newDocumentBuilder();

    Document doc = docBldr.parse(biffile);
    doc.normalize();

    return doc;//from   ww w .j  ava  2s  .  c  om
}

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

@Override
@SuppressWarnings("unchecked")
@Transactional/*  ww  w . ja  v  a2 s .  c  o m*/
public void importLayout(org.dom4j.Element layout) {
    if (layout.getNamespaceForPrefix("dlm") == null) {
        layout.add(new Namespace("dlm", "http://www.uportal.org/layout/dlm"));
    }

    //Remove comments from the DOM they break import
    final List<org.dom4j.Node> comments = layout.selectNodes("//comment()");
    for (final org.dom4j.Node comment : comments) {
        comment.detach();
    }

    //Get a ref to the prefs element and then remove it from the layout
    final org.dom4j.Node preferencesElement = layout.selectSingleNode("preferences");
    if (preferencesElement != null) {
        preferencesElement.getParent().remove(preferencesElement);
    }

    final String ownerUsername = layout.valueOf("@username");

    //Get a ref to the profile element and then remove it from the layout
    final org.dom4j.Node profileElement = layout.selectSingleNode("profile");
    if (profileElement != null) {
        profileElement.getParent().remove(profileElement);

        final org.dom4j.Document profileDocument = new org.dom4j.DocumentFactory().createDocument();
        profileDocument.setRootElement((org.dom4j.Element) profileElement);
        profileDocument.setName(ownerUsername + ".profile");

        final DocumentSource profileSource = new DocumentSource(profileElement);
        this.portalDataHandlerService.importData(profileSource);
    }

    final IPerson person = new PersonImpl();
    person.setUserName(ownerUsername);

    int ownerId;
    try {
        //Can't just pass true for create here, if the user actually exists the create flag also updates the user data
        ownerId = this.userIdentityStore.getPortalUID(person);
    } catch (final AuthorizationException t) {
        if (this.errorOnMissingUser) {
            throw new RuntimeException("Unrecognized user " + person.getUserName()
                    + "; you must import users before their layouts or set org.jasig.portal.io.layout.errorOnMissingUser to false.",
                    t);
        }

        //Create the missing user
        ownerId = this.userIdentityStore.getPortalUID(person, true);
    }

    if (ownerId == -1) {
        throw new RuntimeException("Unrecognized user " + person.getUserName()
                + "; you must import users before their layouts or set org.jasig.portal.io.layout.errorOnMissingUser to false.");
    }
    person.setID(ownerId);

    IUserProfile profile = null;
    try {
        person.setSecurityContext(new BrokenSecurityContext());
        profile = this.getUserProfileByFname(person, "default");
    } catch (final Throwable t) {
        throw new RuntimeException("Failed to load profile for " + person.getUserName()
                + "; This user must have a profile for import to continue.", t);
    }

    // (6) Add database Ids & (5) Add dlm:plfID ...
    int nextId = 1;
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout
            .selectNodes("folder | dlm:* | channel").iterator(); it.hasNext();) {
        nextId = this.addIdAttributesIfNecessary(it.next(), nextId);
    }
    // Now update UP_USER...
    this.jdbcOperations.update("UPDATE up_user SET next_struct_id = ? WHERE user_id = ?", nextId,
            person.getID());

    // (4) Convert external DLM pathrefs to internal form (noderefs)...
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//@dlm:origin").iterator(); itr.hasNext();) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null,
                true, layout);
        if (dlmNoderef != null) {
            // Change the value only if we have a valid pathref...
            a.setValue(dlmNoderef.toString());
            // For dlm:origin only, also use the noderef as the ID attribute...
            a.getParent().addAttribute("ID", dlmNoderef.toString());
        } else {
            // At least insure the value is between 1 and 35 characters
            a.setValue(BAD_PATHREF_MESSAGE);
        }
    }
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//@dlm:target").iterator(); itr.hasNext();) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null,
                true, layout);
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) {
        final org.dom4j.Attribute a = names.next();
        final String value = a.getValue().trim();
        if (!VALID_PATHREF_PATTERN.matcher(value).matches()) {
            /* Don't send it to getDlmNoderef if we know in advance it's not 
             * going to work;  saves annoying/misleading log messages and 
             * possibly some processing.  NOTE this is _only_ a problem with 
             * the name attribute of some dlm:* elements, which seems to go 
             * unused intentionally in some circumstances
             */
            continue;
        }
        final org.dom4j.Attribute fname = a.getParent().attribute("fname");
        Noderef dlmNoderef = null;
        if (fname != null) {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, fname.getValue(),
                    false, layout);
            // Remove the fname attribute now that we're done w/ it...
            fname.getParent().remove(fname);
        } else {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, null, true, layout);
        }
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }

    // (3) Restore chanID attributes on <channel> elements...
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("//channel")
            .iterator(); it.hasNext();) {
        final org.dom4j.Element c = it.next();
        final String fname = c.valueOf("@fname");
        final IPortletDefinition cd = this.portletDefinitionRegistry.getPortletDefinitionByFname(fname);
        if (cd == null) {
            final String msg = "No portlet with fname=" + fname + " exists referenced by node "
                    + c.valueOf("@ID") + " from layout for " + ownerUsername;
            if (errorOnMissingPortlet) {
                throw new IllegalArgumentException(msg);
            } else {
                log.warn(msg);
                //Remove the bad channel node
                c.getParent().remove(c);
            }
        } else {
            c.addAttribute("chanID", String.valueOf(cd.getPortletDefinitionId().getStringId()));
        }
    }

    // (2) Restore locale info...
    // (This step doesn't appear to be needed for imports)

    // (1) Process structure & theme attributes...
    Document layoutDom = null;
    try {

        final int structureStylesheetId = profile.getStructureStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, structureStylesheetId,
                "structure");

        final int themeStylesheetId = profile.getThemeStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, themeStylesheetId, "theme");

        // From this point forward we need the user's PLF set as DLM expects it...
        for (final Iterator<org.dom4j.Text> it = (Iterator<org.dom4j.Text>) layout
                .selectNodes("descendant::text()").iterator(); it.hasNext();) {
            // How many years have we used Java & XML, and this still isn't easy?
            final org.dom4j.Text txt = it.next();
            if (txt.getText().trim().length() == 0) {
                txt.getParent().remove(txt);
            }
        }

        final org.dom4j.Element copy = layout.createCopy();
        final org.dom4j.Document doc = this.fac.createDocument(copy);
        doc.normalize();
        layoutDom = this.writer.get().write(doc);
        person.setAttribute(Constants.PLF, layoutDom);

    } catch (final Throwable t) {
        throw new RuntimeException("Unable to set UserPreferences for user:  " + person.getUserName(), t);
    }

    // Finally store the layout...
    try {
        this.setUserLayout(person, profile, layoutDom, true, true);
    } catch (final Throwable t) {
        final String msg = "Unable to persist layout for user:  " + ownerUsername;
        throw new RuntimeException(msg, t);
    }

    if (preferencesElement != null) {
        final int ownerUserId = this.userIdentityStore.getPortalUserId(ownerUsername);
        //TODO this assumes a single layout, when multi-layout support exists portlet entities will need to be re-worked to allow for a layout id to be associated with the entity

        //track which entities from the user's pre-existing set are touched (all non-touched entities will be removed)
        final Set<IPortletEntity> oldPortletEntities = new LinkedHashSet<IPortletEntity>(
                this.portletEntityDao.getPortletEntitiesForUser(ownerUserId));

        final List<org.dom4j.Element> entries = preferencesElement.selectNodes("entry");
        for (final org.dom4j.Element entry : entries) {
            final String dlmPathRef = entry.attributeValue("entity");
            final String fname = entry.attributeValue("channel");
            final String prefName = entry.attributeValue("name");

            final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(person.getUserName(),
                    dlmPathRef, fname, false, layout);

            if (dlmNoderef != null && !"".equals(dlmNoderef) && fname != null && !"null".equals(fname)) {
                final IPortletEntity portletEntity = this.getPortletEntity(fname, dlmNoderef.toString(),
                        ownerUserId);
                oldPortletEntities.remove(portletEntity);

                final List<IPortletPreference> portletPreferences = portletEntity.getPortletPreferences();

                final List<org.dom4j.Element> valueElements = entry.selectNodes("value");
                final List<String> values = new ArrayList<String>(valueElements.size());
                for (final org.dom4j.Element valueElement : valueElements) {
                    values.add(valueElement.getText());
                }

                portletPreferences.add(
                        new PortletPreferenceImpl(prefName, false, values.toArray(new String[values.size()])));

                this.portletEntityDao.updatePortletEntity(portletEntity);
            }
        }

        //Delete all portlet preferences for entities that were not imported
        for (final IPortletEntity portletEntity : oldPortletEntities) {
            portletEntity.setPortletPreferences(null);

            if (portletEntityRegistry.shouldBePersisted(portletEntity)) {
                this.portletEntityDao.updatePortletEntity(portletEntity);
            } else {
                this.portletEntityDao.deletePortletEntity(portletEntity);
            }
        }
    }
}

From source file:org.kuali.rice.kns.workflow.attribute.KualiXmlAttributeHelper.java

/**
 * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
 * where the super class expects to see them, overwriting the original title in the XML.
 *
 * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
 *///  www.  ja  v a 2  s . c o  m

public Element processConfigXML(Element root, String[] xpathExpressionElements) {

    NodeList fields = root.getElementsByTagName("fieldDef");
    Element theTag = null;
    String docContent = "";

    /**
     * This section will check to see if document content has been defined in the configXML for the document type, by running an
     * XPath. If this is an empty list the xpath expression in the fieldDef is used to define the xml document content that is
     * added to the configXML. The xmldocument content is of this form, when in the document configXML. <xmlDocumentContent>
     * <org.kuali.rice.krad.bo.SourceAccountingLine> <amount> <value>%totaldollarAmount%</value> </amount>
     * </org.kuali.rice.krad.bo.SourceAccountingLine> </xmlDocumentContent> This class generates this on the fly, by creating an XML
     * element for each term in the XPath expression. When this doesn't apply XML can be coded in the configXML for the
     * ruleAttribute.
     *
     * @see org.kuali.rice.kew.plugin.attributes.WorkflowAttribute#getDocContent()
     */

    org.w3c.dom.Document xmlDoc = null;
    if (!xmlDocumentContentExists(root)) { // XML Document content is given because the xpath is non standard
        fields = root.getElementsByTagName("fieldDef");
        xmlDoc = root.getOwnerDocument();
    }
    for (int i = 0; i < fields.getLength(); i++) { // loop over each fieldDef
        String name = null;
        if (!xmlDocumentContentExists(root)) {
            theTag = (Element) fields.item(i);

            /*
             * Even though there may be multiple xpath test, for example one for source lines and one for target lines, the
             * xmlDocumentContent only needs one, since it is used for formatting. The first one is arbitrarily selected, since
             * they are virtually equivalent in structure, most of the time.
             */

            List<String> xPathTerms = getXPathTerms(theTag);
            if (xPathTerms.size() != 0) {
                Node iterNode = xmlDoc.createElement("xmlDocumentContent");

                xmlDoc.normalize();

                iterNode.normalize();

                /*
                 * Since this method is run once per attribute and there may be multiple fieldDefs, the first fieldDef is used
                 * to create the configXML.
                 */
                for (int j = 0; j < xPathTerms.size(); j++) {// build the configXML based on the Xpath
                    // TODO - Fix the document content element generation
                    iterNode.appendChild(xmlDoc.createElement(xPathTerms.get(j)));
                    xmlDoc.normalize();

                    iterNode = iterNode.getFirstChild();
                    iterNode.normalize();

                }
                iterNode.setTextContent("%" + xPathTerms.get(xPathTerms.size() - 1) + "%");
                root.appendChild(iterNode);
            }
        }
        theTag = (Element) fields.item(i);
        // check to see if a values finder is being used to set valid values for a field
        NodeList displayTagElements = theTag.getElementsByTagName("display");
        if (displayTagElements.getLength() == 1) {
            Element displayTag = (Element) displayTagElements.item(0);
            List valuesElementsToAdd = new ArrayList();
            for (int w = 0; w < displayTag.getChildNodes().getLength(); w++) {
                Node displayTagChildNode = (Node) displayTag.getChildNodes().item(w);
                if ((displayTagChildNode != null) && ("values".equals(displayTagChildNode.getNodeName()))) {
                    if (displayTagChildNode.getChildNodes().getLength() > 0) {
                        String valuesNodeText = displayTagChildNode.getFirstChild().getNodeValue();
                        String potentialClassName = getPotentialKualiClassName(valuesNodeText,
                                KUALI_VALUES_FINDER_REFERENCE_PREFIX, KUALI_VALUES_FINDER_REFERENCE_SUFFIX);
                        if (StringUtils.isNotBlank(potentialClassName)) {
                            try {
                                Class finderClass = Class.forName((String) potentialClassName);
                                KeyValuesFinder finder = (KeyValuesFinder) finderClass.newInstance();
                                NamedNodeMap valuesNodeAttributes = displayTagChildNode.getAttributes();
                                Node potentialSelectedAttribute = (valuesNodeAttributes != null)
                                        ? valuesNodeAttributes.getNamedItem("selected")
                                        : null;
                                for (Iterator iter = finder.getKeyValues().iterator(); iter.hasNext();) {
                                    KeyValue keyValue = (KeyValue) iter.next();
                                    Element newValuesElement = root.getOwnerDocument().createElement("values");
                                    newValuesElement.appendChild(
                                            root.getOwnerDocument().createTextNode(keyValue.getKey()));
                                    // newValuesElement.setNodeValue(KeyValue.getKey().toString());
                                    newValuesElement.setAttribute("title", keyValue.getValue());
                                    if (potentialSelectedAttribute != null) {
                                        newValuesElement.setAttribute("selected",
                                                potentialSelectedAttribute.getNodeValue());
                                    }
                                    valuesElementsToAdd.add(newValuesElement);
                                }
                            } catch (ClassNotFoundException cnfe) {
                                String errorMessage = "Caught an exception trying to find class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, cnfe);
                                throw new RuntimeException(errorMessage, cnfe);
                            } catch (InstantiationException ie) {
                                String errorMessage = "Caught an exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, ie);
                                throw new RuntimeException(errorMessage, ie);
                            } catch (IllegalAccessException iae) {
                                String errorMessage = "Caught an access exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, iae);
                                throw new RuntimeException(errorMessage, iae);
                            }
                        } else {
                            valuesElementsToAdd.add(displayTagChildNode.cloneNode(true));
                        }
                        displayTag.removeChild(displayTagChildNode);
                    }
                }
            }
            for (Iterator iter = valuesElementsToAdd.iterator(); iter.hasNext();) {
                Element valuesElementToAdd = (Element) iter.next();
                displayTag.appendChild(valuesElementToAdd);
            }
        }
        if ((xpathExpressionElements != null) && (xpathExpressionElements.length > 0)) {
            NodeList fieldEvaluationElements = theTag.getElementsByTagName("fieldEvaluation");
            if (fieldEvaluationElements.getLength() == 1) {
                Element fieldEvaluationTag = (Element) fieldEvaluationElements.item(0);
                List tagsToAdd = new ArrayList();
                for (int w = 0; w < fieldEvaluationTag.getChildNodes().getLength(); w++) {
                    Node fieldEvaluationChildNode = (Node) fieldEvaluationTag.getChildNodes().item(w);
                    Element newTagToAdd = null;
                    if ((fieldEvaluationChildNode != null)
                            && ("xpathexpression".equals(fieldEvaluationChildNode.getNodeName()))) {
                        newTagToAdd = root.getOwnerDocument().createElement("xpathexpression");
                        newTagToAdd.appendChild(root.getOwnerDocument()
                                .createTextNode(generateNewXpathExpression(
                                        fieldEvaluationChildNode.getFirstChild().getNodeValue(),
                                        xpathExpressionElements)));
                        tagsToAdd.add(newTagToAdd);
                        fieldEvaluationTag.removeChild(fieldEvaluationChildNode);
                    }
                }
                for (Iterator iter = tagsToAdd.iterator(); iter.hasNext();) {
                    Element elementToAdd = (Element) iter.next();
                    fieldEvaluationTag.appendChild(elementToAdd);
                }
            }
        }
        theTag.setAttribute("title", getBusinessObjectTitle(theTag));

    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(XmlJotter.jotNode(root));
        StringWriter xmlBuffer = new StringWriter();
        try {

            root.normalize();
            Source source = new DOMSource(root);
            Result result = new StreamResult(xmlBuffer);
            TransformerFactory.newInstance().newTransformer().transform(source, result);
        } catch (Exception e) {
            LOG.debug(" Exception when printing debug XML output " + e);
        }
        LOG.debug(xmlBuffer.getBuffer());
    }

    return root;
}

From source file:org.rippleosi.common.service.AbstractSCCISService.java

protected <T> T findData(String patientId, Transformer transformer) {

    ResponseEntity<String> response;

    response = queryByHttpGet(patientId);

    Document xml = null;
    if (response.getStatusCode() == HttpStatus.OK) {

        try {/*w  w w  .j a  v  a 2 s  .  co m*/
            xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new InputSource(new StringReader(response.getBody())));
            xml.normalize();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        transformer.transform(xml);

    }

    return (T) transformer.transform(xml);
}

From source file:us.derfers.tribex.rapids.Loader.java

/**
 * Starts loading the GUI. Sets Swing look and feel, then loads the GUI using the GUI_Swing object.
 * @param escapedFile The content .rsm file to load UI elements from.
 * @param parent The (optional) parent Object, Eg, a JFrame or JPanel.
 * @param engine The JavaScript engine to pass to GUI_Swing
 *///from   w  w w. j  a v  a  2  s  . co m
public void loadAll(String escapedFile) {

    //Attempt to load .rsm file filePath
    try {

        //Parse filePath
        Document doc = Utilities.XMLStringToDocument(escapedFile);

        //Stabilize parsed document
        doc.normalize();

        //Get body element
        NodeList mainNodeList = doc.getElementsByTagName("rsm");

        //Make sure there is only ONE body element
        if (mainNodeList.getLength() == 1) {
            debugMsg("Parsing Main Element", 4);
            //Get rsm Element
            Element mainElement = (Element) mainNodeList.item(0);

            debugMsg("Setting Theme", 4);
            //If the mainElement has the attribute "theme"
            if (mainElement.getAttributeNode("theme") != null) {
                //Get the value of the attribute theme for the body element
                Attr swing_Theme = mainElement.getAttributeNode("theme");

                //See if the rsm file specifies a theme other than camo
                if (swing_Theme != null && !swing_Theme.getNodeValue().equalsIgnoreCase("camo")) {
                    try {
                        //Split the theme into the jarfile and the classname (JARFILE.jar : com.stuff.stuff.theme)
                        String[] splitTheme = swing_Theme.getNodeValue().split(":");

                        System.out.println(splitTheme[0].trim() + "**" + splitTheme[1].trim());
                        //Attempt to dynamically load the specified jarfile
                        Sys.addJarToClasspath(Globals.getCWD(splitTheme[0].trim()));

                        //Attempt to set the look'n'feel to the theme specified by the file
                        UIManager.setLookAndFeel(splitTheme[1].trim());

                        debugMsg("Look and Feel set to '" + swing_Theme.getNodeValue() + "'.", 3);

                    } catch (Exception e) {
                        //If unable to set to .rsm's theme, use the system look'n'feel
                        try {
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                        } catch (Exception a) {
                            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                        }
                        Utilities.showError(
                                "Error loading Look and Feel Specified, Look and Feel set to System");
                        e.printStackTrace();

                    }
                } else {
                    //If swing_Theme == camo or is not set, use the system look'n'feel
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception a) {
                        a.printStackTrace();
                        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                    }
                    debugMsg("Look and Feel (Swing) set to System", 3);
                }
            } else {
                //If swing_Theme == camo or is not set, use the system look'n'feel
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception a) {
                    a.printStackTrace();
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                }
                debugMsg("Look and Feel (Swing) set to System", 3);

            }

            //Parse styles
            for (int i = 0; i < mainElement.getElementsByTagName("style").getLength(); i++) {
                Element styleElement = (Element) mainElement.getElementsByTagName("style").item(i);
                //Load all styles from the style tags
                if (styleElement.getAttributeNode("href") != null) {
                    loadStyles(null, styleElement.getTextContent());
                } else {
                    loadStyles(styleElement.getTextContent(), null);

                }
            }

            //Parse links
            for (int i = 0; i < mainElement.getElementsByTagName("link").getLength(); i++) {
                Element linkElement = (Element) mainElement.getElementsByTagName("link").item(i);
                parseLinks(linkElement, engine);
            }

            //Parse JavaScript in <script> tags
            Main.loader.loadJS(escapedFile, engine);

            //Parse GUI
            for (int i = 0; i < mainElement.getElementsByTagName("window").getLength(); i++) {
                GUI.loadWindow((Element) mainElement.getElementsByTagName("window").item(i), engine);
            }

        } else { //There was more than one body tag, or 0 body tags

            //Display Error and quit, as we cannot recover from an abnormally formatted file
            Utilities.showError("Error: More or less than one <rsm> tag in '" + escapedFile + "'.\n\n"
                    + "Please add ONE <rsm> tag to '" + escapedFile + "'.");
            System.exit(1);
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

}

From source file:us.derfers.tribex.rapids.Loader.java

/**
 * Discovers any script tags in the document and sends them to JSIterator to be parsed.
 * @param escapedFile The escaped file containing script(s) to run.
 * @param engine the JavaScript engine to load the script tags into.
 * @return Boolean telling whether or not it completed
 *//*from w ww.  ja  v  a  2 s  .  c o  m*/
public boolean loadJS(String escapedFile, ScriptEngine engine) {
    Utilities.debugMsg("Loading JavaScript from <script> tags.");
    //XXX: JAVASCRIPT HANDLING SECTION :XXX\\
    try {
        //Parse filePath
        Document doc = Utilities.XMLStringToDocument(escapedFile);

        //Stabilize parsed document
        doc.normalize();
        //Execute anything in script tags. JavaScript
        //Load all <script> tags

        NodeList scriptNodes = doc.getElementsByTagName("script");

        JSIterator(scriptNodes, engine);

        return true;
        //XXX: END JAVASCRIPT HANDLING :XXX\\
    } catch (Exception e) {
        e.printStackTrace();
        Utilities.showError(
                "Error loading Javascripts from '" + escapedFile + "'. Please check their validity.");
        return false;
    }
}