Example usage for org.dom4j Element getNamespace

List of usage examples for org.dom4j Element getNamespace

Introduction

In this page you can find the example usage for org.dom4j Element getNamespace.

Prototype

Namespace getNamespace();

Source Link

Document

Returns the Namespace of this element if one exists otherwise Namespace.NO_NAMESPACE is returned.

Usage

From source file:com.webslingerz.jpt.PageTemplateImpl.java

License:Open Source License

private void processElement(Element element, ContentHandler contentHandler, LexicalHandler lexicalHandler,
        Interpreter beanShell, Stack<Map<String, Slot>> slotStack)
        throws SAXException, PageTemplateException, IOException {
    // Get attributes
    Expressions expressions = new Expressions();
    AttributesImpl attributes = getAttributes(element, expressions);

    // Skip macro definitions
    if (expressions.macro) {
        return;/*from  w ww .  jav  a 2  s . c  o  m*/
    }

    // Process instructions
    // 1. define
    if (expressions.define != null) {
        processDefine(expressions.define, beanShell);
    }

    // 2. condition
    if (expressions.condition != null && !Expression.evaluateBoolean(expressions.condition, beanShell)) {
        // Skip this element (and children)
        return;
    }

    // 3. repeat
    Loop loop = new Loop(expressions.repeat, beanShell);
    while (loop.repeat(beanShell)) {
        // expand macro
        if (expressions.useMacro != null) {
            processMacro(expressions.useMacro, element, contentHandler, lexicalHandler, beanShell, slotStack);
            continue;
        }

        // 4. content or replace
        Object jptContent = null;
        if (expressions.content != null) {
            jptContent = processContent(expressions.content, beanShell);
        } else
        // fill slots
        if (expressions.defineSlot != null) {
            // System.err.println( "fill slot: " + expressions.defineSlot );
            if (!slotStack.isEmpty()) {
                Map<String, Slot> slots = slotStack.pop();
                Slot slot = slots.get(expressions.defineSlot);
                // System.err.println( "slot: " + slot );
                if (slot != null) {
                    slot.process(contentHandler, lexicalHandler, beanShell, slotStack);
                    slotStack.push(slots);
                    return;
                }
                // else { use content in macro }
                slotStack.push(slots);
            } else {
                throw new PageTemplateException("slot definition not allowed outside of macro");
            }
        }

        // 5. attributes
        if (expressions.attributes != null) {
            processAttributes(attributes, expressions.attributes, beanShell);
        }

        // 6. omit-tag
        boolean jptOmitTag = false;
        if (expressions.omitTag != null) {
            if (expressions.omitTag.equals("")) {
                jptOmitTag = true;
            } else {
                jptOmitTag = Expression.evaluateBoolean(expressions.omitTag, beanShell);
            }
        }

        // Output

        // Declare element
        Namespace namespace = element.getNamespace();
        if (!jptOmitTag) {
            for (int i = 0; i < attributes.getLength(); i++) {
                String processedValue = Expression.evaluateText(attributes.getValue(i), beanShell);
                attributes.setValue(i, processedValue);
            }
            contentHandler.startElement(namespace.getURI(), element.getName(), element.getQualifiedName(),
                    attributes);
        }

        // Process content
        if (jptContent != null) {
            // Content for this element has been generated dynamically
            if (jptContent instanceof HTMLFragment) {
                HTMLFragment html = (HTMLFragment) jptContent;
                html.toXhtml(contentHandler, lexicalHandler);
            }

            // plain text
            else {
                char[] text = ((String) jptContent).toCharArray();
                contentHandler.characters(text, 0, text.length);
            }
        } else {
            defaultContent(element, contentHandler, lexicalHandler, beanShell, slotStack);
        }

        // End element
        if (!jptOmitTag) {
            contentHandler.endElement(namespace.getURI(), element.getName(), element.getQualifiedName());
        }
    }
}

From source file:com.webslingerz.jpt.PageTemplateImpl.java

License:Open Source License

AttributesImpl getAttributes(Element element, Expressions expressions) throws PageTemplateException {
    AttributesImpl attributes = new AttributesImpl();
    for (Iterator i = element.attributeIterator(); i.hasNext();) {
        Attribute attribute = (Attribute) i.next();
        Namespace namespace = attribute.getNamespace();
        Namespace elementNamespace = element.getNamespace();
        if (!namespace.hasContent() && elementNamespace.hasContent())
            namespace = elementNamespace;
        // String prefix = namespace.getPrefix();
        // System.err.println( "attribute: name=" + attribute.getName() +
        // "\t" +
        // "qualified name=" + attribute.getQualifiedName() + "\t" +
        // "ns prefix=" + namespace.getPrefix() + "\t" +
        // "ns uri=" + namespace.getURI() );
        // String qualifiedName = attribute.getName();
        // String name = qualifiedName;
        // if ( qualifiedName.startsWith( prefix + ":" ) ) {
        // name = qualifiedName.substring( prefix.length() + 1 );
        // }/*from w w  w . j  a v  a 2 s . c o m*/
        String name = attribute.getName();

        // Handle JPT attributes
        // if ( prefix.equals( talNamespacePrefix ) ) {
        if (TAL_NAMESPACE_URI.equals(namespace.getURI())
                || (!strict && TAL_NAMESPACE_PREFIX.equals(namespace.getPrefix()))) {

            // tal:define
            if (name.equals("define")) {
                expressions.define = attribute.getValue();
            }

            // tal:condition
            else if (name.equals("condition")) {
                expressions.condition = attribute.getValue();
            }

            // tal:repeat
            else if (name.equals("repeat")) {
                expressions.repeat = attribute.getValue();
            }

            // tal:content
            else if (name.equals("content")) {
                expressions.content = attribute.getValue();
            }

            // tal:replace
            else if (name.equals("replace")) {
                if (expressions.omitTag == null) {
                    expressions.omitTag = "";
                }
                expressions.content = attribute.getValue();
            }

            // tal:attributes
            else if (name.equals("attributes")) {
                expressions.attributes = attribute.getValue();
            }

            // tal:omit-tag
            else if (name.equals("omit-tag")) {
                expressions.omitTag = attribute.getValue();
            }

            // error
            else {
                throw new PageTemplateException("unknown tal attribute: " + name);
            }
        }
        // else if ( prefix.equals( metalNamespacePrefix ) )
        else if (METAL_NAMESPACE_URI.equals(namespace.getURI())
                || (!strict && METAL_NAMESPACE_PREFIX.equals(namespace.getPrefix()))) {

            // metal:use-macro
            if (name.equals("use-macro")) {
                expressions.useMacro = attribute.getValue();
            }

            // metal:define-slot
            else if (name.equals("define-slot")) {
                expressions.defineSlot = attribute.getValue();
            }

            // metal:define-macro
            else if (name.equals("define-macro")) {
                //System.out.println("Defining macro: " + attribute.getValue());
                Element el = element.createCopy();
                el.remove(attribute);
                macros.put(attribute.getValue(), new MacroImpl(el));
                expressions.macro = true;
            }

            // metal:fill-slot
            else if (name.equals("fill-slot")) {
                // these are ignored here, as they don't affect processing
                // of current template, but are called from other templates
            }

            // error
            else {
                throw new PageTemplateException("unknown metal attribute: " + name);
            }
        }

        // Pass on all other attributes
        else {
            String nsURI = namespace.getURI();
            // String qualifiedName = namespace.getPrefix() + ":" + name;
            attributes.addAttribute(nsURI, name, attribute.getQualifiedName(), "CDATA", attribute.getValue());
            if (nsURI != "" && namespace != elementNamespace) {
                String prefix = namespace.getPrefix();
                String qName = "xmlns:" + prefix;
                if (attributes.getIndex(qName) == -1) {
                    // add xmlns for this attribute
                    attributes.addAttribute("", prefix, qName, "CDATA", nsURI);
                }
            }
            // attributes.addAttribute( getNamespaceURIFromPrefix(prefix),
            // name, qualifiedName, "CDATA", attribute.getValue() );
        }
    }
    return attributes;
}

From source file:de.fct.companian.analyze.mvn.helper.PomHelper.java

License:Apache License

public PomHelper(File pomFile) throws DocumentException {
    this.pomFile = pomFile;
    this.document = null;

    SAXReader reader = new SAXReader();
    reader.setEncoding("ISO-8859-1");
    reader.setIgnoreComments(true);//w w w .j  av a  2 s  .c  o m
    reader.setValidation(false);

    try {
        this.document = reader.read(this.pomFile);
    } catch (Throwable t) {
        t.printStackTrace();
    }

    if (this.document != null) {
        Element projectElement = this.document.getRootElement();
        Namespace defaultNS = projectElement.getNamespace();
        if (logger.isDebugEnabled()) {
            logger.debug("extractPomInfo() using default namespace " + defaultNS.getURI());
        }

        Map<String, String> nsMap = new HashMap<String, String>();
        nsMap.put("mvn", defaultNS.getURI());

        this.nsContext = new SimpleNamespaceContext(nsMap);
    } else {
        throw new DocumentException("Could not create document.");
    }
}

From source file:de.interactive_instruments.etf.bsxm.SecondaryGeometryElementValidationHandler.java

License:Apache License

private void validate(ValidatorContext validatorContext, Element element)
        throws XMLParsingException, UnknownCRSException {

    Namespace namespace = element.getNamespace();
    String namespaceURI = namespace == null ? null : namespace.getURI();

    if (namespace == null
            || (!geoutils.isGML32Namespace(namespaceURI) && !geoutils.isGML31Namespace(namespaceURI))) {

        LOGGER.error("Unable to determine GML version. Namespace= {}", namespaceURI);

        String errMessage = ValidatorMessageBundle.getMessage("validator.core.validation.geometry.no-gml",
                namespaceURI);// w w  w .ja va2  s  .  c o m

        validatorContext.addError(errMessage);
        return;
    }

    if (!isGMLVersionReported) {
        if (geoutils.isGML32Namespace(namespaceURI)) {
            validatorContext.addNotice(
                    ValidatorMessageBundle.getMessage("validator.core.validation.geometry.gmlversion", "3.2"));
        } else if (geoutils.isGML31Namespace(namespaceURI)) {
            validatorContext.addNotice(
                    ValidatorMessageBundle.getMessage("validator.core.validation.geometry.gmlversion", "3.1"));
        }
        isGMLVersionReported = true;
    }

    try {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(element.asXML().getBytes());

        XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(byteArrayInputStream);

        GMLVersion gmlVersion = null;
        if (geoutils.isGML32Namespace(namespaceURI)) {
            // GML 3.2
            gmlVersion = GMLVersion.GML_32;
        } else if (geoutils.isGML31Namespace(namespaceURI)) {
            gmlVersion = GMLVersion.GML_31;
        } else {
            throw new Exception("Cannot determine GML version");
        }

        GMLStreamReader gmlStream = GMLInputFactory.createGMLStreamReader(gmlVersion, xmlStream);

        Geometry geom = gmlStream.readGeometry();

        // ================
        // Test: polygon patches of a surface are connected
        if (isTestPolygonPatchConnectivity) {
            boolean isValid = checkConnectivityOfPolygonPatches(geom);
            if (!isValid) {
                polygonPatchesAreConnected = false;
            }
        }

        // ================
        // Test: point repetition in curve segment
        if (isTestRepetitionInCurveSegments) {
            boolean isValid = checkNoRepetitionInCurveSegment(geom);
            if (!isValid) {
                noRepetitionInCurveSegments = false;
            }
        }

    } catch (XMLStreamException e) {

        String currentGmlId = Dom4JHelper.findGmlId(element);

        String message = getLocationDescription(element, currentGmlId) + ": " + e.getMessage();

        validatorContext.addError(message, new IdErrorLocation(currentGmlId));

        LOGGER.error(e.getMessage(), e);

    } catch (FactoryConfigurationError e) {

        LOGGER.error(e.getMessage(), e);
        validatorContext.addError(
                ValidatorMessageBundle.getMessage("validator.core.validation.geometry.unknown-exception"));

    } catch (Exception e) {
        String currentGmlId = Dom4JHelper.findGmlId(element);

        String message = getLocationDescription(element, currentGmlId) + ": " + e.getMessage();

        validatorContext.addError(message, new IdErrorLocation(currentGmlId));

        LOGGER.error(e.getMessage(), e);
    }

    // finally {
    // // Only permitted if this is a main geometry....
    // if (isMainGeometry(element)) {
    // element.detach();
    // }
    // }
}

From source file:edu.ucsd.library.dams.jhove.MyJhoveBase.java

License:Open Source License

public static void removeNS(Element elem) {
    elem.remove(elem.getNamespace());
    elem.setQName(new QName(elem.getQName().getName(), Namespace.NO_NAMESPACE));
    // fix children
    List children = elem.elements();
    for (int i = 0; i < children.size(); i++) {
        Element child = (Element) children.get(i);
        removeNS(child);/*from  ww  w  . ja v a 2s . c o  m*/
    }
}

From source file:fr.gouv.culture.vitam.utils.XmlDom.java

License:Open Source License

public final static void removeAllNamespaces(Document doc) {
    Element root = doc.getRootElement();
    Namespace namespace = root.getNamespace();
    if (namespace != Namespace.NO_NAMESPACE) {
        root.remove(namespace);//from   www.j av a2 s .co m
        removeNamespaces(root.content());
    }
}

From source file:net.dontdrinkandroot.lastfm.api.CheckImplementationStatus.java

License:Apache License

/**
 * Removes namespaces if removeNamespaces is true
 */// w w w  .  j  av a  2 s .  com
@SuppressWarnings("unchecked")
public static void fixNamespaces(final Document doc) {

    final Element root = doc.getRootElement();
    if (CheckImplementationStatus.removeNamespaces && root.getNamespace() != Namespace.NO_NAMESPACE) {
        CheckImplementationStatus.removeNamespaces(root.content());
    }
}

From source file:nl.tue.gale.ae.processor.XMLProcessor.java

License:Open Source License

public void traverse(Element element, Resource resource) throws ProcessorException {
    if (element == null)
        return;//w w  w  .j ava  2 s .co m
    Namespace ns = element.getNamespace();
    String tag = null;
    if (ns != Namespace.NO_NAMESPACE) {
        tag = "{" + ns.getURI() + "}" + element.getName();
        if (!moduleTable.containsKey(tag))
            tag = null;
    }
    if (tag == null)
        tag = element.getName();
    if (moduleTable.containsKey(tag)) {
        Module mod = moduleTable.get(tag);
        if (mod.getMimeToHandle().contains(GaleContext.mime(resource))) {
            try {
                element = moduleTable.get(tag).traverse(element, resource);
            } catch (Exception e) {
                e.printStackTrace();
                element = (Element) GaleUtil.replaceNode(element,
                        GaleUtil.createErrorElement("[" + e.getMessage() + "]"));
            }
        }
    }
    traverseChildren(element, resource);
    if ("text/xhtml".equals(GaleContext.mime(resource)))
        if (element != null)
            if ("http://www.w3.org/1999/xhtml".equals(element.getNamespaceURI()))
                element.setQName(DocumentFactory.getInstance().createQName(element.getName(), "",
                        "http://www.w3.org/1999/xhtml"));
}

From source file:org.apache.poi.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

/**
 * Check the element for the following OPC compliance rules:
 * <p>//from ww w. j  av  a  2 s  .c o  m
 * Rule M4.2: A format consumer shall consider the use of the Markup
 * Compatibility namespace to be an error.
 * </p><p>
 * Rule M4.3: Producers shall not create a document element that contains
 * refinements to the Dublin Core elements, except for the two specified in
 * the schema: <dcterms:created> and <dcterms:modified> Consumers shall
 * consider a document element that violates this constraint to be an error.
 * </p><p>
 * Rule M4.4: Producers shall not create a document element that contains
 * the xml:lang attribute. Consumers shall consider a document element that
 * violates this constraint to be an error.
 *  </p><p>
 * Rule M4.5: Producers shall not create a document element that contains
 * the xsi:type attribute, except for a <dcterms:created> or
 * <dcterms:modified> element where the xsi:type attribute shall be present
 * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace
 * prefix of the Dublin Core namespace. Consumers shall consider a document
 * element that violates this constraint to be an error.
 * </p>
 */
public void checkElementForOPCCompliance(Element el) throws InvalidFormatException {
    // Check the current element
    @SuppressWarnings("unchecked")
    List<Namespace> declaredNamespaces = el.declaredNamespaces();
    Iterator<Namespace> itNS = declaredNamespaces.iterator();
    while (itNS.hasNext()) {
        Namespace ns = itNS.next();

        // Rule M4.2
        if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY))
            throw new InvalidFormatException(
                    "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
    }

    // Rule M4.3
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)
            && !(el.getName().equals(KEYWORD_CREATED) || el.getName().equals(KEYWORD_MODIFIED)))
        throw new InvalidFormatException(
                "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.4
    if (el.attribute(new QName("lang", namespaceXML)) != null)
        throw new InvalidFormatException(
                "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.5
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)) {
        // DCTerms namespace only use with 'created' and 'modified' elements
        String elName = el.getName();
        if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED)))
            throw new InvalidFormatException("Namespace error : " + elName
                    + " shouldn't have the following naemspace -> " + PackageProperties.NAMESPACE_DCTERMS);

        // Check for the 'xsi:type' attribute
        Attribute typeAtt = el.attribute(new QName("type", namespaceXSI));
        if (typeAtt == null)
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute present !");

        // Check for the attribute value => 'dcterms:W3CDTF'
        if (!typeAtt.getValue().equals("dcterms:W3CDTF"))
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute with the value 'dcterms:W3CDTF' !");
    }

    // Check its children
    @SuppressWarnings("unchecked")
    Iterator<Element> itChildren = el.elementIterator();
    while (itChildren.hasNext())
        checkElementForOPCCompliance(itChildren.next());
}

From source file:org.b5chat.crossfire.core.net.sasl.SASLAuthentication.java

License:Open Source License

/**
 * Handles the SASL authentication packet. The entity may be sending an initial
 * authentication request or a response to a challenge made by the server. The returned
 * value indicates whether the authentication has finished either successfully or not or
 * if the entity is expected to send a response to a challenge.
 *
 * @param session the session that is authenticating with the server.
 * @param doc the stanza sent by the authenticating entity.
 * @return value that indicates whether the authentication has finished either successfully
 *         or not or if the entity is expected to send a response to a challenge.
 * @throws UnsupportedEncodingException If UTF-8 charset is not supported.
 *//*from   www.  j  a va  2 s  . co  m*/
public static Status handle(LocalSession session, Element doc) throws UnsupportedEncodingException {
    Status status;
    String mechanism;
    if (doc.getNamespace().asXML().equals(SASL_NAMESPACE)) {
        ElementType type = ElementType.valueof(doc.getName());
        switch (type) {
        case AUTH:
            mechanism = doc.attributeValue("mechanism");
            // Store the requested SASL mechanism by the client
            session.setSessionData("SaslMechanism", mechanism);
            //Log.debug("SASLAuthentication.doHandshake() AUTH entered: "+mechanism);
            if (mechanism.equalsIgnoreCase("ANONYMOUS") && mechanisms.contains("ANONYMOUS")) {
                status = doAnonymousAuthentication(session);
            } else if (mechanisms.contains(mechanism)) {
                // The selected SASL mechanism requires the server to send a challenge
                // to the client
                try {
                    Map<String, String> props = new TreeMap<String, String>();
                    props.put(Sasl.QOP, "auth");
                    if (mechanism.equals("GSSAPI")) {
                        props.put(Sasl.SERVER_AUTH, "TRUE");
                    }
                    SaslServer ss = Sasl.createSaslServer(mechanism, "xmpp",
                            Globals.getProperty("xmpp.fqdn", session.getServerName()), props,
                            new XMPPCallbackHandler());
                    // evaluateResponse doesn't like null parameter
                    byte[] token = new byte[0];
                    if (doc.getText().length() > 0) {
                        // If auth request includes a value then validate it
                        token = StringUtils.decodeBase64(doc.getText().trim());
                        if (token == null) {
                            token = new byte[0];
                        }
                    }
                    if (mechanism.equals("DIGEST-MD5")) {
                        // RFC2831 (DIGEST-MD5) says the client MAY provide an initial response on subsequent
                        // authentication. Java SASL does not (currently) support this and thows an exception
                        // if we try.  This violates the RFC, so we just strip any initial token.
                        token = new byte[0];
                    }
                    byte[] challenge = ss.evaluateResponse(token);
                    if (ss.isComplete()) {
                        authenticationSuccessful(session, ss.getAuthorizationID(), challenge);
                        status = Status.authenticated;
                    } else {
                        // Send the challenge
                        sendChallenge(session, challenge);
                        status = Status.needResponse;
                    }
                    session.setSessionData("SaslServer", ss);
                } catch (SaslException e) {
                    Log.info("User Login Failed. " + e.getMessage());
                    authenticationFailed(session);
                    status = Status.failed;
                }
            } else {
                Log.warn("Client wants to do a MECH we don't support: '" + mechanism + "'");
                authenticationFailed(session);
                status = Status.failed;
            }
            break;
        case RESPONSE:
            // Store the requested SASL mechanism by the client
            mechanism = (String) session.getSessionData("SaslMechanism");
            if (mechanism.equalsIgnoreCase("b5chat-SHAREDSECRET")) {
                status = doSharedSecretAuthentication(session, doc);
            } else if (mechanisms.contains(mechanism)) {
                SaslServer ss = (SaslServer) session.getSessionData("SaslServer");
                if (ss != null) {
                    boolean ssComplete = ss.isComplete();
                    String response = doc.getTextTrim();
                    try {
                        if (ssComplete) {
                            authenticationSuccessful(session, ss.getAuthorizationID(), null);
                            status = Status.authenticated;
                        } else {
                            byte[] data = StringUtils.decodeBase64(response);
                            if (data == null) {
                                data = new byte[0];
                            }
                            byte[] challenge = ss.evaluateResponse(data);
                            if (ss.isComplete()) {
                                authenticationSuccessful(session, ss.getAuthorizationID(), challenge);
                                status = Status.authenticated;
                            } else {
                                // Send the challenge
                                sendChallenge(session, challenge);
                                status = Status.needResponse;
                            }
                        }
                    } catch (SaslException e) {
                        Log.debug("SASLAuthentication: SaslException", e);
                        authenticationFailed(session);
                        status = Status.failed;
                    }
                } else {
                    Log.error("SaslServer is null, should be valid object instead.");
                    authenticationFailed(session);
                    status = Status.failed;
                }
            } else {
                Log.warn("Client responded to a MECH we don't support: '" + mechanism + "'");
                authenticationFailed(session);
                status = Status.failed;
            }
            break;
        default:
            authenticationFailed(session);
            status = Status.failed;
            // Ignore
            break;
        }
    } else {
        Log.debug("SASLAuthentication: Unknown namespace sent in auth element: " + doc.asXML());
        authenticationFailed(session);
        status = Status.failed;
    }
    // Check if SASL authentication has finished so we can clean up temp information
    if (status == Status.failed || status == Status.authenticated) {
        // Remove the SaslServer from the ISession
        session.removeSessionData("SaslServer");
        // Remove the requested SASL mechanism by the client
        session.removeSessionData("SaslMechanism");
    }
    return status;
}