Example usage for org.dom4j Element getNamespaceURI

List of usage examples for org.dom4j Element getNamespaceURI

Introduction

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

Prototype

String getNamespaceURI();

Source Link

Document

Returns the URI mapped to the namespace of this element if one exists otherwise an empty String is returned.

Usage

From source file:org.jivesoftware.xmpp.workgroup.WorkgroupIQHandler.java

License:Open Source License

private void handleIQGet(IQ packet) {
    IQ reply = null;/* w w  w . j a va2s .  co m*/
    // TODO: verify namespace and send error if wrong
    Element iq = packet.getChildElement();
    UserRequest request;

    final WorkgroupStats stats = new WorkgroupStats(workgroup);

    String name = iq.getName();
    String namespace = iq.getNamespaceURI();
    if ("queue-status".equals(name)) {
        try {
            request = UserRequest.getRequest(workgroup, packet.getFrom());
            request.updateQueueStatus(true);
        } catch (NotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(new PacketError(PacketError.Condition.item_not_found));
        }
    } else if ("transcripts".equals(name)) {
        try {
            // Check if the sender of the packet is a connected Agent to this workgroup.
            // Otherwise return a not_authorized
            if (agentManager.getAgentSession(packet.getFrom()) == null) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(new PacketError(PacketError.Condition.not_authorized));
            } else {
                String userID = iq.attributeValue("userID");
                stats.getChatTranscripts(packet, userID);
            }
        } catch (AgentNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(new PacketError(PacketError.Condition.not_authorized));
        }
    } else if ("transcript".equals(name)) {
        try {
            // Check if the sender of the packet is a connected Agent to this workgroup.
            // Otherwise return a not_authorized
            if (agentManager.getAgentSession(packet.getFrom()) == null) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(new PacketError(PacketError.Condition.not_authorized));
            } else {
                String sessionID = iq.attributeValue("sessionID");
                stats.getChatTranscript(packet, sessionID);
            }
        } catch (AgentNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(new PacketError(PacketError.Condition.not_authorized));
        }
    } else if ("agent-status-request".equals(name)) {
        try {
            AgentSession agentSession = agentManager.getAgentSession(packet.getFrom());
            if (agentSession == null) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(new PacketError(PacketError.Condition.item_not_found));
            } else {
                agentSession.sendAgentsInWorkgroup(packet, workgroup);
            }
        } catch (AgentNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(new PacketError(PacketError.Condition.item_not_found));
        }
    } else if ("agent-info".equals(name)) {
        try {
            // Send the agent's info to the session that requested its own information
            AgentSession agentSession = agentManager.getAgentSession(packet.getFrom());
            if (agentSession == null) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(new PacketError(PacketError.Condition.item_not_found));
            } else {
                agentSession.sendAgentInfo(packet);
            }
        } catch (AgentNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(new PacketError(PacketError.Condition.item_not_found));
        }
    } else if ("occupants-info".equals(name)) {
        try {
            // Just check that the packet was sent by a logged agent to this workgroup
            AgentSession agentSession = agentManager.getAgentSession(packet.getFrom());
            if (agentSession == null) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(new PacketError(PacketError.Condition.not_authorized));
            } else {
                // Send information about the occupants of the requested room
                String roomID = iq.attributeValue("roomID");
                workgroup.sendOccupantsInfo(packet, roomID);
            }
        } catch (AgentNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(new PacketError(PacketError.Condition.not_authorized));
        }
    } else if ("chat-settings".equals(name)) {
        ChatSettingsManager chatSettingsManager = ChatSettingsManager.getInstance();
        String key = iq.attributeValue("key");
        String type = iq.attributeValue("type");
        if (ModelUtil.hasLength(key)) {
            chatSettingsManager.getChatSettingByKey(packet, workgroup, key);
        } else if (ModelUtil.hasLength(type)) {
            try {
                int typeInt = Integer.parseInt(type);
                chatSettingsManager.getChatSettingsByType(packet, workgroup, typeInt);
            } catch (NumberFormatException e) {
                // Bad type.
            }
        } else {
            chatSettingsManager.getAllChatSettings(packet, workgroup);
        }
    } else if ("jabber:iq:private".equals(namespace)) {
        // IQ private for agents global macro storage
        getIQPrivate(packet);
    } else if ("vcard-temp".equals(namespace)) {
        // Return workgroup's VCard
        getVCard(packet);
    } else {

        // Check all Workgroup Providers for handling this GET request. If
        // none are found, send bad request error.
        for (WorkgroupProvider provider : providerManager.getWorkgroupProviders()) {
            // Will provider handle the GET
            if (provider.handleGet(packet)) {
                // Pass off packet
                provider.executeGet(packet, workgroup);
                return;
            }
        }

        dropPacket(packet);
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(new PacketError(PacketError.Condition.bad_request));
    }
    if (reply != null) {
        workgroup.send(reply);
    }
}

From source file:org.jivesoftware.xmpp.workgroup.WorkgroupManager.java

License:Open Source License

/**
 * Returns true if the IQ packet was processed. This method should only process disco packets
 * sent to the workgroup service.//from  w ww.j ava2  s .  co m
 *
 * @param iq the IQ packet to process.
 * @return true if the IQ packet was processed.
 */
private boolean process(IQ iq) {
    if (iq.getType() == IQ.Type.error) {
        // Skip IQ packets of type error
        return false;
    }
    Element childElement = iq.getChildElement();
    String name = null;
    String namespace = null;
    if (childElement != null) {
        namespace = childElement.getNamespaceURI();
        name = childElement.getName();
    }
    if ("http://jabber.org/protocol/disco#info".equals(namespace)) {
        IQ reply = iqDiscoInfoHandler.handleIQ(iq);
        if (reply != null) {
            send(reply);
        }
    } else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
        IQ reply = iqDiscoItemsHandler.handleIQ(iq);
        if (reply != null) {
            send(reply);
        }
    } else if ("jabber:iq:version".equals(namespace)) {
        IQ reply = IQ.createResultIQ(iq);
        Element version = reply.setChildElement("query", "jabber:iq:version");
        version.addElement("name").setText("Spark Fastpath");
        version.addElement("version").setText("3.2");
        version.addElement("os").setText("Java 5");
        send(reply);
    } else if ("workgroups".equals(name)) {
        try {
            // Check that the sender of this IQ is an agent
            getAgentManager().getAgent(iq.getFrom());
            // Get the agent JID to return his workgroups
            String agentJID = childElement.attributeValue("jid");
            try {
                // Answer the workgroups where the agent can work in
                Agent agent = getAgentManager().getAgent(new JID(agentJID));
                sendWorkgroups(iq, agent);
            } catch (AgentNotFoundException e) {
                IQ reply = IQ.createResultIQ(iq);
                reply.setChildElement(iq.getChildElement().createCopy());
                reply.setError(new PacketError(PacketError.Condition.item_not_found));
                send(reply);
            }
        } catch (AgentNotFoundException e) {
            IQ reply = IQ.createResultIQ(iq);
            reply.setChildElement(iq.getChildElement().createCopy());
            reply.setError(new PacketError(PacketError.Condition.not_authorized));
            send(reply);
        }
    } else if ("transcript-search".equals(name)) {
        iqChatSearchHandler.handleIQ(iq);
    } else if ("http://jabber.org/protocol/commands".equals(namespace)) {
        // Process ad-hoc command
        IQ reply = commandManager.process(iq);
        send(reply);
    } else {
        return false;
    }
    return true;
}

From source file:org.mos.openfire.plugin.B9Plugin.java

License:Open Source License

private void processIQ(IQ iq, boolean targetSrv, boolean canProceed) {

    IQ reply = IQ.createResultIQ(iq);//from   w w w .j  av  a 2s.  c  o  m
    Element childElement = iq.getChildElement();
    String namespace = childElement.getNamespaceURI();
    Element childElementCopy = iq.getChildElement().createCopy();
    reply.setChildElement(childElementCopy);

    if ("http://jabber.org/protocol/disco#info".equals(namespace)) {

        if (iq.getTo().getNode() == null) {

            // Return service identity and features
            Element identity = childElementCopy.addElement("identity");
            identity.addAttribute("category", "component");
            identity.addAttribute("type", "generic");
            identity.addAttribute("name", "B9 service");
            childElementCopy.addElement("feature").addAttribute("var", "http://jabber.org/protocol/disco#info");
            childElementCopy.addElement("feature").addAttribute("var",
                    "http://jabber.org/protocol/disco#items");
        }

        else {

            if (targetSrv) {

                // Return identity and features of the "all" group
                Element identity = childElementCopy.addElement("identity");
                identity.addAttribute("category", "component");
                identity.addAttribute("type", "generic");
                identity.addAttribute("name", "Openfire Administration Bot");
                childElementCopy.addElement("feature").addAttribute("var",
                        "http://jabber.org/protocol/disco#info");
            }
        }
    }

    try {

        componentManager.sendPacket(this, reply);
    } catch (Exception e) {

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

From source file:org.mos.openfire.plugin.ServerInfoPlugin.java

License:Open Source License

private void processIQ(IQ iq, boolean targetSrv, boolean canProceed) {

    IQ reply = IQ.createResultIQ(iq);//  w  w  w. j a v  a2 s.  c o m
    Element childElement = iq.getChildElement();
    String namespace = childElement.getNamespaceURI();
    Element childElementCopy = iq.getChildElement().createCopy();
    reply.setChildElement(childElementCopy);

    if ("http://jabber.org/protocol/disco#info".equals(namespace)) {

        if (iq.getTo().getNode() == null) {

            // Return service identity and features
            Element identity = childElementCopy.addElement("identity");
            identity.addAttribute("category", "component");
            identity.addAttribute("type", "generic");
            identity.addAttribute("name", "ServerInfo service");
            childElementCopy.addElement("feature").addAttribute("var", "http://jabber.org/protocol/disco#info");
            childElementCopy.addElement("feature").addAttribute("var",
                    "http://jabber.org/protocol/disco#items");
        }

        else {

            if (targetSrv) {

                // Return identity and features of the "all" group
                Element identity = childElementCopy.addElement("identity");
                identity.addAttribute("category", "component");
                identity.addAttribute("type", "generic");
                identity.addAttribute("name", "Display requested server information");
                childElementCopy.addElement("feature").addAttribute("var",
                        "http://jabber.org/protocol/disco#info");
            }
        }
    }

    try {

        componentManager.sendPacket(this, reply);
    } catch (Exception e) {

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

From source file:org.mule.config.spring.SpringXmlConfigurationMuleArtifactFactory.java

License:Open Source License

private MuleArtifact doGetArtifact(org.w3c.dom.Element element, XmlConfigurationCallback callback,
        boolean embedInFlow) throws MuleArtifactFactoryException {
    ConfigResource config = null;/*from  ww w  .  j  a v  a 2  s.c  o m*/
    Document document = DocumentHelper.createDocument();

    // the rootElement is the root of the document
    Element rootElement = document.addElement("mule", "http://www.mulesoft.org/schema/mule/core");

    // the parentElement is the parent of the element we are adding
    Element parentElement = rootElement;
    addSchemaLocation(rootElement, element, callback);
    String flowName = "flow-" + Integer.toString(element.hashCode());
    if (embedInFlow) {
        // Need to put the message processor in a valid flow. Our default flow is:
        //            "<flow name=\"CreateSingle\">"
        //          + "</flow>"
        parentElement = rootElement.addElement("flow", "http://www.mulesoft.org/schema/mule/core");
        parentElement.addAttribute("name", flowName);
    }
    try {
        parentElement.add(convert(element));
        for (int i = 0; i < element.getAttributes().getLength(); i++) {
            String attributeName = element.getAttributes().item(i).getLocalName();
            if (attributeName != null && attributeName.endsWith("-ref")) {
                org.w3c.dom.Element dependentElement = callback
                        .getGlobalElement(element.getAttributes().item(i).getNodeValue());
                if (dependentElement != null) {
                    // if the element is a spring bean, wrap the element in a top-level spring beans element
                    if ("http://www.springframework.org/schema/beans"
                            .equals(dependentElement.getNamespaceURI())) {
                        String namespaceUri = dependentElement.getNamespaceURI();
                        Namespace namespace = new Namespace(dependentElement.getPrefix(), namespaceUri);
                        Element beans = rootElement.element(new QName("beans", namespace));
                        if (beans == null) {
                            beans = rootElement.addElement("beans", namespaceUri);
                        }
                        beans.add(convert(dependentElement));
                    } else {
                        rootElement.add(convert(dependentElement));
                        addSchemaLocation(rootElement, dependentElement, callback);
                    }
                    addChildSchemaLocations(rootElement, dependentElement, callback);
                }
                // if missing a dependent element, try anyway because it might not be needed.
            }
        }

        config = new ConfigResource("", new StringBufferInputStream(document.asXML()));
    } catch (Exception e) {
        throw new MuleArtifactFactoryException("Error parsing XML", e);
    }
    MuleContext muleContext = null;
    SpringXmlConfigurationBuilder builder = null;
    try {
        MuleContextFactory factory = new DefaultMuleContextFactory();
        builder = new SpringXmlConfigurationBuilder(new ConfigResource[] { config });
        muleContext = factory.createMuleContext(builder);
        muleContext.start();

        MuleArtifact artifact = null;
        if (embedInFlow) {
            Pipeline pipeline = (Pipeline) muleContext.getRegistry().lookupFlowConstruct(flowName);
            artifact = new DefaultMuleArtifact(pipeline.getMessageProcessors().get(0));
        } else {
            artifact = new DefaultMuleArtifact(
                    muleContext.getRegistry().lookupObject(element.getAttribute("name")));
        }
        builders.put(artifact, builder);
        contexts.put(artifact, muleContext);
        return artifact;
    } catch (Exception e) {
        dispose(builder, muleContext);
        throw new MuleArtifactFactoryException("Error initializing", e);
    }
}

From source file:org.mule.config.spring.SpringXmlConfigurationMuleArtifactFactory.java

License:Open Source License

protected void addSchemaLocation(Element rootElement, org.w3c.dom.Element element,
        XmlConfigurationCallback callback) {
    StringBuffer schemaLocation = new StringBuffer();
    schemaLocation.append(/* www. j ava 2  s. c  o m*/
            "http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd\n");
    schemaLocation
            .append(element.getNamespaceURI() + " " + callback.getSchemaLocation(element.getNamespaceURI()));
    rootElement.addAttribute(
            org.dom4j.QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
            schemaLocation.toString());
}

From source file:org.onosproject.xmpp.pubsub.ctl.XmppPubSubControllerImpl.java

License:Apache License

private boolean isPubSub(IQ iq) {
    Element pubsub = iq.getElement().element(PUBSUB_ELEMENT);
    if (pubsub != null && pubsub.getNamespaceURI().equals(PUBSUB_NAMESPACE)) {
        return true;
    }/*from   w  w w  .  j ava 2s.c  o m*/
    return false;
}

From source file:org.onosproject.yms.app.ych.defaultcodecs.xml.DefaultXmlCodec.java

License:Apache License

@Override
public YdtBuilder decodeProtocolDataToYdt(String protoData, Object schemaReg, YmsOperationType opType) {
    Document document;/*  w  w w.jav a  2 s. c o  m*/

    try {
        document = DocumentHelper.parseText(protoData);
    } catch (DocumentException e) {
        throw new YchException(E_ROOT_ELEMENT);
    }

    NetconfCodec codec = new NetconfCodec();
    // Find the root element in xml string
    Element rootElement = codec.getDataRootElement(document.getRootElement(), opType);

    if (rootElement == null) {
        throw new YchException(E_ROOT_KEY_ELEMENT);
    }

    // Get the YDT builder for the logical root name.
    YdtExtendedBuilder extBuilder = new YangRequestWorkBench(rootElement.getName(),
            rootElement.getNamespaceURI(), opType, (YangSchemaRegistry) schemaReg, false);

    XmlCodecListener listener = new XmlCodecListener();
    listener.setYdtExtBuilder(extBuilder);
    // Walk through xml and build the yang data tree.
    XmlWalker walker = new DefaultXmlCodecWalker();
    walker.walk(listener, rootElement, rootElement);
    return extBuilder;
}

From source file:org.orbeon.oxf.processor.SessionSerializer.java

License:Open Source License

public void start(org.orbeon.oxf.pipeline.api.PipelineContext context) {
    try {//from   ww  w .  ja va  2  s  . c o  m
        ExternalContext externalContext = (ExternalContext) context
                .getAttribute(PipelineContext.EXTERNAL_CONTEXT);

        SAXStore store = new SAXStore();
        Document document = readCacheInputAsDOM4J(context, INPUT_DATA);
        Element value = document.getRootElement();
        if (value == null)
            throw new OXFException("Session serializer input data is null");

        String namespaceURI = value.getNamespaceURI();
        String localName = value.getName();
        String key = (namespaceURI.equals("")) ? localName : "{" + namespaceURI + "}" + localName;

        LocationSAXWriter saxw = new LocationSAXWriter();
        saxw.setContentHandler(store);
        saxw.write(document);

        // Store the document into the session
        externalContext.getSession(true).getAttributesMap().put(key, store);

    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.processor.sql.SQLProcessor.java

License:Open Source License

protected void execute(final PipelineContext context, XMLReceiver xmlReceiver) {
    try {//from   w  w w.jav  a2s .  com
        // Cache, read and interpret the config input
        Config config = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG),
                new CacheableInputReader<Config>() {
                    public Config read(PipelineContext context, ProcessorInput input) {
                        // Read the config input document
                        Node config = readInputAsDOM4J(context, input);
                        Document configDocument = config.getDocument();

                        // Extract XPath expressions and also check whether any XPath expression is used at all
                        // NOTE: This could be done through streaming below as well
                        // NOTE: For now, just match <sql:param select="/*" type="xs:base64Binary"/>
                        List xpathExpressions = new ArrayList();
                        boolean useXPathExpressions = false;
                        for (Iterator i = XPathUtils.selectIterator(configDocument,
                                "//*[namespace-uri() = '" + SQL_NAMESPACE_URI + "' and @select]"); i
                                        .hasNext();) {
                            Element element = (Element) i.next();
                            useXPathExpressions = true;
                            String typeAttribute = element.attributeValue("type");
                            if ("xs:base64Binary".equals(typeAttribute)) {
                                String selectAttribute = element.attributeValue("select");
                                xpathExpressions.add(selectAttribute);
                            }
                        }

                        // Normalize spaces. What this does is to coalesce adjacent text nodes, and to remove
                        // resulting empty text, unless the text is contained within a sql:text element.
                        configDocument.accept(new VisitorSupport() {
                            private boolean endTextSequence(Element element, Text previousText) {
                                if (previousText != null) {
                                    String value = previousText.getText();
                                    if (value == null || value.trim().equals("")) {
                                        element.remove(previousText);
                                        return true;
                                    }
                                }
                                return false;
                            }

                            @Override
                            public void visit(Element element) {
                                // Don't touch text within sql:text elements
                                if (!SQL_NAMESPACE_URI.equals(element.getNamespaceURI())
                                        || !"text".equals(element.getName())) {
                                    Text previousText = null;
                                    for (int i = 0, size = element.nodeCount(); i < size;) {
                                        Node node = element.node(i);
                                        if (node instanceof Text) {
                                            Text text = (Text) node;
                                            if (previousText != null) {
                                                previousText.appendText(text.getText());
                                                element.remove(text);
                                            } else {
                                                String value = text.getText();
                                                // Remove empty text nodes
                                                if (value == null || value.length() < 1) {
                                                    element.remove(text);
                                                } else {
                                                    previousText = text;
                                                    i++;
                                                }
                                            }
                                        } else {
                                            if (!endTextSequence(element, previousText))
                                                i++;
                                            previousText = null;
                                        }
                                    }
                                    endTextSequence(element, previousText);
                                }
                            }
                        });
                        // Create SAXStore
                        try {
                            final SAXStore store = new SAXStore();
                            final LocationSAXWriter locationSAXWriter = new LocationSAXWriter();
                            locationSAXWriter.setContentHandler(store);
                            locationSAXWriter.write(configDocument);
                            // Return the normalized document
                            return new Config(store, useXPathExpressions, xpathExpressions);
                        } catch (SAXException e) {
                            throw new OXFException(e);
                        }
                    }
                });

        // Either read the whole input as a DOM, or try to serialize
        Node data = null;
        XPathXMLReceiver xpathReceiver = null;

        // Check if the data input is connected
        boolean hasDataInput = getConnectedInputs().get(INPUT_DATA) != null;
        if (!hasDataInput && config.useXPathExpressions)
            throw new OXFException(
                    "The data input must be connected when the configuration uses XPath expressions.");
        if (!hasDataInput || !config.useXPathExpressions) {
            // Just use an empty document
            data = Dom4jUtils.NULL_DOCUMENT;
        } else {
            // There is a data input connected and there are some XPath expressions operating on it
            boolean useXPathContentHandler = false;
            if (config.xpathExpressions.size() > 0) {
                // Create XPath content handler
                final XPathXMLReceiver _xpathReceiver = new XPathXMLReceiver();
                // Add expressions and check whether we can try to stream
                useXPathContentHandler = true;
                for (Iterator i = config.xpathExpressions.iterator(); i.hasNext();) {
                    String expression = (String) i.next();
                    boolean canStream = _xpathReceiver.addExpresssion(expression, false);// FIXME: boolean nodeSet
                    if (!canStream) {
                        useXPathContentHandler = false;
                        break;
                    }
                }
                // Finish setting up the XPathContentHandler
                if (useXPathContentHandler) {
                    _xpathReceiver.setReadInputCallback(new Runnable() {
                        public void run() {
                            readInputAsSAX(context, INPUT_DATA, _xpathReceiver);
                        }
                    });
                    xpathReceiver = _xpathReceiver;
                }
            }
            // If we can't stream, read everything in
            if (!useXPathContentHandler)
                data = readInputAsDOM4J(context, INPUT_DATA);
        }

        // Try to read datasource input if any
        Datasource datasource = null;
        {
            List datasourceInputs = (List) getConnectedInputs().get(INPUT_DATASOURCE);
            if (datasourceInputs != null) {
                if (datasourceInputs.size() > 1)
                    throw new OXFException("At most one one datasource input can be connected.");
                ProcessorInput datasourceInput = (ProcessorInput) datasourceInputs.get(0);
                datasource = Datasource.getDatasource(context, this, datasourceInput);
            }
        }

        // Replay the config SAX store through the interpreter
        config.configInput.replay(
                new RootInterpreter(context, getPropertySet(), data, datasource, xpathReceiver, xmlReceiver));
    } catch (OXFException e) {
        throw e;
    } catch (Exception e) {
        throw new OXFException(e);
    }
}