Example usage for org.dom4j QName QName

List of usage examples for org.dom4j QName QName

Introduction

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

Prototype

public QName(String name, Namespace namespace) 

Source Link

Usage

From source file:org.jivesoftware.openfire.http.HttpSession.java

License:Open Source License

/**
 * Forwards a client request, which is related to a session, to the server. A connection is
 * created and queued up in the provided session. When a connection reaches the top of a queue
 * any pending packets bound for the client will be forwarded to the client through the
 * connection.// w w  w .j a  v a  2s . c om
 *
 * @param rid the unique, sequential, requestID sent from the client.
 * @param isSecure true if the request was made over a secure channel, HTTPS, and false if it
 * was not.
 * @param rootNode the XML body of the request.
 * @param context the context of the asynchronous servlet call leading up to this method call.
 *
 * @throws org.jivesoftware.openfire.http.HttpBindException for several reasons: if the encoding inside of an auth packet is
 * not recognized by the server, or if the packet type is not recognized.
 * @throws org.jivesoftware.openfire.http.HttpConnectionClosedException if the session is no longer available.
 */
public void forwardRequest(long rid, boolean isSecure, Element rootNode, AsyncContext context)
        throws HttpBindException, HttpConnectionClosedException, IOException {
    List<Element> elements = rootNode.elements();
    boolean isPoll = (elements.size() == 0);
    if ("terminate".equals(rootNode.attributeValue("type")))
        isPoll = false;
    else if ("true"
            .equals(rootNode.attributeValue(new QName("restart", rootNode.getNamespaceForPrefix("xmpp")))))
        isPoll = false;
    else if (rootNode.attributeValue("pause") != null)
        isPoll = false;
    HttpConnection connection = this.createConnection(rid, isSecure, isPoll, context);
    if (elements.size() > 0) {
        // creates the runnable to forward the packets
        packetsToSend.add(elements);
        new HttpPacketSender(this).init();
    }

    final String type = rootNode.attributeValue("type");
    String restartStream = rootNode
            .attributeValue(new QName("restart", rootNode.getNamespaceForPrefix("xmpp")));
    int pauseDuration = HttpBindServlet.getIntAttribute(rootNode.attributeValue("pause"), -1);

    if ("terminate".equals(type)) {
        connection.deliverBody(createEmptyBody(true), true);
        close();
        lastRequestID = connection.getRequestId();
    } else if ("true".equals(restartStream) && rootNode.elements().size() == 0) {
        connection.deliverBody(createSessionRestartResponse(), true);
        lastRequestID = connection.getRequestId();
    } else if (pauseDuration > 0 && pauseDuration <= getMaxPause()) {
        pause(pauseDuration);
        connection.deliverBody(createEmptyBody(false), true);
        lastRequestID = connection.getRequestId();
        setLastResponseEmpty(true);
    } else {
        resetInactivityTimeout();
    }
}

From source file:org.jivesoftware.openfire.net.SASLAuthentication.java

License:Open Source License

public static Element getSASLMechanismsElement(Session session) {
    if (!(session instanceof ClientSession) && !(session instanceof IncomingServerSession)) {
        return null;
    }//from  w  ww . j  a v  a  2 s.  c  om

    Element mechs = DocumentHelper
            .createElement(new QName("mechanisms", new Namespace("", "urn:ietf:params:xml:ns:xmpp-sasl")));
    if (session instanceof LocalIncomingServerSession) {
        // Server connections don't follow the same rules as clients
        if (session.isSecure()) {
            boolean haveTrustedCertificate = false;
            try {
                LocalIncomingServerSession svr = (LocalIncomingServerSession) session;
                X509Certificate trusted = CertificateManager.getEndEntityCertificate(
                        svr.getConnection().getPeerCertificates(), SSLConfig.getKeyStore(),
                        SSLConfig.gets2sTrustStore());
                haveTrustedCertificate = trusted != null;
                if (trusted != null && svr.getDefaultIdentity() != null) {
                    haveTrustedCertificate = verifyCertificate(trusted, svr.getDefaultIdentity());
                }
            } catch (IOException ex) {
                Log.warn(
                        "Exception occurred while trying to determine whether remote certificate is trusted. Treating as untrusted.",
                        ex);
            }
            if (haveTrustedCertificate) {
                // Offer SASL EXTERNAL only if TLS has already been negotiated and the peer has a trusted cert.
                Element mechanism = mechs.addElement("mechanism");
                mechanism.setText("EXTERNAL");
            }
        }
    } else {
        for (String mech : getSupportedMechanisms()) {
            Element mechanism = mechs.addElement("mechanism");
            mechanism.setText(mech);
        }
    }
    return mechs;
}

From source file:org.jivesoftware.openfire.plugin.Xep227Exporter.java

License:Apache License

/**
 * Adding offline messages, if there are some.
 * //w  w w  .j  a va2  s . c o m
 * @param hostname
 *            host name
 * @param userElement
 *            DOM element
 * @param userName
 *            user name
 */
@SuppressWarnings("unchecked")
private void exportOfflineMessages(String hostname, Element userElement, String userName) {
    Collection<OfflineMessage> offlineMessages = offlineMessagesStore.getMessages(userName, false);

    if (!offlineMessages.isEmpty()) {
        Element offlineElement = userElement.addElement(OFFLINE_MESSAGES_ELEMENT_NAME);

        for (OfflineMessage offMessage : offlineMessages) {

            Element messageElement = offlineElement.addElement(new QName(MESSAGE_ELEMENT_NAME, JABBER_MSG_NS));
            for (Object att : offMessage.getElement().attributes()) {
                Attribute attribute = (Attribute) att;
                messageElement.addAttribute(attribute.getQName(), attribute.getValue());
            }

            for (Iterator<Element> iterator = offMessage.getElement().elementIterator(); iterator.hasNext();) {
                Element element = iterator.next();
                messageElement.add(element.createCopy(new QName(element.getName(),
                        (element.getNamespace() == Namespace.NO_NAMESPACE ? JABBER_MSG_NS
                                : element.getNamespace()))));

            }

            /**
             * Adding delay element
             */
            Element delayElement = messageElement.addElement("delay", "urn:xmpp:delay");
            delayElement.addAttribute(FROM_NAME, hostname);
            delayElement.addAttribute("stamp", XMPPDateTimeFormat.format(offMessage.getCreationDate()));
            delayElement.addText("Offline Storage");
        }

    }

}

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;// w ww. ja va 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.intents.AppBuilder.java

License:Open Source License

protected Document createMuleConfig() {
    DocumentFactory factory = DocumentFactory.getInstance();
    Element root = factory.createElement(new QName("mule", muleNS));
    root.addAttribute("version", app.getPlatformVersion());
    return DocumentFactory.getInstance().createDocument(root);
}

From source file:org.mule.module.cxf.MuleSoapHeaders.java

License:Open Source License

public Element createHeaders() throws Exception {
    Element muleHeader = null;// www. j a v  a  2  s.  com

    if (correlationId != null || replyTo != null) {
        muleHeader = new DOMElement(new QName(MULE_HEADER, new Namespace(MULE_NAMESPACE, MULE_10_ACTOR)));
    } else {
        return null;
    }

    if (correlationId != null) {
        Node e = muleHeader.appendChild(new DOMElement(new QName(MuleProperties.MULE_CORRELATION_ID_PROPERTY,
                new Namespace(MULE_NAMESPACE, MULE_10_ACTOR))));
        e.setNodeValue(correlationId);

        e = muleHeader.appendChild(new DOMElement(new QName(MuleProperties.MULE_CORRELATION_GROUP_SIZE_PROPERTY,
                new Namespace(MULE_NAMESPACE, MULE_10_ACTOR))));
        e.setNodeValue(correlationGroup);

        e = muleHeader.appendChild(new DOMElement(new QName(MuleProperties.MULE_CORRELATION_SEQUENCE_PROPERTY,
                new Namespace(MULE_NAMESPACE, MULE_10_ACTOR))));
        e.setNodeValue(correlationSequence);
    }
    if (replyTo != null) {

        Node e = muleHeader.appendChild(new DOMElement(new QName(MuleProperties.MULE_REPLY_TO_PROPERTY,
                new Namespace(MULE_NAMESPACE, MULE_10_ACTOR))));
        e.setNodeValue(replyTo);
    }
    return muleHeader;
}

From source file:org.nuxeo.ecm.core.io.impl.transformers.SchemaRenamer.java

License:Open Source License

@Override
public boolean transform(ExportedDocument xdoc) throws IOException {
    Element root = xdoc.getDocument().getRootElement();

    List<Object> schemas = root.elements("schema");
    Element src = null;/* w w w  . j a v  a2 s .  c o  m*/
    if (schemas != null) {
        for (Object s : schemas) {
            Element schema = (Element) s;
            String name = schema.attribute("name").getText();
            if (srcSchema.equalsIgnoreCase(name)) {
                Namespace ns = new Namespace(dstPrefix, "http://www.nuxeo.org/ecm/schemas/" + dstSchema);
                schema.add(ns);
                schema.setAttributeValue("name", dstSchema);
                List<Element> fields = schema.elements();
                for (Element field : fields) {
                    field.setQName(new QName(field.getName(), ns));
                    ;
                }
            }
        }
    }
    return true;
}

From source file:org.nuxeo.ecm.jsf2.migration.parser.GenericParser.java

License:Open Source License

@Override
public void migrate(Document input) throws Exception {
    // Migrate the elements matching the rule
    if (rule.isMigrationAuto()) {
        for (Node node : listElementsToMigrate) {
            if (!StringUtils.isEmpty(rule.getNewValue())) {
                Element element = (Element) node;
                String newValue = rule.getNewValue();
                String prefix = null;
                if (newValue.contains(":")) {
                    String[] split = newValue.split(":");
                    prefix = split[0];/*from w  w  w  . ja va2s.  co  m*/
                    newValue = split[1];
                }
                element.setQName(new QName(newValue, input.getRootElement().getNamespaceForPrefix(prefix)));
            }
        }
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.restAPI.OpenSearchRestlet.java

License:Open Source License

@Override
public void handle(Request req, Response res) {

    CoreSession session;//from   ww w  .  j ava 2s.c  o  m
    try {
        Repository repository = Framework.getService(RepositoryManager.class).getDefaultRepository();
        if (repository == null) {
            throw new ClientException("Cannot get default repository");
        }
        Map<String, Serializable> context = new HashMap<String, Serializable>();
        context.put("principal", getSerializablePrincipal(req));
        session = repository.open(context);
    } catch (Exception e) {
        handleError(res, e);
        return;
    }
    try {
        // read the search term passed as the 'q' request parameter
        String keywords = getQueryParamValue(req, "q", " ");

        // perform the search on the fulltext index and wrap the results as
        // a DocumentModelList with the 10 first matching results ordered by
        // modification time
        String query = String.format(QUERY, keywords);
        DocumentModelList documents = session.query(query, null, MAX, 0, true);

        // build the RSS 2.0 response document holding the results
        DOMDocumentFactory domFactory = new DOMDocumentFactory();
        DOMDocument resultDocument = (DOMDocument) domFactory.createDocument();

        // rss root tag
        Element rssElement = resultDocument.addElement(RSS_TAG);
        rssElement.addAttribute("version", "2.0");
        rssElement.addNamespace(OPENSEARCH_NS.getPrefix(), OPENSEARCH_NS.getURI());
        rssElement.addNamespace(ATOM_NS.getPrefix(), ATOM_NS.getURI());

        // channel with OpenSearch metadata
        Element channelElement = rssElement.addElement(CHANNEL_TAG);

        channelElement.addElement(TITLE_TAG).setText("Nuxeo EP OpenSearch channel for " + keywords);
        channelElement.addElement("link").setText(BaseURL.getBaseURL(getHttpRequest(req))
                + "restAPI/opensearch?q=" + URLEncoder.encode(keywords, "UTF-8"));
        channelElement.addElement(new QName("totalResults", OPENSEARCH_NS))
                .setText(Long.toString(documents.totalSize()));
        channelElement.addElement(new QName("startIndex", OPENSEARCH_NS)).setText("0");
        channelElement.addElement(new QName("itemsPerPage", OPENSEARCH_NS))
                .setText(Integer.toString(documents.size()));

        Element queryElement = channelElement.addElement(new QName("Query", OPENSEARCH_NS));
        queryElement.addAttribute("role", "request");
        queryElement.addAttribute("searchTerms", keywords);
        queryElement.addAttribute("startPage", Integer.toString(1));

        // document items
        String baseUrl = BaseURL.getBaseURL(getHttpRequest(req));

        for (DocumentModel doc : documents) {
            Element itemElement = channelElement.addElement(ITEM_TAG);
            Element titleElement = itemElement.addElement(TITLE_TAG);
            String title = doc.getTitle();
            if (title != null) {
                titleElement.setText(title);
            }
            Element descriptionElement = itemElement.addElement(DESCRIPTION_TAG);
            String description = doc.getProperty("dublincore:description").getValue(String.class);
            if (description != null) {
                descriptionElement.setText(description);
            }
            Element linkElement = itemElement.addElement("link");
            linkElement.setText(baseUrl + DocumentModelFunctions.documentUrl(doc));
        }

        Representation rep = new StringRepresentation(resultDocument.asXML(), MediaType.APPLICATION_XML);
        rep.setCharacterSet(CharacterSet.UTF_8);
        res.setEntity(rep);

    } catch (Exception e) {
        handleError(res, e);
    } finally {
        try {
            Repository.close(session);
        } catch (Exception e) {
            log.error("Repository close failed", e);
        }
    }
}

From source file:org.openbravo.dal.xml.XMLUtil.java

License:Open Source License

/**
 * Creates a standard Openbravo root element for a xml document and set ths namespace. Ads the new
 * root element to the Dom4j document.//from ww w.  j a va  2  s .c  o m
 * 
 * @param doc
 *          the Dom4j document to set the root element
 * @param elementName
 *          the name of the root element
 * @return the new root element
 */
public Element addRootElement(Document doc, String elementName) {
    final Namespace ns = new Namespace("ob", "http://www.openbravo.com");
    final QName qName = new QName(elementName, ns);
    final Element root = doc.addElement(qName);
    root.addNamespace("ob", "http://www.openbravo.com");
    return root;
}