Example usage for org.w3c.dom Element getNodeName

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

Introduction

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

Prototype

public String getNodeName();

Source Link

Document

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

Usage

From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java

public IUserLayoutNodeDescription createNodeDescription(Element node) throws PortalException {
    String type = node.getNodeName();
    if (type.equals(Constants.ELM_CHANNEL)) {
        return new ChannelDescription(node);
    } else if (type.equals(Constants.ELM_FOLDER)) {
        return new UserLayoutFolderDescription(node);
    } else {/*from   ww  w .j  a  v  a2 s  . c  o  m*/
        throw new PortalException("Given XML Element is not a channel!");
    }
}

From source file:org.apereo.portal.layout.dlm.EditManager.java

/**
   Create and append an edit directive to the edit set if not there.
*//*from w w  w. ja  v  a2s.c o m*/
private static void addDirective(Element plfNode, String attributeName, String type, IPerson person)
        throws PortalException {
    Document plf = (Document) person.getAttribute(Constants.PLF);
    Element editSet = getEditSet(plfNode, plf, person, true);

    // see if attributes has already been marked as being edited
    Element child = (Element) editSet.getFirstChild();
    Element edit = null;

    while (child != null && edit == null) {
        if (child.getNodeName().equals(type) && child.getAttribute(Constants.ATT_NAME).equals(attributeName))
            edit = child;
        child = (Element) child.getNextSibling();
    }
    if (edit == null) // if not found then newly mark as edited
    {
        String ID = null;

        try {
            ID = getDLS().getNextStructDirectiveId(person);
        } catch (Exception e) {
            throw new PortalException("Exception encountered while " + "generating new edit node "
                    + "Id for userId=" + person.getID(), e);
        }
        edit = plf.createElement(type);
        edit.setAttribute(Constants.ATT_TYPE, type);
        edit.setAttribute(Constants.ATT_ID, ID);
        edit.setAttribute(Constants.ATT_NAME, attributeName);
        editSet.appendChild(edit);
    }
}

From source file:org.apereo.portal.layout.dlm.EditManager.java

/**
   Evaluate whether attribute changes exist in the ilfChild and if so
   apply them. Returns true if some changes existed. If changes existed
   but matched those in the original node then they are not applicable,
   are removed from the editSet, and false is returned.
*//*from www .  ja v  a  2s .c  om*/
public static boolean applyEditSet(Element plfChild, Element original) {
    // first get edit set if it exists
    Element editSet = null;
    try {
        editSet = getEditSet(plfChild, null, null, false);
    } catch (Exception e) {
        // should never occur unless problem during create in getEditSet
        // and we are telling it not to create.
        return false;
    }

    if (editSet == null || editSet.getChildNodes().getLength() == 0)
        return false;

    if (original.getAttribute(Constants.ATT_EDIT_ALLOWED).equals("false")) {
        // can't change anymore so discard changes
        plfChild.removeChild(editSet);
        return false;
    }

    Document ilf = original.getOwnerDocument();
    boolean attributeChanged = false;
    Element edit = (Element) editSet.getFirstChild();

    while (edit != null) {
        String attribName = edit.getAttribute(Constants.ATT_NAME);
        Attr attr = plfChild.getAttributeNode(attribName);

        // preferences are only updated at preference storage time so
        // if a preference change exists in the edit set assume it is
        // still valid so that the node being edited will persist in
        // the PLF.
        if (edit.getNodeName().equals(Constants.ELM_PREF))
            attributeChanged = true;
        else if (attr == null) {
            // attribute removed. See if needs removing in original.
            attr = original.getAttributeNode(attribName);
            if (attr == null) // edit irrelevant,
                editSet.removeChild(edit);
            else {
                // edit differs, apply to original
                original.removeAttribute(attribName);
                attributeChanged = true;
            }
        } else {
            // attribute there, see if original is also there
            Attr origAttr = original.getAttributeNode(attribName);
            if (origAttr == null) {
                // original attribute isn't defined so need to add
                origAttr = (Attr) ilf.importNode(attr, true);
                original.setAttributeNode(origAttr);
                attributeChanged = true;
            } else {
                // original attrib found, see if different
                if (attr.getValue().equals(origAttr.getValue())) {
                    // they are the same, edit irrelevant
                    editSet.removeChild(edit);
                } else {
                    // edit differs, apply to original
                    origAttr.setValue(attr.getValue());
                    attributeChanged = true;
                }
            }
        }
        edit = (Element) edit.getNextSibling();
    }
    return attributeChanged;
}

From source file:org.apereo.portal.layout.dlm.PLFIntegrator.java

private static void applyChildChanges(Element plfParent, Element ilfParent, IntegrationResult result,
        NodeInfoTracker tracker) throws PortalException {

    Element positions = null;// w ww .  ja  v a 2  s  . c om
    Element node = (Element) plfParent.getFirstChild();

    while (node != null) {
        Element nextNode = (Element) node.getNextSibling();

        if (node.getNodeName().equals("folder"))
            mergeFolder(node, plfParent, ilfParent, result, tracker);
        else if (node.getNodeName().equals(Constants.ELM_POSITION_SET))
            positions = node;
        else if (node.getNodeName().equals("channel"))
            mergeChannel(node, plfParent, ilfParent, result, tracker);
        node = nextNode;
    }

    if (positions != null) {
        IntegrationResult posResult = new IntegrationResult();
        if (LOG.isInfoEnabled())
            LOG.info("applying positions");
        PositionManager.applyPositions(ilfParent, positions, posResult, tracker);
        if (!posResult.isChangedILF()) {
            if (LOG.isInfoEnabled())
                LOG.info("removing positionSet");
            plfParent.removeChild(positions);
            result.setChangedPLF(true);
        } else {
            result.setChangedILF(true);
            if (posResult.isChangedPLF())
                result.setChangedPLF(true);
        }
    }
}

From source file:org.apereo.portal.layout.node.UserLayoutChannelDescription.java

/**
 * Reconstruct channel information from an xml <code>Element</code>
 *
 * @param xmlNode a user layout channel <code>Element</code> value
 * @exception PortalException if xml is malformed
 *///from  w ww  .  ja v a2s .  c  o m
public UserLayoutChannelDescription(Element xmlNode) throws PortalException {
    super(xmlNode);

    if (!xmlNode.getNodeName().equals("channel")) {
        throw new PortalException("Given XML Element is not a channel!");
    }

    // channel-specific attributes
    this.setTitle(xmlNode.getAttribute("title"));
    this.setDescription(xmlNode.getAttribute("description"));
    this.setClassName(xmlNode.getAttribute("class"));
    this.setChannelPublishId(xmlNode.getAttribute("chanID"));
    this.setChannelTypeId(xmlNode.getAttribute("typeID"));
    this.setFunctionalName(xmlNode.getAttribute("fname"));
    this.setTimeout(Long.parseLong(xmlNode.getAttribute("timeout")));
    this.setEditable(Boolean.valueOf(xmlNode.getAttribute("editable")).booleanValue());
    this.setHasHelp(Boolean.valueOf(xmlNode.getAttribute("hasHelp")).booleanValue());
    this.setHasAbout(Boolean.valueOf(xmlNode.getAttribute("hasAbout")).booleanValue());
    this.setIsSecure(Boolean.valueOf(xmlNode.getAttribute("secure")).booleanValue());

    // process parameter elements
    for (Node n = xmlNode.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) n;
            if (e.getNodeName().equals("parameter")) {
                // get parameter name and value
                String pName = e.getAttribute("name");
                String pValue = e.getAttribute("value");

                if (pName != null && pValue != null) {
                    this.setParameterValue(pName, pValue);
                }
            }
        }
    }
}

From source file:org.apereo.portal.layout.node.UserLayoutFolderDescription.java

/**
 * Reconstruct folder information from an xml <code>Element</code>
 *
 * @param xmlNode a user layout channel <code>Element</code> value
 * @exception PortalException if xml is malformed
 *//*from  w w  w  .j av  a2 s. c om*/
public UserLayoutFolderDescription(Element xmlNode) throws PortalException {
    super(xmlNode);

    if (!xmlNode.getNodeName().equals("folder")) {
        throw new PortalException("Given XML Element is not a folder!");
    }

    this.folderType = xmlNode.getAttribute("type");
}

From source file:org.apereo.portal.layout.node.UserLayoutNodeDescription.java

/**
 * A factory method to create a <code>UserLayoutNodeDescription</code> instance,
 * based on the information provided in the user layout <code>Element</code>.
 *
 * @param xmlNode a user layout DTD folder/channel <code>Element</code> value
 * @return an <code>UserLayoutNodeDescription</code> value
 * @exception PortalException if the xml passed is somehow invalid.
 *//*from w w w . jav  a  2 s .c o m*/
public static UserLayoutNodeDescription createUserLayoutNodeDescription(Element xmlNode)
        throws PortalException {
    // is this a folder or a channel ?
    String nodeName = xmlNode.getNodeName();
    if (nodeName.equals("channel")) {
        return new UserLayoutChannelDescription(xmlNode);
    } else if (nodeName.equals("folder")) {
        return new UserLayoutFolderDescription(xmlNode);
    } else {
        throw new PortalException("Given XML element '" + nodeName + "' is neither folder nor channel");
    }
}

From source file:org.atricore.idbus.idojos.memoryidentitystore.MemoryIdentityStore.java

/**
 * Transforms a DOM Node to a Credential instance
 * @return/*from  w w w  . j a  v a 2s . co m*/
 */
protected Credential[] toCredentials(Element domCredentialSet, CredentialProvider cp)
        throws SSOIdentityException {

    NodeList domCredentials = domCredentialSet.getElementsByTagName("credential");

    List<Credential> creds = new ArrayList<Credential>();

    // Each child must be a credential element
    for (int i = 0; i < domCredentials.getLength(); i++) {

        Element domCredential = (Element) domCredentials.item(i);
        if (domCredential.getNodeType() != Node.ELEMENT_NODE
                || !domCredential.getNodeName().equals("credential"))
            continue;

        Node domName = domCredential.getElementsByTagName("name").item(0);
        if (domName.getNodeType() != Node.ELEMENT_NODE || !domName.getNodeName().equals("name"))
            throw new SSOIdentityException("Credential definitions need a 'name' and 'value' element");

        Node domValue = domCredential.getElementsByTagName("value").item(0);
        if (domValue.getNodeType() != Node.ELEMENT_NODE || !domValue.getNodeName().equals("value"))
            throw new SSOIdentityException("Credential definitions need a 'name' and 'value' element");

        String name = getTextContent(domName);
        String value = getTextContent(domValue);

        if (logger.isDebugEnabled())
            logger.debug("Creating credential [" + name + "/" + value + "] ");

        Credential c = cp.newCredential(name, value);
        if (c != null)
            creds.add(c);
    }

    return creds.toArray(new Credential[creds.size()]);

}

From source file:org.beepcore.beep.example.Beepd.java

/**
 * Parses the beepd element in the configuration file and loads the
 * classes for the specified profiles.//from  w  w  w . ja  va2 s.co  m
 *
 * @param serverConfig &ltbeepd&gt configuration element.
 */
private Beepd(Element serverConfig) throws Exception {
    reg = new ProfileRegistry();

    if (serverConfig.hasAttribute("port") == false) {
        throw new Exception("Invalid configuration, no port specified");
    }

    port = Integer.parseInt(serverConfig.getAttribute("port"));

    // Parse the list of profile elements.
    NodeList profiles = serverConfig.getElementsByTagName("profile");
    for (int i = 0; i < profiles.getLength(); ++i) {
        if (profiles.item(i).getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        Element profile = (Element) profiles.item(i);

        if (profile.getNodeName().equalsIgnoreCase("profile") == false) {
            continue;
        }

        String uri;
        String className;
        String requiredProperites;
        String tuningProperties;

        if (profile.hasAttribute("uri") == false) {
            throw new Exception("Invalid configuration, no uri specified");
        }

        uri = profile.getAttribute("uri");

        if (profile.hasAttribute("class") == false) {
            throw new Exception("Invalid configuration, no class " + "specified for profile " + uri);
        }

        className = profile.getAttribute("class");

        // parse the parameter elements into a ProfileConfiguration
        ProfileConfiguration profileConfig = parseProfileConfig(profile.getElementsByTagName("parameter"));

        // load the profile class
        Profile p;
        try {
            p = (Profile) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            throw new Exception("Class " + className + " not found");
        } catch (ClassCastException e) {
            throw new Exception("class " + className + " does not " + "implement the "
                    + "org.beepcore.beep.profile.Profile " + "interface");
        }

        SessionTuningProperties tuning = null;

        if (profile.hasAttribute("tuning")) {
            String tuningString = profile.getAttribute("tuning");
            Hashtable hash = new Hashtable();
            StringTokenizer tokens = new StringTokenizer(tuningString, ":=");

            try {
                while (tokens.hasMoreTokens()) {
                    String parameter = tokens.nextToken();
                    String value = tokens.nextToken();

                    hash.put(parameter, value);
                }
            } catch (NoSuchElementException e) {
                e.printStackTrace();

                throw new Exception("Error parsing tuning property on " + "profile " + uri);
            }

            tuning = new SessionTuningProperties(hash);
        }

        // Initialize the profile and add it to the advertised profiles
        reg.addStartChannelListener(uri, p.init(uri, profileConfig), tuning);
    }
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * builds a form from a XML schema.//www .j  a  v  a  2 s.  c o  m
 *
 * @param inputURI the URI of the Schema to be used
 * @return __UNDOCUMENTED__
 * @throws FormBuilderException __UNDOCUMENTED__
 */
public Document buildForm(String inputURI) throws FormBuilderException {
    try {
        this.loadSchema(inputURI);
        buildTypeTree(schema);

        //refCounter = 0;
        counter = new HashMap();

        Document xForm = createFormTemplate(_rootTagName, _rootTagName + " Form",
                getProperty(CSS_STYLE_PROP, DEFAULT_CSS_STYLE_PROP));

        //this.buildInheritenceTree(schema);
        Element envelopeElement = xForm.getDocumentElement();

        //Element formSection = (Element) envelopeElement.getElementsByTagNameNS(CHIBA_NS, "form").item(0);
        //Element formSection =(Element) envelopeElement.getElementsByTagName("body").item(0);
        //find form element: last element created
        NodeList children = xForm.getDocumentElement().getChildNodes();
        int nb = children.getLength();
        Element formSection = (Element) children.item(nb - 1);

        Element modelSection = (Element) envelopeElement.getElementsByTagNameNS(XFORMS_NS, "model").item(0);

        //add XMLSchema if we use schema types
        if (_useSchemaTypes && modelSection != null) {
            modelSection.setAttributeNS(XFORMS_NS, this.getXFormsNSPrefix() + "schema", inputURI);
        }

        //change stylesheet
        String stylesheet = this.getStylesheet();

        if ((stylesheet != null) && !stylesheet.equals("")) {
            envelopeElement.setAttributeNS(CHIBA_NS, this.getChibaNSPrefix() + "stylesheet", stylesheet);
        }

        // TODO: Commented out because comments aren't output properly by the Transformer.
        //String comment = "This XForm was automatically generated by " + this.getClass().getName() + " on " + (new Date()) + System.getProperty("line.separator") + "    from the '" + rootElementName + "' element from the '" + schema.getSchemaTargetNS() + "' XML Schema.";
        //xForm.insertBefore(xForm.createComment(comment),envelopeElement);
        //xxx XSDNode node = findXSDNodeByName(rootElementTagName,schemaNode.getElementSet());

        //check if target namespace
        //no way to do this with XS API ? load DOM document ?
        //TODO: find a better way to find the targetNamespace
        try {
            Document domDoc = DOMUtil.parseXmlFile(inputURI, true, false);
            if (domDoc != null) {
                Element root = domDoc.getDocumentElement();
                targetNamespace = root.getAttribute("targetNamespace");
                if (targetNamespace != null && targetNamespace.equals(""))
                    targetNamespace = null;
            }
        } catch (Exception ex) {
            LOGGER.error("Schema not loaded as DOM document: " + ex.getMessage());
        }

        //if target namespace & we use the schema types: add it to form ns declarations
        if (_useSchemaTypes && targetNamespace != null && !targetNamespace.equals("")) {
            envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:schema", targetNamespace);
        }

        //TODO: WARNING: in Xerces 2.6.1, parameters are switched !!! (name, namespace)
        //XSElementDeclaration rootElementDecl =schema.getElementDeclaration(targetNamespace, _rootTagName);
        XSElementDeclaration rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace);

        if (rootElementDecl == null) {
            //DEBUG
            rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace);
            if (rootElementDecl != null && LOGGER.isDebugEnabled())
                LOGGER.debug("getElementDeclaration: inversed parameters OK !!!");

            throw new FormBuilderException("Invalid root element tag name [" + _rootTagName
                    + ", targetNamespace=" + targetNamespace + "]");
        }

        Element instanceElement = (Element) modelSection
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "instance"));
        this.setXFormsId(instanceElement);

        Element rootElement;

        if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_NONE) {
            rootElement = (Element) instanceElement.appendChild(
                    xForm.createElementNS(targetNamespace, getElementName(rootElementDecl, xForm)));

            String prefix = xmlSchemaInstancePrefix.substring(0, xmlSchemaInstancePrefix.length() - 1);
            rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix,
                    XMLSCHEMA_INSTANCE_NAMESPACE_URI);

        } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_INCLUDED)
        //get the instance element
        {
            boolean ok = true;

            try {
                /*DOMResult result = new DOMResult();
                TransformerFactory trFactory =
                TransformerFactory.newInstance();
                Transformer tr = trFactory.newTransformer();
                tr.transform(_instanceSource, result);
                Document instanceDoc = (Document) result.getNode();*/
                DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance();
                docFact.setNamespaceAware(true);
                docFact.setValidating(false);
                DocumentBuilder parser = docFact.newDocumentBuilder();
                Document instanceDoc = parser.parse(new InputSource(_instanceSource.getSystemId()));

                //possibility abandonned for the moment:
                //modify the instance to add the correct "xsi:type" attributes wherever needed
                //Document instanceDoc=this.setXMLSchemaAndPSVILoad(inputURI, _instanceSource, targetNamespace);

                if (instanceDoc != null) {
                    Element instanceInOtherDoc = instanceDoc.getDocumentElement();

                    if (instanceInOtherDoc.getNodeName().equals(_rootTagName)) {
                        rootElement = (Element) xForm.importNode(instanceInOtherDoc, true);
                        instanceElement.appendChild(rootElement);

                        //add XMLSchema instance NS
                        String prefix = xmlSchemaInstancePrefix.substring(0,
                                xmlSchemaInstancePrefix.length() - 1);
                        if (!rootElement.hasAttributeNS(XMLNS_NAMESPACE_URI, prefix))
                            rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix,
                                    XMLSCHEMA_INSTANCE_NAMESPACE_URI);

                        //possibility abandonned for the moment:
                        //modify the instance to add the correct "xsi:type" attributes wherever needed
                        //this.addXSITypeAttributes(rootElement);
                    } else {
                        ok = false;
                    }
                } else {
                    ok = false;
                }
            } catch (Exception ex) {
                ex.printStackTrace();

                //if there is an exception we put the empty root element
                ok = false;
            }

            //if there was a problem
            if (!ok) {
                rootElement = (Element) instanceElement.appendChild(xForm.createElement(_rootTagName));
            }
        } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_HREF)
        //add the xlink:href attribute
        {
            instanceElement.setAttributeNS(SchemaFormBuilder.XLINK_NS, this.getXLinkNSPrefix() + "href",
                    _instanceHref);
        }

        Element formContentWrapper = _wrapper.createGroupContentWrapper(formSection);
        addElement(xForm, modelSection, formContentWrapper, rootElementDecl,
                rootElementDecl.getTypeDefinition(), "/" + getElementName(rootElementDecl, xForm));

        Element submitInfoElement = (Element) modelSection
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submission"));

        //submitInfoElement.setAttributeNS(XFORMS_NS,getXFormsNSPrefix()+"id","save");
        String submissionId = this.setXFormsId(submitInfoElement);

        //action
        if (_action == null) {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", "");
        } else {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", _action);
        }

        //method
        if ((_submitMethod != null) && !_submitMethod.equals("")) {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method", _submitMethod);
        } else { //default is "post"
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method",
                    AbstractSchemaFormBuilder.SUBMIT_METHOD_POST);
        }

        //Element submitButton = (Element) formSection.appendChild(xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix()+"submit"));
        Element submitButton = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submit");
        Element submitControlWrapper = _wrapper.createControlsWrapper(submitButton);
        formContentWrapper.appendChild(submitControlWrapper);
        submitButton.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "submission", submissionId);
        this.setXFormsId(submitButton);

        Element submitButtonCaption = (Element) submitButton
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label"));
        submitButtonCaption.appendChild(xForm.createTextNode("Submit"));
        this.setXFormsId(submitButtonCaption);

        return xForm;
    } catch (ParserConfigurationException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.ClassNotFoundException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.InstantiationException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.IllegalAccessException x) {
        throw new FormBuilderException(x);
    }
}